org.el 804 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2020 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Bastien Guerry <bzg@gnu.org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Version: 9.3.6
  10. ;;
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the homepage of
  55. ;; Org mode, you can read the same text online as HTML. There is also an
  56. ;; excellent reference card made by Philip Rooke. This card can be found
  57. ;; in the doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar org-inlinetask-min-level)
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (eval-and-compile (require 'org-macs))
  82. (require 'org-compat)
  83. (require 'org-keys)
  84. (require 'ol)
  85. (require 'org-table)
  86. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  87. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  88. (defvar org-outline-regexp "\\*+ "
  89. "Regexp to match Org headlines.")
  90. (defvar org-outline-regexp-bol "^\\*+ "
  91. "Regexp to match Org headlines.
  92. This is similar to `org-outline-regexp' but additionally makes
  93. sure that we are at the beginning of the line.")
  94. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  95. "Matches a headline, putting stars and text into groups.
  96. Stars are put in group 1 and the trimmed body in group 2.")
  97. (declare-function calendar-check-holidays "holidays" (date))
  98. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  99. (declare-function cdlatex-math-symbol "ext:cdlatex")
  100. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  105. (declare-function org-agenda-redo "org-agenda" (&optional all))
  106. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  107. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  108. (declare-function org-archive-subtree-default "org-archive" ())
  109. (declare-function org-archive-to-archive-sibling "org-archive" ())
  110. (declare-function org-attach "org-attach" ())
  111. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  112. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  113. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  114. (declare-function org-clock-cancel "org-clock" ())
  115. (declare-function org-clock-display "org-clock" (&optional arg))
  116. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  117. (declare-function org-clock-goto "org-clock" (&optional select))
  118. (declare-function org-clock-in "org-clock" (&optional select start-time))
  119. (declare-function org-clock-in-last "org-clock" (&optional arg))
  120. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  121. (declare-function org-clock-out-if-current "org-clock" ())
  122. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  123. (declare-function org-clock-report "org-clock" (&optional arg))
  124. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  125. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  126. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  127. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  128. (declare-function org-clock-update-time-maybe "org-clock" ())
  129. (declare-function org-clocking-buffer "org-clock" ())
  130. (declare-function org-clocktable-shift "org-clock" (dir n))
  131. (declare-function org-columns-insert-dblock "org-colview" ())
  132. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  133. (declare-function org-element-at-point "org-element" ())
  134. (declare-function org-element-cache-refresh "org-element" (pos))
  135. (declare-function org-element-cache-reset "org-element" (&optional all))
  136. (declare-function org-element-contents "org-element" (element))
  137. (declare-function org-element-context "org-element" (&optional element))
  138. (declare-function org-element-copy "org-element" (datum))
  139. (declare-function org-element-create "org-element" (type &optional props &rest children))
  140. (declare-function org-element-interpret-data "org-element" (data))
  141. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  142. (declare-function org-element-link-parser "org-element" ())
  143. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  144. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  145. (declare-function org-element-property "org-element" (property element))
  146. (declare-function org-element-put-property "org-element" (element property value))
  147. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  148. (declare-function org-element-timestamp-parser "org-element" ())
  149. (declare-function org-element-type "org-element" (element))
  150. (declare-function org-export-dispatch "ox" (&optional arg))
  151. (declare-function org-export-get-backend "ox" (name))
  152. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  153. (declare-function org-feed-goto-inbox "org-feed" (feed))
  154. (declare-function org-feed-update-all "org-feed" ())
  155. (declare-function org-goto "org-goto" (&optional alternative-interface))
  156. (declare-function org-id-find-id-file "org-id" (id))
  157. (declare-function org-id-get-create "org-id" (&optional force))
  158. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  159. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  160. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  161. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  162. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  163. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  164. (declare-function org-timer "org-timer" (&optional restart no-insert))
  165. (declare-function org-timer-item "org-timer" (&optional arg))
  166. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  167. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  168. (declare-function org-timer-start "org-timer" (&optional offset))
  169. (declare-function org-timer-stop "org-timer" ())
  170. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  171. (declare-function org-update-radio-target-regexp "ol" ())
  172. (defvar ffap-url-regexp)
  173. (defvar org-element-paragraph-separate)
  174. (defvar org-indent-indentation-per-level)
  175. (defvar org-radio-target-regexp)
  176. (defvar org-target-link-regexp)
  177. (defvar org-target-regexp)
  178. ;; load languages based on value of `org-babel-load-languages'
  179. (defvar org-babel-load-languages)
  180. ;;;###autoload
  181. (defun org-babel-do-load-languages (sym value)
  182. "Load the languages defined in `org-babel-load-languages'."
  183. (set-default sym value)
  184. (dolist (pair org-babel-load-languages)
  185. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  186. (if active
  187. (require (intern (concat "ob-" lang)))
  188. (fmakunbound
  189. (intern (concat "org-babel-execute:" lang)))
  190. (fmakunbound
  191. (intern (concat "org-babel-expand-body:" lang)))))))
  192. ;;;###autoload
  193. (defun org-babel-load-file (file &optional compile)
  194. "Load Emacs Lisp source code blocks in the Org FILE.
  195. This function exports the source code using `org-babel-tangle'
  196. and then loads the resulting file using `load-file'. With
  197. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  198. byte-compiled before it is loaded."
  199. (interactive "fFile to load: \nP")
  200. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  201. ;; Tangle only if the Org file is newer than the Elisp file.
  202. (unless (org-file-newer-than-p
  203. tangled-file
  204. (file-attribute-modification-time
  205. (file-attributes (file-truename file))))
  206. (org-babel-tangle-file file tangled-file "emacs-lisp"))
  207. (if compile
  208. (progn
  209. (byte-compile-file tangled-file 'load)
  210. (message "Compiled and loaded %s" tangled-file))
  211. (load-file tangled-file)
  212. (message "Loaded %s" tangled-file))))
  213. (defcustom org-babel-load-languages '((emacs-lisp . t))
  214. "Languages which can be evaluated in Org buffers.
  215. \\<org-mode-map>
  216. This list can be used to load support for any of the languages
  217. below. Each language will depend on a different set of system
  218. executables and/or Emacs modes.
  219. When a language is \"loaded\", code blocks in that language can
  220. be evaluated with `org-babel-execute-src-block', which is bound
  221. by default to \\[org-ctrl-c-ctrl-c].
  222. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  223. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  224. default, only Emacs Lisp is loaded, since it has no specific
  225. requirement."
  226. :group 'org-babel
  227. :set 'org-babel-do-load-languages
  228. :version "24.1"
  229. :type '(alist :tag "Babel Languages"
  230. :key-type
  231. (choice
  232. (const :tag "Awk" awk)
  233. (const :tag "C" C)
  234. (const :tag "R" R)
  235. (const :tag "Asymptote" asymptote)
  236. (const :tag "Calc" calc)
  237. (const :tag "Clojure" clojure)
  238. (const :tag "CSS" css)
  239. (const :tag "Ditaa" ditaa)
  240. (const :tag "Dot" dot)
  241. (const :tag "Ebnf2ps" ebnf2ps)
  242. (const :tag "Emacs Lisp" emacs-lisp)
  243. (const :tag "Forth" forth)
  244. (const :tag "Fortran" fortran)
  245. (const :tag "Gnuplot" gnuplot)
  246. (const :tag "Haskell" haskell)
  247. (const :tag "hledger" hledger)
  248. (const :tag "IO" io)
  249. (const :tag "J" J)
  250. (const :tag "Java" java)
  251. (const :tag "Javascript" js)
  252. (const :tag "LaTeX" latex)
  253. (const :tag "Ledger" ledger)
  254. (const :tag "Lilypond" lilypond)
  255. (const :tag "Lisp" lisp)
  256. (const :tag "Makefile" makefile)
  257. (const :tag "Maxima" maxima)
  258. (const :tag "Matlab" matlab)
  259. (const :tag "Mscgen" mscgen)
  260. (const :tag "Ocaml" ocaml)
  261. (const :tag "Octave" octave)
  262. (const :tag "Org" org)
  263. (const :tag "Perl" perl)
  264. (const :tag "Pico Lisp" picolisp)
  265. (const :tag "PlantUML" plantuml)
  266. (const :tag "Python" python)
  267. (const :tag "Ruby" ruby)
  268. (const :tag "Sass" sass)
  269. (const :tag "Scala" scala)
  270. (const :tag "Scheme" scheme)
  271. (const :tag "Screen" screen)
  272. (const :tag "Shell Script" shell)
  273. (const :tag "Shen" shen)
  274. (const :tag "Sql" sql)
  275. (const :tag "Sqlite" sqlite)
  276. (const :tag "Stan" stan)
  277. (const :tag "Vala" vala))
  278. :value-type (boolean :tag "Activate" :value t)))
  279. ;;;; Customization variables
  280. (defcustom org-clone-delete-id nil
  281. "Remove ID property of clones of a subtree.
  282. When non-nil, clones of a subtree don't inherit the ID property.
  283. Otherwise they inherit the ID property with a new unique
  284. identifier."
  285. :type 'boolean
  286. :version "24.1"
  287. :group 'org-id)
  288. ;;; Version
  289. (org-check-version)
  290. ;;;###autoload
  291. (defun org-version (&optional here full message)
  292. "Show the Org version.
  293. Interactively, or when MESSAGE is non-nil, show it in echo area.
  294. With prefix argument, or when HERE is non-nil, insert it at point.
  295. In non-interactive uses, a reduced version string is output unless
  296. FULL is given."
  297. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  298. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  299. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  300. (load-suffixes (list ".el"))
  301. (org-install-dir
  302. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  303. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  304. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  305. (let* ((load-suffixes save-load-suffixes)
  306. (release (org-release))
  307. (git-version (org-git-version))
  308. (version (format "Org mode version %s (%s @ %s)"
  309. release
  310. git-version
  311. (if org-install-dir
  312. (if (string= org-dir org-install-dir)
  313. org-install-dir
  314. (concat "mixed installation! "
  315. org-install-dir
  316. " and "
  317. org-dir))
  318. "org-loaddefs.el can not be found!")))
  319. (version1 (if full version release)))
  320. (when here (insert version1))
  321. (when message (message "%s" version1))
  322. version1)))
  323. (defconst org-version (org-version))
  324. ;;; Syntax Constants
  325. ;;;; Block
  326. (defconst org-block-regexp
  327. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  328. "Regular expression for hiding blocks.")
  329. (defconst org-dblock-start-re
  330. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  331. "Matches the start line of a dynamic block, with parameters.")
  332. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  333. "Matches the end of a dynamic block.")
  334. ;;;; Clock and Planning
  335. (defconst org-clock-string "CLOCK:"
  336. "String used as prefix for timestamps clocking work hours on an item.")
  337. (defvar org-closed-string "CLOSED:"
  338. "String used as the prefix for timestamps logging closing a TODO entry.")
  339. (defvar org-deadline-string "DEADLINE:"
  340. "String to mark deadline entries.
  341. \\<org-mode-map>
  342. A deadline is this string, followed by a time stamp. It must be
  343. a word, terminated by a colon. You can insert a schedule keyword
  344. and a timestamp with `\\[org-deadline]'.")
  345. (defvar org-scheduled-string "SCHEDULED:"
  346. "String to mark scheduled TODO entries.
  347. \\<org-mode-map>
  348. A schedule is this string, followed by a time stamp. It must be
  349. a word, terminated by a colon. You can insert a schedule keyword
  350. and a timestamp with `\\[org-schedule]'.")
  351. (defconst org-ds-keyword-length
  352. (+ 2
  353. (apply #'max
  354. (mapcar #'length
  355. (list org-deadline-string org-scheduled-string
  356. org-clock-string org-closed-string))))
  357. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  358. (defconst org-planning-line-re
  359. (concat "^[ \t]*"
  360. (regexp-opt
  361. (list org-closed-string org-deadline-string org-scheduled-string)
  362. t))
  363. "Matches a line with planning info.
  364. Matched keyword is in group 1.")
  365. (defconst org-clock-line-re
  366. (concat "^[ \t]*" org-clock-string)
  367. "Matches a line with clock info.")
  368. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  369. "Matches the DEADLINE keyword.")
  370. (defconst org-deadline-time-regexp
  371. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  372. "Matches the DEADLINE keyword together with a time stamp.")
  373. (defconst org-deadline-time-hour-regexp
  374. (concat "\\<" org-deadline-string
  375. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  376. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  377. (defconst org-deadline-line-regexp
  378. (concat "\\<\\(" org-deadline-string "\\).*")
  379. "Matches the DEADLINE keyword and the rest of the line.")
  380. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  381. "Matches the SCHEDULED keyword.")
  382. (defconst org-scheduled-time-regexp
  383. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  384. "Matches the SCHEDULED keyword together with a time stamp.")
  385. (defconst org-scheduled-time-hour-regexp
  386. (concat "\\<" org-scheduled-string
  387. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  388. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  389. (defconst org-closed-time-regexp
  390. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  391. "Matches the CLOSED keyword together with a time stamp.")
  392. (defconst org-keyword-time-regexp
  393. (concat "\\<"
  394. (regexp-opt
  395. (list org-scheduled-string org-deadline-string org-closed-string
  396. org-clock-string)
  397. t)
  398. " *[[<]\\([^]>]+\\)[]>]")
  399. "Matches any of the 4 keywords, together with the time stamp.")
  400. (defconst org-keyword-time-not-clock-regexp
  401. (concat
  402. "\\<"
  403. (regexp-opt
  404. (list org-scheduled-string org-deadline-string org-closed-string) t)
  405. " *[[<]\\([^]>]+\\)[]>]")
  406. "Matches any of the 3 keywords, together with the time stamp.")
  407. (defconst org-maybe-keyword-time-regexp
  408. (concat "\\(\\<"
  409. (regexp-opt
  410. (list org-scheduled-string org-deadline-string org-closed-string
  411. org-clock-string)
  412. t)
  413. "\\)?"
  414. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  415. "\\|"
  416. "<%%([^\r\n>]*>\\)")
  417. "Matches a timestamp, possibly preceded by a keyword.")
  418. (defconst org-all-time-keywords
  419. (mapcar (lambda (w) (substring w 0 -1))
  420. (list org-scheduled-string org-deadline-string
  421. org-clock-string org-closed-string))
  422. "List of time keywords.")
  423. ;;;; Drawer
  424. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  425. "Matches first or last line of a hidden block.
  426. Group 1 contains drawer's name or \"END\".")
  427. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  428. "Regular expression matching the first line of a property drawer.")
  429. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  430. "Regular expression matching the last line of a property drawer.")
  431. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  432. "Regular expression matching the first line of a clock drawer.")
  433. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  434. "Regular expression matching the last line of a clock drawer.")
  435. (defconst org-property-drawer-re
  436. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  437. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  438. "[ \t]*:END:[ \t]*$")
  439. "Matches an entire property drawer.")
  440. (defconst org-clock-drawer-re
  441. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  442. org-clock-drawer-end-re "\\)\n?")
  443. "Matches an entire clock drawer.")
  444. ;;;; Headline
  445. (defconst org-heading-keyword-regexp-format
  446. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  447. "Printf format for a regexp matching a headline with some keyword.
  448. This regexp will match the headline of any node which has the
  449. exact keyword that is put into the format. The keyword isn't in
  450. any group by default, but the stars and the body are.")
  451. (defconst org-heading-keyword-maybe-regexp-format
  452. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  453. "Printf format for a regexp matching a headline, possibly with some keyword.
  454. This regexp can match any headline with the specified keyword, or
  455. without a keyword. The keyword isn't in any group by default,
  456. but the stars and the body are.")
  457. (defconst org-archive-tag "ARCHIVE"
  458. "The tag that marks a subtree as archived.
  459. An archived subtree does not open during visibility cycling, and does
  460. not contribute to the agenda listings.")
  461. (defconst org-tag-re "[[:alnum:]_@#%]+"
  462. "Regexp matching a single tag.")
  463. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  464. "Regexp matching the tag group at the end of a line, with leading spaces.
  465. Tags are stored in match group 1. Match group 2 stores the tags
  466. without the enclosing colons.")
  467. (defconst org-tag-line-re
  468. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  469. "Regexp matching tags in a headline.
  470. Tags are stored in match group 1. Match group 2 stores the tags
  471. without the enclosing colons.")
  472. (eval-and-compile
  473. (defconst org-comment-string "COMMENT"
  474. "Entries starting with this keyword will never be exported.
  475. \\<org-mode-map>
  476. An entry can be toggled between COMMENT and normal with
  477. `\\[org-toggle-comment]'."))
  478. ;;;; LaTeX Environments and Fragments
  479. (defconst org-latex-regexps
  480. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  481. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  482. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  483. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  484. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  485. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  486. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  487. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  488. "Regular expressions for matching embedded LaTeX.")
  489. ;;;; Node Property
  490. (defconst org-effort-property "Effort"
  491. "The property that is being used to keep track of effort estimates.
  492. Effort estimates given in this property need to have the format H:MM.")
  493. ;;;; Timestamp
  494. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  495. "Regular expression for fast time stamp matching.")
  496. (defconst org-ts-regexp-inactive
  497. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  498. "Regular expression for fast inactive time stamp matching.")
  499. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  500. "Regular expression for fast time stamp matching.")
  501. (defconst org-ts-regexp0
  502. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  503. "Regular expression matching time strings for analysis.
  504. This one does not require the space after the date, so it can be used
  505. on a string that terminates immediately after the date.")
  506. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  507. "Regular expression matching time strings for analysis.")
  508. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  509. "Regular expression matching time stamps, with groups.")
  510. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  511. "Regular expression matching time stamps (also [..]), with groups.")
  512. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  513. "Regular expression matching a time stamp range.")
  514. (defconst org-tr-regexp-both
  515. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  516. "Regular expression matching a time stamp range.")
  517. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  518. org-ts-regexp "\\)?")
  519. "Regular expression matching a time stamp or time stamp range.")
  520. (defconst org-tsr-regexp-both
  521. (concat org-ts-regexp-both "\\(--?-?"
  522. org-ts-regexp-both "\\)?")
  523. "Regular expression matching a time stamp or time stamp range.
  524. The time stamps may be either active or inactive.")
  525. (defconst org-repeat-re
  526. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  527. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  528. "Regular expression for specifying repeated events.
  529. After a match, group 1 contains the repeat expression.")
  530. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  531. "Formats for `format-time-string' which are used for time stamps.")
  532. ;;; The custom variables
  533. (defgroup org nil
  534. "Outline-based notes management and organizer."
  535. :tag "Org"
  536. :group 'outlines
  537. :group 'calendar)
  538. (defcustom org-mode-hook nil
  539. "Mode hook for Org mode, run after the mode was turned on."
  540. :group 'org
  541. :type 'hook)
  542. (defcustom org-load-hook nil
  543. "Hook that is run after org.el has been loaded."
  544. :group 'org
  545. :type 'hook)
  546. (defcustom org-log-buffer-setup-hook nil
  547. "Hook that is run after an Org log buffer is created."
  548. :group 'org
  549. :version "24.1"
  550. :type 'hook)
  551. (defvar org-modules) ; defined below
  552. (defvar org-modules-loaded nil
  553. "Have the modules been loaded already?")
  554. (defun org-load-modules-maybe (&optional force)
  555. "Load all extensions listed in `org-modules'."
  556. (when (or force (not org-modules-loaded))
  557. (dolist (ext org-modules)
  558. (condition-case nil (require ext)
  559. (error (message "Problems while trying to load feature `%s'" ext))))
  560. (setq org-modules-loaded t)))
  561. (defun org-set-modules (var value)
  562. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  563. (set var value)
  564. (when (featurep 'org)
  565. (org-load-modules-maybe 'force)
  566. (org-element-cache-reset 'all)))
  567. (defcustom org-modules '(ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  568. "Modules that should always be loaded together with org.el.
  569. If a description starts with <C>, the file is not part of Emacs
  570. and loading it will require that you have downloaded and properly
  571. installed the Org mode distribution.
  572. You can also use this system to load external packages (i.e. neither Org
  573. core modules, nor modules from the CONTRIB directory). Just add symbols
  574. to the end of the list. If the package is called org-xyz.el, then you need
  575. to add the symbol `xyz', and the package must have a call to:
  576. (provide \\='org-xyz)
  577. For export specific modules, see also `org-export-backends'."
  578. :group 'org
  579. :set 'org-set-modules
  580. :version "26.1"
  581. :package-version '(Org . "9.2")
  582. :type
  583. '(set :greedy t
  584. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  585. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  586. (const :tag " crypt: Encryption of subtrees" org-crypt)
  587. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  588. (const :tag " docview: Links to Docview buffers" ol-docview)
  589. (const :tag " eww: Store link to URL of Eww" ol-eww)
  590. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  591. (const :tag " habit: Track your consistency with habits" org-habit)
  592. (const :tag " id: Global IDs for identifying entries" org-id)
  593. (const :tag " info: Links to Info nodes" ol-info)
  594. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  595. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  596. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  597. (const :tag " mouse: Additional mouse support" org-mouse)
  598. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  599. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  600. (const :tag " tempo: Fast completion for structures" org-tempo)
  601. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  602. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  603. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  604. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  605. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  606. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  607. (const :tag "C collector: Collect properties into tables" org-collector)
  608. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  609. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  610. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  611. (const :tag "C eval: Include command output as text" org-eval)
  612. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  613. (const :tag "C git-link: Links to specific file version" ol-git-link)
  614. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  615. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  616. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  617. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  618. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  619. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  620. (const :tag "C man: Links to man pages in Org mode" ol-man)
  621. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  622. (const :tag "C notify: Notifications for Org mode" org-notify)
  623. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  624. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  625. (const :tag "C registry: A registry for Org links" org-registry)
  626. (const :tag "C screen: Visit screen sessions through links" org-screen)
  627. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  628. (const :tag "C secretary: Team management with Org" org-secretary)
  629. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  630. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  631. (const :tag "C track: Keep up with Org mode development" org-track)
  632. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  633. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  634. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  635. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  636. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  637. (defvar org-export-registered-backends) ; From ox.el.
  638. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  639. (declare-function org-export-backend-name "ox" (backend) t)
  640. (defcustom org-export-backends '(ascii html icalendar latex odt)
  641. "List of export back-ends that should be always available.
  642. If a description starts with <C>, the file is not part of Emacs
  643. and loading it will require that you have downloaded and properly
  644. installed the Org mode distribution.
  645. Unlike to `org-modules', libraries in this list will not be
  646. loaded along with Org, but only once the export framework is
  647. needed.
  648. This variable needs to be set before org.el is loaded. If you
  649. need to make a change while Emacs is running, use the customize
  650. interface or run the following code, where VAL stands for the new
  651. value of the variable, after updating it:
  652. (progn
  653. (setq org-export-registered-backends
  654. (cl-remove-if-not
  655. (lambda (backend)
  656. (let ((name (org-export-backend-name backend)))
  657. (or (memq name val)
  658. (catch \\='parentp
  659. (dolist (b val)
  660. (and (org-export-derived-backend-p b name)
  661. (throw \\='parentp t)))))))
  662. org-export-registered-backends))
  663. (let ((new-list (mapcar #\\='org-export-backend-name
  664. org-export-registered-backends)))
  665. (dolist (backend val)
  666. (cond
  667. ((not (load (format \"ox-%s\" backend) t t))
  668. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  669. backend))
  670. ((not (memq backend new-list)) (push backend new-list))))
  671. (set-default \\='org-export-backends new-list)))
  672. Adding a back-end to this list will also pull the back-end it
  673. depends on, if any."
  674. :group 'org
  675. :group 'org-export
  676. :version "26.1"
  677. :package-version '(Org . "9.0")
  678. :initialize 'custom-initialize-set
  679. :set (lambda (var val)
  680. (if (not (featurep 'ox)) (set-default var val)
  681. ;; Any back-end not required anymore (not present in VAL and not
  682. ;; a parent of any back-end in the new value) is removed from the
  683. ;; list of registered back-ends.
  684. (setq org-export-registered-backends
  685. (cl-remove-if-not
  686. (lambda (backend)
  687. (let ((name (org-export-backend-name backend)))
  688. (or (memq name val)
  689. (catch 'parentp
  690. (dolist (b val)
  691. (and (org-export-derived-backend-p b name)
  692. (throw 'parentp t)))))))
  693. org-export-registered-backends))
  694. ;; Now build NEW-LIST of both new back-ends and required
  695. ;; parents.
  696. (let ((new-list (mapcar #'org-export-backend-name
  697. org-export-registered-backends)))
  698. (dolist (backend val)
  699. (cond
  700. ((not (load (format "ox-%s" backend) t t))
  701. (message "Problems while trying to load export back-end `%s'"
  702. backend))
  703. ((not (memq backend new-list)) (push backend new-list))))
  704. ;; Set VAR to that list with fixed dependencies.
  705. (set-default var new-list))))
  706. :type '(set :greedy t
  707. (const :tag " ascii Export buffer to ASCII format" ascii)
  708. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  709. (const :tag " html Export buffer to HTML format" html)
  710. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  711. (const :tag " latex Export buffer to LaTeX format" latex)
  712. (const :tag " man Export buffer to MAN format" man)
  713. (const :tag " md Export buffer to Markdown format" md)
  714. (const :tag " odt Export buffer to ODT format" odt)
  715. (const :tag " org Export buffer to Org format" org)
  716. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  717. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  718. (const :tag "C deck Export buffer to deck.js presentations" deck)
  719. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  720. (const :tag "C groff Export buffer to Groff format" groff)
  721. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  722. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  723. (const :tag "C s5 Export buffer to s5 presentations" s5)
  724. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  725. (eval-after-load 'ox
  726. '(dolist (backend org-export-backends)
  727. (condition-case nil (require (intern (format "ox-%s" backend)))
  728. (error (message "Problems while trying to load export back-end `%s'"
  729. backend)))))
  730. (defcustom org-support-shift-select nil
  731. "Non-nil means make shift-cursor commands select text when possible.
  732. \\<org-mode-map>
  733. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  734. start selecting a region, or enlarge regions started in this way.
  735. In Org mode, in special contexts, these same keys are used for
  736. other purposes, important enough to compete with shift selection.
  737. Org tries to balance these needs by supporting `shift-select-mode'
  738. outside these special contexts, under control of this variable.
  739. The default of this variable is nil, to avoid confusing behavior. Shifted
  740. cursor keys will then execute Org commands in the following contexts:
  741. - on a headline, changing TODO state (left/right) and priority (up/down)
  742. - on a time stamp, changing the time
  743. - in a plain list item, changing the bullet type
  744. - in a property definition line, switching between allowed values
  745. - in the BEGIN line of a clock table (changing the time block).
  746. Outside these contexts, the commands will throw an error.
  747. When this variable is t and the cursor is not in a special
  748. context, Org mode will support shift-selection for making and
  749. enlarging regions. To make this more effective, the bullet
  750. cycling will no longer happen anywhere in an item line, but only
  751. if the cursor is exactly on the bullet.
  752. If you set this variable to the symbol `always', then the keys
  753. will not be special in headlines, property lines, and item lines,
  754. to make shift selection work there as well. If this is what you
  755. want, you can use the following alternative commands:
  756. `\\[org-todo]' and `\\[org-priority]' \
  757. to change TODO state and priority,
  758. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  759. can be used to switch TODO sets,
  760. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  761. and properties can be edited by hand or in column view.
  762. However, when the cursor is on a timestamp, shift-cursor commands
  763. will still edit the time stamp - this is just too good to give up."
  764. :group 'org
  765. :type '(choice
  766. (const :tag "Never" nil)
  767. (const :tag "When outside special context" t)
  768. (const :tag "Everywhere except timestamps" always)))
  769. (defcustom org-loop-over-headlines-in-active-region nil
  770. "Shall some commands act upon headlines in the active region?
  771. When set to t, some commands will be performed in all headlines
  772. within the active region.
  773. When set to `start-level', some commands will be performed in all
  774. headlines within the active region, provided that these headlines
  775. are of the same level than the first one.
  776. When set to a string, those commands will be performed on the
  777. matching headlines within the active region. Such string must be
  778. a tags/property/todo match as it is used in the agenda tags view.
  779. The list of commands is: `org-schedule', `org-deadline',
  780. `org-todo', `org-set-tags-command', `org-archive-subtree',
  781. `org-archive-set-tag', `org-toggle-archive-tag' and
  782. `org-archive-to-archive-sibling'. The archiving commands skip
  783. already archived entries."
  784. :type '(choice (const :tag "Don't loop" nil)
  785. (const :tag "All headlines in active region" t)
  786. (const :tag "In active region, headlines at the same level than the first one" start-level)
  787. (string :tag "Tags/Property/Todo matcher"))
  788. :version "24.1"
  789. :group 'org-todo
  790. :group 'org-archive)
  791. (defcustom org-startup-folded t
  792. "Non-nil means entering Org mode will switch to OVERVIEW.
  793. This can also be configured on a per-file basis by adding one of
  794. the following lines anywhere in the buffer:
  795. #+STARTUP: fold (or `overview', this is equivalent)
  796. #+STARTUP: nofold (or `showall', this is equivalent)
  797. #+STARTUP: content
  798. #+STARTUP: showeverything
  799. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  800. to ignore this option when Org opens agenda files for the first
  801. time."
  802. :group 'org-startup
  803. :type '(choice
  804. (const :tag "nofold: show all" nil)
  805. (const :tag "fold: overview" t)
  806. (const :tag "content: all headlines" content)
  807. (const :tag "show everything, even drawers" showeverything)))
  808. (defcustom org-startup-truncated t
  809. "Non-nil means entering Org mode will set `truncate-lines'.
  810. This is useful since some lines containing links can be very long and
  811. uninteresting. Also tables look terrible when wrapped.
  812. The variable `org-startup-truncated' allows to configure
  813. truncation for Org mode different to the other modes that use the
  814. variable `truncate-lines' and as a shortcut instead of putting
  815. the variable `truncate-lines' into the `org-mode-hook'. If one
  816. wants to configure truncation for Org mode not statically but
  817. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  818. the variable `truncate-lines' has to be used because in such a
  819. case it is too late to set the variable `org-startup-truncated'."
  820. :group 'org-startup
  821. :type 'boolean)
  822. (defcustom org-startup-indented nil
  823. "Non-nil means turn on `org-indent-mode' on startup.
  824. This can also be configured on a per-file basis by adding one of
  825. the following lines anywhere in the buffer:
  826. #+STARTUP: indent
  827. #+STARTUP: noindent"
  828. :group 'org-structure
  829. :type '(choice
  830. (const :tag "Not" nil)
  831. (const :tag "Globally (slow on startup in large files)" t)))
  832. (defcustom org-use-sub-superscripts t
  833. "Non-nil means interpret \"_\" and \"^\" for display.
  834. If you want to control how Org exports those characters, see
  835. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  836. used to be an alias for `org-export-with-sub-superscripts' in
  837. Org <8.0, it is not anymore.
  838. When this option is turned on, you can use TeX-like syntax for
  839. sub- and superscripts within the buffer. Several characters after
  840. \"_\" or \"^\" will be considered as a single item - so grouping
  841. with {} is normally not needed. For example, the following things
  842. will be parsed as single sub- or superscripts:
  843. 10^24 or 10^tau several digits will be considered 1 item.
  844. 10^-12 or 10^-tau a leading sign with digits or a word
  845. x^2-y^3 will be read as x^2 - y^3, because items are
  846. terminated by almost any nonword/nondigit char.
  847. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  848. Still, ambiguity is possible. So when in doubt, use {} to enclose
  849. the sub/superscript. If you set this variable to the symbol `{}',
  850. the braces are *required* in order to trigger interpretations as
  851. sub/superscript. This can be helpful in documents that need \"_\"
  852. frequently in plain text."
  853. :group 'org-startup
  854. :version "24.4"
  855. :package-version '(Org . "8.0")
  856. :type '(choice
  857. (const :tag "Always interpret" t)
  858. (const :tag "Only with braces" {})
  859. (const :tag "Never interpret" nil)))
  860. (defcustom org-startup-with-beamer-mode nil
  861. "Non-nil means turn on `org-beamer-mode' on startup.
  862. This can also be configured on a per-file basis by adding one of
  863. the following lines anywhere in the buffer:
  864. #+STARTUP: beamer"
  865. :group 'org-startup
  866. :version "24.1"
  867. :type 'boolean)
  868. (defcustom org-startup-align-all-tables nil
  869. "Non-nil means align all tables when visiting a file.
  870. This can also be configured on a per-file basis by adding one of
  871. the following lines anywhere in the buffer:
  872. #+STARTUP: align
  873. #+STARTUP: noalign"
  874. :group 'org-startup
  875. :type 'boolean)
  876. (defcustom org-startup-shrink-all-tables nil
  877. "Non-nil means shrink all table columns with a width cookie.
  878. This can also be configured on a per-file basis by adding one of
  879. the following lines anywhere in the buffer:
  880. #+STARTUP: shrink"
  881. :group 'org-startup
  882. :type 'boolean
  883. :version "27.1"
  884. :package-version '(Org . "9.2")
  885. :safe #'booleanp)
  886. (defcustom org-startup-with-inline-images nil
  887. "Non-nil means show inline images when loading a new Org file.
  888. This can also be configured on a per-file basis by adding one of
  889. the following lines anywhere in the buffer:
  890. #+STARTUP: inlineimages
  891. #+STARTUP: noinlineimages"
  892. :group 'org-startup
  893. :version "24.1"
  894. :type 'boolean)
  895. (defcustom org-startup-with-latex-preview nil
  896. "Non-nil means preview LaTeX fragments when loading a new Org file.
  897. This can also be configured on a per-file basis by adding one of
  898. the following lines anywhere in the buffer:
  899. #+STARTUP: latexpreview
  900. #+STARTUP: nolatexpreview"
  901. :group 'org-startup
  902. :version "24.4"
  903. :package-version '(Org . "8.0")
  904. :type 'boolean)
  905. (defcustom org-insert-mode-line-in-empty-file nil
  906. "Non-nil means insert the first line setting Org mode in empty files.
  907. When the function `org-mode' is called interactively in an empty file, this
  908. normally means that the file name does not automatically trigger Org mode.
  909. To ensure that the file will always be in Org mode in the future, a
  910. line enforcing Org mode will be inserted into the buffer, if this option
  911. has been set."
  912. :group 'org-startup
  913. :type 'boolean)
  914. (defcustom org-ellipsis nil
  915. "The ellipsis to use in the Org mode outline.
  916. When nil, just use the standard three dots. When a non-empty string,
  917. use that string instead.
  918. The change affects only Org mode (which will then use its own display table).
  919. Changing this requires executing `\\[org-mode]' in a buffer to become
  920. effective."
  921. :group 'org-startup
  922. :type '(choice (const :tag "Default" nil)
  923. (string :tag "String" :value "...#"))
  924. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  925. (defvar org-display-table nil
  926. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  927. (defgroup org-keywords nil
  928. "Keywords in Org mode."
  929. :tag "Org Keywords"
  930. :group 'org)
  931. (defcustom org-closed-keep-when-no-todo nil
  932. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  933. :group 'org-todo
  934. :group 'org-keywords
  935. :version "24.4"
  936. :package-version '(Org . "8.0")
  937. :type 'boolean)
  938. (defgroup org-structure nil
  939. "Options concerning the general structure of Org files."
  940. :tag "Org Structure"
  941. :group 'org)
  942. (defgroup org-reveal-location nil
  943. "Options about how to make context of a location visible."
  944. :tag "Org Reveal Location"
  945. :group 'org-structure)
  946. (defcustom org-show-context-detail '((agenda . local)
  947. (bookmark-jump . lineage)
  948. (isearch . lineage)
  949. (default . ancestors))
  950. "Alist between context and visibility span when revealing a location.
  951. \\<org-mode-map>Some actions may move point into invisible
  952. locations. As a consequence, Org always expose a neighborhood
  953. around point. How much is shown depends on the initial action,
  954. or context. Valid contexts are
  955. agenda when exposing an entry from the agenda
  956. org-goto when using the command `org-goto' (`\\[org-goto]')
  957. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  958. tags-tree when constructing a sparse tree based on tags matches
  959. link-search when exposing search matches associated with a link
  960. mark-goto when exposing the jump goal of a mark
  961. bookmark-jump when exposing a bookmark location
  962. isearch when exiting from an incremental search
  963. default default for all contexts not set explicitly
  964. Allowed visibility spans are
  965. minimal show current headline; if point is not on headline,
  966. also show entry
  967. local show current headline, entry and next headline
  968. ancestors show current headline and its direct ancestors; if
  969. point is not on headline, also show entry
  970. lineage show current headline, its direct ancestors and all
  971. their children; if point is not on headline, also show
  972. entry and first child
  973. tree show current headline, its direct ancestors and all
  974. their children; if point is not on headline, also show
  975. entry and all children
  976. canonical show current headline, its direct ancestors along with
  977. their entries and children; if point is not located on
  978. the headline, also show current entry and all children
  979. As special cases, a nil or t value means show all contexts in
  980. `minimal' or `canonical' view, respectively.
  981. Some views can make displayed information very compact, but also
  982. make it harder to edit the location of the match. In such
  983. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  984. more context."
  985. :group 'org-reveal-location
  986. :version "26.1"
  987. :package-version '(Org . "9.0")
  988. :type '(choice
  989. (const :tag "Canonical" t)
  990. (const :tag "Minimal" nil)
  991. (repeat :greedy t :tag "Individual contexts"
  992. (cons
  993. (choice :tag "Context"
  994. (const agenda)
  995. (const org-goto)
  996. (const occur-tree)
  997. (const tags-tree)
  998. (const link-search)
  999. (const mark-goto)
  1000. (const bookmark-jump)
  1001. (const isearch)
  1002. (const default))
  1003. (choice :tag "Detail level"
  1004. (const minimal)
  1005. (const local)
  1006. (const ancestors)
  1007. (const lineage)
  1008. (const tree)
  1009. (const canonical))))))
  1010. (defcustom org-indirect-buffer-display 'other-window
  1011. "How should indirect tree buffers be displayed?
  1012. This applies to indirect buffers created with the commands
  1013. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1014. Valid values are:
  1015. current-window Display in the current window
  1016. other-window Just display in another window.
  1017. dedicated-frame Create one new frame, and re-use it each time.
  1018. new-frame Make a new frame each time. Note that in this case
  1019. previously-made indirect buffers are kept, and you need to
  1020. kill these buffers yourself."
  1021. :group 'org-structure
  1022. :group 'org-agenda-windows
  1023. :type '(choice
  1024. (const :tag "In current window" current-window)
  1025. (const :tag "In current frame, other window" other-window)
  1026. (const :tag "Each time a new frame" new-frame)
  1027. (const :tag "One dedicated frame" dedicated-frame)))
  1028. (defconst org-file-apps-gnu
  1029. '((remote . emacs)
  1030. (system . mailcap)
  1031. (t . mailcap))
  1032. "Default file applications on a UNIX or GNU/Linux system.
  1033. See `org-file-apps'.")
  1034. (defconst org-file-apps-macos
  1035. '((remote . emacs)
  1036. (system . "open %s")
  1037. ("ps.gz" . "gv %s")
  1038. ("eps.gz" . "gv %s")
  1039. ("dvi" . "xdvi %s")
  1040. ("fig" . "xfig %s")
  1041. (t . "open %s"))
  1042. "Default file applications on a macOS system.
  1043. The system \"open\" is known as a default, but we use X11 applications
  1044. for some files for which the OS does not have a good default.
  1045. See `org-file-apps'.")
  1046. (defconst org-file-apps-windowsnt
  1047. (list '(remote . emacs)
  1048. (cons 'system (lambda (file _path)
  1049. (with-no-warnings (w32-shell-execute "open" file))))
  1050. (cons t (lambda (file _path)
  1051. (with-no-warnings (w32-shell-execute "open" file)))))
  1052. "Default file applications on a Windows NT system.
  1053. The system \"open\" is used for most files.
  1054. See `org-file-apps'.")
  1055. (defcustom org-file-apps
  1056. '((auto-mode . emacs)
  1057. ("\\.mm\\'" . default)
  1058. ("\\.x?html?\\'" . default)
  1059. ("\\.pdf\\'" . default))
  1060. "External applications for opening `file:path' items in a document.
  1061. \\<org-mode-map>
  1062. Org mode uses system defaults for different file types, but
  1063. you can use this variable to set the application for a given file
  1064. extension. The entries in this list are cons cells where the car identifies
  1065. files and the cdr the corresponding command.
  1066. Possible values for the file identifier are:
  1067. \"string\" A string as a file identifier can be interpreted in different
  1068. ways, depending on its contents:
  1069. - Alphanumeric characters only:
  1070. Match links with this file extension.
  1071. Example: (\"pdf\" . \"evince %s\")
  1072. to open PDFs with evince.
  1073. - Regular expression: Match links where the
  1074. filename matches the regexp. If you want to
  1075. use groups here, use shy groups.
  1076. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1077. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1078. to open *.html and *.xhtml with firefox.
  1079. - Regular expression which contains (non-shy) groups:
  1080. Match links where the whole link, including \"::\", and
  1081. anything after that, matches the regexp.
  1082. In a custom command string, %1, %2, etc. are replaced with
  1083. the parts of the link that were matched by the groups.
  1084. For backwards compatibility, if a command string is given
  1085. that does not use any of the group matches, this case is
  1086. handled identically to the second one (i.e. match against
  1087. file name only).
  1088. In a custom function, you can access the group matches with
  1089. (match-string n link).
  1090. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1091. \"evince -p %1 %s\")
  1092. to open [[file:document.pdf::5]] with evince at page 5.
  1093. `directory' Matches a directory
  1094. `remote' Matches a remote file, accessible through tramp or efs.
  1095. Remote files most likely should be visited through Emacs
  1096. because external applications cannot handle such paths.
  1097. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1098. so all files Emacs knows how to handle. Using this with
  1099. command `emacs' will open most files in Emacs. Beware that this
  1100. will also open html files inside Emacs, unless you add
  1101. (\"html\" . default) to the list as well.
  1102. `system' The system command to open files, like `open' on Windows
  1103. and macOS, and mailcap under GNU/Linux. This is the command
  1104. that will be selected if you call `org-open-at-point' with a
  1105. double prefix argument (`\\[universal-argument] \
  1106. \\[universal-argument] \\[org-open-at-point]').
  1107. t Default for files not matched by any of the other options.
  1108. Possible values for the command are:
  1109. `emacs' The file will be visited by the current Emacs process.
  1110. `default' Use the default application for this file type, which is the
  1111. association for t in the list, most likely in the system-specific
  1112. part. This can be used to overrule an unwanted setting in the
  1113. system-specific variable.
  1114. `system' Use the system command for opening files, like \"open\".
  1115. This command is specified by the entry whose car is `system'.
  1116. Most likely, the system-specific version of this variable
  1117. does define this command, but you can overrule/replace it
  1118. here.
  1119. `mailcap' Use command specified in the mailcaps.
  1120. string A command to be executed by a shell; %s will be replaced
  1121. by the path to the file.
  1122. function A Lisp function, which will be called with two arguments:
  1123. the file path and the original link string, without the
  1124. \"file:\" prefix.
  1125. For more examples, see the system specific constants
  1126. `org-file-apps-macos'
  1127. `org-file-apps-windowsnt'
  1128. `org-file-apps-gnu'."
  1129. :group 'org
  1130. :type '(repeat
  1131. (cons (choice :value ""
  1132. (string :tag "Extension")
  1133. (const :tag "System command to open files" system)
  1134. (const :tag "Default for unrecognized files" t)
  1135. (const :tag "Remote file" remote)
  1136. (const :tag "Links to a directory" directory)
  1137. (const :tag "Any files that have Emacs modes"
  1138. auto-mode))
  1139. (choice :value ""
  1140. (const :tag "Visit with Emacs" emacs)
  1141. (const :tag "Use default" default)
  1142. (const :tag "Use the system command" system)
  1143. (string :tag "Command")
  1144. (function :tag "Function")))))
  1145. (defcustom org-open-non-existing-files nil
  1146. "Non-nil means `org-open-file' opens non-existing files.
  1147. When nil, an error is thrown.
  1148. This variable applies only to external applications because they
  1149. might choke on non-existing files. If the link is to a file that
  1150. will be opened in Emacs, the variable is ignored."
  1151. :group 'org
  1152. :type 'boolean
  1153. :safe #'booleanp)
  1154. (defcustom org-open-directory-means-index-dot-org nil
  1155. "When non-nil a link to a directory really means to \"index.org\".
  1156. When nil, following a directory link runs Dired or opens
  1157. a finder/explorer window on that directory."
  1158. :group 'org
  1159. :type 'boolean
  1160. :safe #'booleanp)
  1161. (defcustom org-bookmark-names-plist
  1162. '(:last-capture "org-capture-last-stored"
  1163. :last-refile "org-refile-last-stored"
  1164. :last-capture-marker "org-capture-last-stored-marker")
  1165. "Names for bookmarks automatically set by some Org commands.
  1166. This can provide strings as names for a number of bookmarks Org sets
  1167. automatically. The following keys are currently implemented:
  1168. :last-capture
  1169. :last-capture-marker
  1170. :last-refile
  1171. When a key does not show up in the property list, the corresponding bookmark
  1172. is not set."
  1173. :group 'org-structure
  1174. :type 'plist)
  1175. (defgroup org-cycle nil
  1176. "Options concerning visibility cycling in Org mode."
  1177. :tag "Org Cycle"
  1178. :group 'org-structure)
  1179. (defcustom org-cycle-skip-children-state-if-no-children t
  1180. "Non-nil means skip CHILDREN state in entries that don't have any."
  1181. :group 'org-cycle
  1182. :type 'boolean)
  1183. (defcustom org-cycle-max-level nil
  1184. "Maximum level which should still be subject to visibility cycling.
  1185. Levels higher than this will, for cycling, be treated as text, not a headline.
  1186. When `org-odd-levels-only' is set, a value of N in this variable actually
  1187. means 2N-1 stars as the limiting headline.
  1188. When nil, cycle all levels.
  1189. Note that the limiting level of cycling is also influenced by
  1190. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1191. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1192. than its value."
  1193. :group 'org-cycle
  1194. :type '(choice
  1195. (const :tag "No limit" nil)
  1196. (integer :tag "Maximum level")))
  1197. (defcustom org-hide-block-startup nil
  1198. "Non-nil means entering Org mode will fold all blocks.
  1199. This can also be set in on a per-file basis with
  1200. #+STARTUP: hideblocks
  1201. #+STARTUP: showblocks"
  1202. :group 'org-startup
  1203. :group 'org-cycle
  1204. :type 'boolean)
  1205. (defcustom org-cycle-global-at-bob nil
  1206. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1207. This makes it possible to do global cycling without having to use `S-TAB'
  1208. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1209. line of the buffer
  1210. must not be a headline -- it may be empty or some other text.
  1211. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1212. sure the cursor stays at the beginning of the buffer.
  1213. When this option is nil, don't do anything special at the beginning of
  1214. the buffer."
  1215. :group 'org-cycle
  1216. :type 'boolean)
  1217. (defcustom org-cycle-level-after-item/entry-creation t
  1218. "Non-nil means cycle entry level or item indentation in new empty entries.
  1219. When the cursor is at the end of an empty headline, i.e., with only stars
  1220. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1221. and then all possible ancestor states, before returning to the original state.
  1222. This makes data entry extremely fast: M-RET to create a new headline,
  1223. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1224. When the cursor is at the end of an empty plain list item, one TAB will
  1225. make it a subitem, two or more tabs will back up to make this an item
  1226. higher up in the item hierarchy."
  1227. :group 'org-cycle
  1228. :type 'boolean)
  1229. (defcustom org-cycle-emulate-tab t
  1230. "Where should `org-cycle' emulate TAB.
  1231. nil Never
  1232. white Only in completely white lines
  1233. whitestart Only at the beginning of lines, before the first non-white char
  1234. t Everywhere except in headlines
  1235. exc-hl-bol Everywhere except at the start of a headline
  1236. If TAB is used in a place where it does not emulate TAB, the current subtree
  1237. visibility is cycled."
  1238. :group 'org-cycle
  1239. :type '(choice (const :tag "Never" nil)
  1240. (const :tag "Only in completely white lines" white)
  1241. (const :tag "Before first char in a line" whitestart)
  1242. (const :tag "Everywhere except in headlines" t)
  1243. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1244. (defcustom org-cycle-separator-lines 2
  1245. "Number of empty lines needed to keep an empty line between collapsed trees.
  1246. If you leave an empty line between the end of a subtree and the following
  1247. headline, this empty line is hidden when the subtree is folded.
  1248. Org mode will leave (exactly) one empty line visible if the number of
  1249. empty lines is equal or larger to the number given in this variable.
  1250. So the default 2 means at least 2 empty lines after the end of a subtree
  1251. are needed to produce free space between a collapsed subtree and the
  1252. following headline.
  1253. If the number is negative, and the number of empty lines is at least -N,
  1254. all empty lines are shown.
  1255. Special case: when 0, never leave empty lines in collapsed view."
  1256. :group 'org-cycle
  1257. :type 'integer)
  1258. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1259. (defcustom org-pre-cycle-hook nil
  1260. "Hook that is run before visibility cycling is happening.
  1261. The function(s) in this hook must accept a single argument which indicates
  1262. the new state that will be set right after running this hook. The
  1263. argument is a symbol. Before a global state change, it can have the values
  1264. `overview', `content', or `all'. Before a local state change, it can have
  1265. the values `folded', `children', or `subtree'."
  1266. :group 'org-cycle
  1267. :type 'hook)
  1268. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1269. org-cycle-show-empty-lines
  1270. org-optimize-window-after-visibility-change)
  1271. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1272. The function(s) in this hook must accept a single argument which indicates
  1273. the new state that was set by the most recent `org-cycle' command. The
  1274. argument is a symbol. After a global state change, it can have the values
  1275. `overview', `contents', or `all'. After a local state change, it can have
  1276. the values `folded', `children', or `subtree'."
  1277. :group 'org-cycle
  1278. :type 'hook
  1279. :version "26.1"
  1280. :package-version '(Org . "8.3"))
  1281. (defgroup org-edit-structure nil
  1282. "Options concerning structure editing in Org mode."
  1283. :tag "Org Edit Structure"
  1284. :group 'org-structure)
  1285. (defcustom org-odd-levels-only nil
  1286. "Non-nil means skip even levels and only use odd levels for the outline.
  1287. This has the effect that two stars are being added/taken away in
  1288. promotion/demotion commands. It also influences how levels are
  1289. handled by the exporters.
  1290. Changing it requires restart of `font-lock-mode' to become effective
  1291. for fontification also in regions already fontified.
  1292. You may also set this on a per-file basis by adding one of the following
  1293. lines to the buffer:
  1294. #+STARTUP: odd
  1295. #+STARTUP: oddeven"
  1296. :group 'org-edit-structure
  1297. :group 'org-appearance
  1298. :type 'boolean)
  1299. (defcustom org-adapt-indentation t
  1300. "Non-nil means adapt indentation to outline node level.
  1301. When this variable is set, Org assumes that you write outlines by
  1302. indenting text in each node to align with the headline (after the
  1303. stars). The following issues are influenced by this variable:
  1304. - The indentation is increased by one space in a demotion
  1305. command, and decreased by one in a promotion command. However,
  1306. in the latter case, if shifting some line in the entry body
  1307. would alter document structure (e.g., insert a new headline),
  1308. indentation is not changed at all.
  1309. - Property drawers and planning information is inserted indented
  1310. when this variable is set. When nil, they will not be indented.
  1311. - TAB indents a line relative to current level. The lines below
  1312. a headline will be indented when this variable is set.
  1313. Note that this is all about true indentation, by adding and
  1314. removing space characters. See also \"org-indent.el\" which does
  1315. level-dependent indentation in a virtual way, i.e. at display
  1316. time in Emacs."
  1317. :group 'org-edit-structure
  1318. :type 'boolean
  1319. :safe #'booleanp)
  1320. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1321. (defcustom org-special-ctrl-a/e nil
  1322. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1323. When t, `C-a' will bring back the cursor to the beginning of the
  1324. headline text, i.e. after the stars and after a possible TODO
  1325. keyword. In an item, this will be the position after bullet and
  1326. check-box, if any. When the cursor is already at that position,
  1327. another `C-a' will bring it to the beginning of the line.
  1328. `C-e' will jump to the end of the headline, ignoring the presence
  1329. of tags in the headline. A second `C-e' will then jump to the
  1330. true end of the line, after any tags. This also means that, when
  1331. this variable is non-nil, `C-e' also will never jump beyond the
  1332. end of the heading of a folded section, i.e. not after the
  1333. ellipses.
  1334. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1335. normally, going to the true line boundary first. Only a directly
  1336. following, identical keypress will bring the cursor to the
  1337. special positions.
  1338. This may also be a cons cell where the behavior for `C-a' and
  1339. `C-e' is set separately."
  1340. :group 'org-edit-structure
  1341. :type '(choice
  1342. (const :tag "off" nil)
  1343. (const :tag "on: after stars/bullet and before tags first" t)
  1344. (const :tag "reversed: true line boundary first" reversed)
  1345. (cons :tag "Set C-a and C-e separately"
  1346. (choice :tag "Special C-a"
  1347. (const :tag "off" nil)
  1348. (const :tag "on: after stars/bullet first" t)
  1349. (const :tag "reversed: before stars/bullet first" reversed))
  1350. (choice :tag "Special C-e"
  1351. (const :tag "off" nil)
  1352. (const :tag "on: before tags first" t)
  1353. (const :tag "reversed: after tags first" reversed)))))
  1354. (defcustom org-special-ctrl-k nil
  1355. "Non-nil means `C-k' will behave specially in headlines.
  1356. When nil, `C-k' will call the default `kill-line' command.
  1357. When t, the following will happen while the cursor is in the headline:
  1358. - When the cursor is at the beginning of a headline, kill the entire
  1359. line and possible the folded subtree below the line.
  1360. - When in the middle of the headline text, kill the headline up to the tags.
  1361. - When after the headline text, kill the tags."
  1362. :group 'org-edit-structure
  1363. :type 'boolean)
  1364. (defcustom org-ctrl-k-protect-subtree nil
  1365. "Non-nil means, do not delete a hidden subtree with C-k.
  1366. When set to the symbol `error', simply throw an error when C-k is
  1367. used to kill (part-of) a headline that has hidden text behind it.
  1368. Any other non-nil value will result in a query to the user, if it is
  1369. OK to kill that hidden subtree. When nil, kill without remorse."
  1370. :group 'org-edit-structure
  1371. :version "24.1"
  1372. :type '(choice
  1373. (const :tag "Do not protect hidden subtrees" nil)
  1374. (const :tag "Protect hidden subtrees with a security query" t)
  1375. (const :tag "Never kill a hidden subtree with C-k" error)))
  1376. (defcustom org-special-ctrl-o t
  1377. "Non-nil means, make `C-o' insert a row in tables."
  1378. :group 'org-edit-structure
  1379. :type 'boolean)
  1380. (defcustom org-catch-invisible-edits nil
  1381. "Check if in invisible region before inserting or deleting a character.
  1382. Valid values are:
  1383. nil Do not check, so just do invisible edits.
  1384. error Throw an error and do nothing.
  1385. show Make point visible, and do the requested edit.
  1386. show-and-error Make point visible, then throw an error and abort the edit.
  1387. smart Make point visible, and do insertion/deletion if it is
  1388. adjacent to visible text and the change feels predictable.
  1389. Never delete a previously invisible character or add in the
  1390. middle or right after an invisible region. Basically, this
  1391. allows insertion and backward-delete right before ellipses.
  1392. FIXME: maybe in this case we should not even show?"
  1393. :group 'org-edit-structure
  1394. :version "24.1"
  1395. :type '(choice
  1396. (const :tag "Do not check" nil)
  1397. (const :tag "Throw error when trying to edit" error)
  1398. (const :tag "Unhide, but do not do the edit" show-and-error)
  1399. (const :tag "Show invisible part and do the edit" show)
  1400. (const :tag "Be smart and do the right thing" smart)))
  1401. (defcustom org-yank-folded-subtrees t
  1402. "Non-nil means when yanking subtrees, fold them.
  1403. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1404. it starts with a heading and all other headings in it are either children
  1405. or siblings, then fold all the subtrees. However, do this only if no
  1406. text after the yank would be swallowed into a folded tree by this action."
  1407. :group 'org-edit-structure
  1408. :type 'boolean)
  1409. (defcustom org-yank-adjusted-subtrees nil
  1410. "Non-nil means when yanking subtrees, adjust the level.
  1411. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1412. this function for details."
  1413. :group 'org-edit-structure
  1414. :type 'boolean)
  1415. (defcustom org-M-RET-may-split-line '((default . t))
  1416. "Non-nil means M-RET will split the line at the cursor position.
  1417. When nil, it will go to the end of the line before making a
  1418. new line.
  1419. You may also set this option in a different way for different
  1420. contexts. Valid contexts are:
  1421. headline when creating a new headline
  1422. item when creating a new item
  1423. table in a table field
  1424. default the value to be used for all contexts not explicitly
  1425. customized"
  1426. :group 'org-structure
  1427. :group 'org-table
  1428. :type '(choice
  1429. (const :tag "Always" t)
  1430. (const :tag "Never" nil)
  1431. (repeat :greedy t :tag "Individual contexts"
  1432. (cons
  1433. (choice :tag "Context"
  1434. (const headline)
  1435. (const item)
  1436. (const table)
  1437. (const default))
  1438. (boolean)))))
  1439. (defcustom org-insert-heading-respect-content nil
  1440. "Non-nil means insert new headings after the current subtree.
  1441. \\<org-mode-map>
  1442. When nil, the new heading is created directly after the current line.
  1443. The commands `\\[org-insert-heading-respect-content]' and \
  1444. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1445. for the duration of the command."
  1446. :group 'org-structure
  1447. :type 'boolean)
  1448. (defcustom org-blank-before-new-entry '((heading . auto)
  1449. (plain-list-item . auto))
  1450. "Should `org-insert-heading' leave a blank line before new heading/item?
  1451. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1452. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1453. which case Org will look at the surrounding headings/items and try to
  1454. make an intelligent decision whether to insert a blank line or not."
  1455. :group 'org-edit-structure
  1456. :type '(list
  1457. (cons (const heading)
  1458. (choice (const :tag "Never" nil)
  1459. (const :tag "Always" t)
  1460. (const :tag "Auto" auto)))
  1461. (cons (const plain-list-item)
  1462. (choice (const :tag "Never" nil)
  1463. (const :tag "Always" t)
  1464. (const :tag "Auto" auto)))))
  1465. (defcustom org-insert-heading-hook nil
  1466. "Hook being run after inserting a new heading."
  1467. :group 'org-edit-structure
  1468. :type 'hook)
  1469. (defgroup org-sparse-trees nil
  1470. "Options concerning sparse trees in Org mode."
  1471. :tag "Org Sparse Trees"
  1472. :group 'org-structure)
  1473. (defcustom org-highlight-sparse-tree-matches t
  1474. "Non-nil means highlight all matches that define a sparse tree.
  1475. The highlights will automatically disappear the next time the buffer is
  1476. changed by an edit command."
  1477. :group 'org-sparse-trees
  1478. :type 'boolean)
  1479. (defcustom org-remove-highlights-with-change t
  1480. "Non-nil means any change to the buffer will remove temporary highlights.
  1481. \\<org-mode-map>\
  1482. Such highlights are created by `org-occur' and `org-clock-display'.
  1483. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1484. to get rid of the highlights.
  1485. The highlights created by `org-latex-preview' always need
  1486. `\\[org-latex-preview]' to be removed."
  1487. :group 'org-sparse-trees
  1488. :group 'org-time
  1489. :type 'boolean)
  1490. (defcustom org-occur-case-fold-search t
  1491. "Non-nil means `org-occur' should be case-insensitive.
  1492. If set to `smart' the search will be case-insensitive only if it
  1493. doesn't specify any upper case character."
  1494. :group 'org-sparse-trees
  1495. :version "26.1"
  1496. :type '(choice
  1497. (const :tag "Case-sensitive" nil)
  1498. (const :tag "Case-insensitive" t)
  1499. (const :tag "Case-insensitive for lower case searches only" smart)))
  1500. (defcustom org-occur-hook '(org-first-headline-recenter)
  1501. "Hook that is run after `org-occur' has constructed a sparse tree.
  1502. This can be used to recenter the window to show as much of the structure
  1503. as possible."
  1504. :group 'org-sparse-trees
  1505. :type 'hook)
  1506. (defcustom org-self-insert-cluster-for-undo nil
  1507. "Non-nil means cluster self-insert commands for undo when possible.
  1508. If this is set, then, like in the Emacs command loop, 20 consecutive
  1509. characters will be undone together.
  1510. This is configurable, because there is some impact on typing performance."
  1511. :group 'org-table
  1512. :type 'boolean)
  1513. (defvaralias 'org-activate-links 'org-highlight-links)
  1514. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1515. "Types of links that should be highlighted in Org files.
  1516. This is a list of symbols, each one of them leading to the
  1517. highlighting of a certain link type.
  1518. You can still open links that are not highlighted.
  1519. In principle, it does not hurt to turn on highlighting for all
  1520. link types. There may be a small gain when turning off unused
  1521. link types. The types are:
  1522. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1523. angle Links in angular brackets that may contain whitespace like
  1524. <bbdb:Carsten Dominik>.
  1525. plain Plain links in normal text, no whitespace, like http://google.com.
  1526. radio Text that is matched by a radio target, see manual for details.
  1527. tag Tag settings in a headline (link to tag search).
  1528. date Time stamps (link to calendar).
  1529. footnote Footnote labels.
  1530. If you set this variable during an Emacs session, use `org-mode-restart'
  1531. in the Org buffer so that the change takes effect."
  1532. :group 'org-appearance
  1533. :type '(set :greedy t
  1534. (const :tag "Double bracket links" bracket)
  1535. (const :tag "Angular bracket links" angle)
  1536. (const :tag "Plain text links" plain)
  1537. (const :tag "Radio target matches" radio)
  1538. (const :tag "Tags" tag)
  1539. (const :tag "Timestamps" date)
  1540. (const :tag "Footnotes" footnote)))
  1541. (defcustom org-mark-ring-length 4
  1542. "Number of different positions to be recorded in the ring.
  1543. Changing this requires a restart of Emacs to work correctly."
  1544. :group 'org-link-follow
  1545. :type 'integer)
  1546. (defgroup org-refile nil
  1547. "Options concerning refiling entries in Org mode."
  1548. :tag "Org Refile"
  1549. :group 'org)
  1550. (defcustom org-directory "~/org"
  1551. "Directory with Org files.
  1552. This is just a default location to look for Org files. There is no need
  1553. at all to put your files into this directory. It is used in the
  1554. following situations:
  1555. 1. When a capture template specifies a target file that is not an
  1556. absolute path. The path will then be interpreted relative to
  1557. `org-directory'
  1558. 2. When the value of variable `org-agenda-files' is a single file, any
  1559. relative paths in this file will be taken as relative to
  1560. `org-directory'."
  1561. :group 'org-refile
  1562. :group 'org-capture
  1563. :type 'directory)
  1564. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  1565. "Default target for storing notes.
  1566. Used as a fall back file for org-capture.el, for templates that
  1567. do not specify a target file."
  1568. :group 'org-refile
  1569. :group 'org-capture
  1570. :type 'file)
  1571. (defcustom org-reverse-note-order nil
  1572. "Non-nil means store new notes at the beginning of a file or entry.
  1573. When nil, new notes will be filed to the end of a file or entry.
  1574. This can also be a list with cons cells of regular expressions that
  1575. are matched against file names, and values."
  1576. :group 'org-capture
  1577. :group 'org-refile
  1578. :type '(choice
  1579. (const :tag "Reverse always" t)
  1580. (const :tag "Reverse never" nil)
  1581. (repeat :tag "By file name regexp"
  1582. (cons regexp boolean))))
  1583. (defcustom org-log-refile nil
  1584. "Information to record when a task is refiled.
  1585. Possible values are:
  1586. nil Don't add anything
  1587. time Add a time stamp to the task
  1588. note Prompt for a note and add it with template `org-log-note-headings'
  1589. This option can also be set with on a per-file-basis with
  1590. #+STARTUP: nologrefile
  1591. #+STARTUP: logrefile
  1592. #+STARTUP: lognoterefile
  1593. You can have local logging settings for a subtree by setting the LOGGING
  1594. property to one or more of these keywords.
  1595. When bulk-refiling, e.g., from the agenda, the value `note' is
  1596. forbidden and will temporarily be changed to `time'."
  1597. :group 'org-refile
  1598. :group 'org-progress
  1599. :version "24.1"
  1600. :type '(choice
  1601. (const :tag "No logging" nil)
  1602. (const :tag "Record timestamp" time)
  1603. (const :tag "Record timestamp with note." note)))
  1604. (defcustom org-refile-targets nil
  1605. "Targets for refiling entries with `\\[org-refile]'.
  1606. This is a list of cons cells. Each cell contains:
  1607. - a specification of the files to be considered, either a list of files,
  1608. or a symbol whose function or variable value will be used to retrieve
  1609. a file name or a list of file names. If you use `org-agenda-files' for
  1610. that, all agenda files will be scanned for targets. Nil means consider
  1611. headings in the current buffer.
  1612. - A specification of how to find candidate refile targets. This may be
  1613. any of:
  1614. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  1615. This tag has to be present in all target headlines, inheritance will
  1616. not be considered.
  1617. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  1618. todo keyword.
  1619. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  1620. headlines that are refiling targets.
  1621. - a cons cell (:level . N). Any headline of level N is considered a target.
  1622. Note that, when `org-odd-levels-only' is set, level corresponds to
  1623. order in hierarchy, not to the number of stars.
  1624. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  1625. Note that, when `org-odd-levels-only' is set, level corresponds to
  1626. order in hierarchy, not to the number of stars.
  1627. Each element of this list generates a set of possible targets.
  1628. The union of these sets is presented (with completion) to
  1629. the user by `org-refile'.
  1630. You can set the variable `org-refile-target-verify-function' to a function
  1631. to verify each headline found by the simple criteria above.
  1632. When this variable is nil, all top-level headlines in the current buffer
  1633. are used, equivalent to the value `((nil . (:level . 1))'."
  1634. :group 'org-refile
  1635. :type '(repeat
  1636. (cons
  1637. (choice :value org-agenda-files
  1638. (const :tag "All agenda files" org-agenda-files)
  1639. (const :tag "Current buffer" nil)
  1640. (function) (variable) (file))
  1641. (choice :tag "Identify target headline by"
  1642. (cons :tag "Specific tag" (const :value :tag) (string))
  1643. (cons :tag "TODO keyword" (const :value :todo) (string))
  1644. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  1645. (cons :tag "Level number" (const :value :level) (integer))
  1646. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  1647. (defcustom org-refile-target-verify-function nil
  1648. "Function to verify if the headline at point should be a refile target.
  1649. The function will be called without arguments, with point at the
  1650. beginning of the headline. It should return t and leave point
  1651. where it is if the headline is a valid target for refiling.
  1652. If the target should not be selected, the function must return nil.
  1653. In addition to this, it may move point to a place from where the search
  1654. should be continued. For example, the function may decide that the entire
  1655. subtree of the current entry should be excluded and move point to the end
  1656. of the subtree."
  1657. :group 'org-refile
  1658. :type '(choice
  1659. (const nil)
  1660. (function)))
  1661. (defcustom org-refile-use-cache nil
  1662. "Non-nil means cache refile targets to speed up the process.
  1663. \\<org-mode-map>\
  1664. The cache for a particular file will be updated automatically when
  1665. the buffer has been killed, or when any of the marker used for flagging
  1666. refile targets no longer points at a live buffer.
  1667. If you have added new entries to a buffer that might themselves be targets,
  1668. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  1669. if you find that easier, \
  1670. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  1671. \\[org-refile]'."
  1672. :group 'org-refile
  1673. :version "24.1"
  1674. :type 'boolean)
  1675. (defcustom org-refile-use-outline-path nil
  1676. "Non-nil means provide refile targets as paths.
  1677. So a level 3 headline will be available as level1/level2/level3.
  1678. When the value is `file', also include the file name (without directory)
  1679. into the path. In this case, you can also stop the completion after
  1680. the file name, to get entries inserted as top level in the file.
  1681. When `full-file-path', include the full file path.
  1682. When `buffer-name', use the buffer name."
  1683. :group 'org-refile
  1684. :type '(choice
  1685. (const :tag "Not" nil)
  1686. (const :tag "Yes" t)
  1687. (const :tag "Start with file name" file)
  1688. (const :tag "Start with full file path" full-file-path)
  1689. (const :tag "Start with buffer name" buffer-name)))
  1690. (defcustom org-outline-path-complete-in-steps t
  1691. "Non-nil means complete the outline path in hierarchical steps.
  1692. When Org uses the refile interface to select an outline path (see
  1693. `org-refile-use-outline-path'), the completion of the path can be
  1694. done in a single go, or it can be done in steps down the headline
  1695. hierarchy. Going in steps is probably the best if you do not use
  1696. a special completion package like `ido' or `icicles'. However,
  1697. when using these packages, going in one step can be very fast,
  1698. while still showing the whole path to the entry."
  1699. :group 'org-refile
  1700. :type 'boolean)
  1701. (defcustom org-refile-allow-creating-parent-nodes nil
  1702. "Non-nil means allow the creation of new nodes as refile targets.
  1703. New nodes are then created by adding \"/new node name\" to the completion
  1704. of an existing node. When the value of this variable is `confirm',
  1705. new node creation must be confirmed by the user (recommended).
  1706. When nil, the completion must match an existing entry.
  1707. Note that, if the new heading is not seen by the criteria
  1708. listed in `org-refile-targets', multiple instances of the same
  1709. heading would be created by trying again to file under the new
  1710. heading."
  1711. :group 'org-refile
  1712. :type '(choice
  1713. (const :tag "Never" nil)
  1714. (const :tag "Always" t)
  1715. (const :tag "Prompt for confirmation" confirm)))
  1716. (defcustom org-refile-active-region-within-subtree nil
  1717. "Non-nil means also refile active region within a subtree.
  1718. By default `org-refile' doesn't allow refiling regions if they
  1719. don't contain a set of subtrees, but it might be convenient to
  1720. do so sometimes: in that case, the first line of the region is
  1721. converted to a headline before refiling."
  1722. :group 'org-refile
  1723. :version "24.1"
  1724. :type 'boolean)
  1725. (defgroup org-todo nil
  1726. "Options concerning TODO items in Org mode."
  1727. :tag "Org TODO"
  1728. :group 'org)
  1729. (defgroup org-progress nil
  1730. "Options concerning Progress logging in Org mode."
  1731. :tag "Org Progress"
  1732. :group 'org-time)
  1733. (defvar org-todo-interpretation-widgets
  1734. '((:tag "Sequence (cycling hits every state)" sequence)
  1735. (:tag "Type (cycling directly to DONE)" type))
  1736. "The available interpretation symbols for customizing `org-todo-keywords'.
  1737. Interested libraries should add to this list.")
  1738. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1739. "List of TODO entry keyword sequences and their interpretation.
  1740. \\<org-mode-map>This is a list of sequences.
  1741. Each sequence starts with a symbol, either `sequence' or `type',
  1742. indicating if the keywords should be interpreted as a sequence of
  1743. action steps, or as different types of TODO items. The first
  1744. keywords are states requiring action - these states will select a headline
  1745. for inclusion into the global TODO list Org produces. If one of the
  1746. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1747. signify that no further action is necessary. If \"|\" is not found,
  1748. the last keyword is treated as the only DONE state of the sequence.
  1749. The command `\\[org-todo]' cycles an entry through these states, and one
  1750. additional state where no keyword is present. For details about this
  1751. cycling, see the manual.
  1752. TODO keywords and interpretation can also be set on a per-file basis with
  1753. the special #+SEQ_TODO and #+TYP_TODO lines.
  1754. Each keyword can optionally specify a character for fast state selection
  1755. \(in combination with the variable `org-use-fast-todo-selection')
  1756. and specifiers for state change logging, using the same syntax that
  1757. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1758. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1759. indicates to record a time stamp each time this state is selected.
  1760. Each keyword may also specify if a timestamp or a note should be
  1761. recorded when entering or leaving the state, by adding additional
  1762. characters in the parenthesis after the keyword. This looks like this:
  1763. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1764. record only the time of the state change. With X and Y being either
  1765. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1766. Y when leaving the state if and only if the *target* state does not
  1767. define X. You may omit any of the fast-selection key or X or /Y,
  1768. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1769. For backward compatibility, this variable may also be just a list
  1770. of keywords. In this case the interpretation (sequence or type) will be
  1771. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1772. :group 'org-todo
  1773. :group 'org-keywords
  1774. :type '(choice
  1775. (repeat :tag "Old syntax, just keywords"
  1776. (string :tag "Keyword"))
  1777. (repeat :tag "New syntax"
  1778. (cons
  1779. (choice
  1780. :tag "Interpretation"
  1781. ;;Quick and dirty way to see
  1782. ;;`org-todo-interpretations'. This takes the
  1783. ;;place of item arguments
  1784. :convert-widget
  1785. (lambda (widget)
  1786. (widget-put widget
  1787. :args (mapcar
  1788. (lambda (x)
  1789. (widget-convert
  1790. (cons 'const x)))
  1791. org-todo-interpretation-widgets))
  1792. widget))
  1793. (repeat
  1794. (string :tag "Keyword"))))))
  1795. (defvar-local org-todo-keywords-1 nil
  1796. "All TODO and DONE keywords active in a buffer.")
  1797. (defvar org-todo-keywords-for-agenda nil)
  1798. (defvar org-done-keywords-for-agenda nil)
  1799. (defvar org-todo-keyword-alist-for-agenda nil)
  1800. (defvar org-tag-alist-for-agenda nil
  1801. "Alist of all tags from all agenda files.")
  1802. (defvar org-tag-groups-alist-for-agenda nil
  1803. "Alist of all groups tags from all current agenda files.")
  1804. (defvar-local org-tag-groups-alist nil)
  1805. (defvar org-agenda-contributing-files nil)
  1806. (defvar-local org-current-tag-alist nil
  1807. "Alist of all tag groups in current buffer.
  1808. This variable takes into consideration `org-tag-alist',
  1809. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1810. (defvar-local org-not-done-keywords nil)
  1811. (defvar-local org-done-keywords nil)
  1812. (defvar-local org-todo-heads nil)
  1813. (defvar-local org-todo-sets nil)
  1814. (defvar-local org-todo-log-states nil)
  1815. (defvar-local org-todo-kwd-alist nil)
  1816. (defvar-local org-todo-key-alist nil)
  1817. (defvar-local org-todo-key-trigger nil)
  1818. (defcustom org-todo-interpretation 'sequence
  1819. "Controls how TODO keywords are interpreted.
  1820. This variable is in principle obsolete and is only used for
  1821. backward compatibility, if the interpretation of todo keywords is
  1822. not given already in `org-todo-keywords'. See that variable for
  1823. more information."
  1824. :group 'org-todo
  1825. :group 'org-keywords
  1826. :type '(choice (const sequence)
  1827. (const type)))
  1828. (defcustom org-use-fast-todo-selection 'auto
  1829. "\\<org-mode-map>\
  1830. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1831. This variable describes if and under what circumstances the cycling
  1832. mechanism for TODO keywords will be replaced by a single-key, direct
  1833. selection scheme, where the choices are displayed in a little window.
  1834. When nil, fast selection is never used. This means that the command
  1835. will always switch to the next state.
  1836. When it is the symbol `auto', fast selection is whenever selection
  1837. keys have been defined.
  1838. `expert' is like `auto', but no special window with the keyword
  1839. will be shown, choices will only be listed in the prompt.
  1840. In all cases, the special interface is only used if access keys have
  1841. actually been assigned by the user, i.e. if keywords in the configuration
  1842. are followed by a letter in parenthesis, like TODO(t)."
  1843. :group 'org-todo
  1844. :set (lambda (var val)
  1845. (cond
  1846. ((eq var t) (set var 'auto))
  1847. ((eq var 'prefix) (set var nil))
  1848. (t (set var val))))
  1849. :type '(choice
  1850. (const :tag "Never" nil)
  1851. (const :tag "Automatically, when key letter have been defined" auto)
  1852. (const :tag "Automatically, but don't show the selection window" expert)))
  1853. (defcustom org-provide-todo-statistics t
  1854. "Non-nil means update todo statistics after insert and toggle.
  1855. ALL-HEADLINES means update todo statistics by including headlines
  1856. with no TODO keyword as well, counting them as not done.
  1857. A list of TODO keywords means the same, but skip keywords that are
  1858. not in this list.
  1859. When set to a list of two lists, the first list contains keywords
  1860. to consider as TODO keywords, the second list contains keywords
  1861. to consider as DONE keywords.
  1862. When this is set, todo statistics is updated in the parent of the
  1863. current entry each time a todo state is changed."
  1864. :group 'org-todo
  1865. :type '(choice
  1866. (const :tag "Yes, only for TODO entries" t)
  1867. (const :tag "Yes, including all entries" all-headlines)
  1868. (repeat :tag "Yes, for TODOs in this list"
  1869. (string :tag "TODO keyword"))
  1870. (list :tag "Yes, for TODOs and DONEs in these lists"
  1871. (repeat (string :tag "TODO keyword"))
  1872. (repeat (string :tag "DONE keyword")))
  1873. (other :tag "No TODO statistics" nil)))
  1874. (defcustom org-hierarchical-todo-statistics t
  1875. "Non-nil means TODO statistics covers just direct children.
  1876. When nil, all entries in the subtree are considered.
  1877. This has only an effect if `org-provide-todo-statistics' is set.
  1878. To set this to nil for only a single subtree, use a COOKIE_DATA
  1879. property and include the word \"recursive\" into the value."
  1880. :group 'org-todo
  1881. :type 'boolean)
  1882. (defcustom org-after-todo-state-change-hook nil
  1883. "Hook which is run after the state of a TODO item was changed.
  1884. The new state (a string with a TODO keyword, or nil) is available in the
  1885. Lisp variable `org-state'."
  1886. :group 'org-todo
  1887. :type 'hook)
  1888. (defvar org-blocker-hook nil
  1889. "Hook for functions that are allowed to block a state change.
  1890. Functions in this hook should not modify the buffer.
  1891. Each function gets as its single argument a property list,
  1892. see `org-trigger-hook' for more information about this list.
  1893. If any of the functions in this hook returns nil, the state change
  1894. is blocked.")
  1895. (defvar org-trigger-hook nil
  1896. "Hook for functions that are triggered by a state change.
  1897. Each function gets as its single argument a property list with at
  1898. least the following elements:
  1899. (:type type-of-change :position pos-at-entry-start
  1900. :from old-state :to new-state)
  1901. Depending on the type, more properties may be present.
  1902. This mechanism is currently implemented for:
  1903. TODO state changes
  1904. ------------------
  1905. :type todo-state-change
  1906. :from previous state (keyword as a string), or nil, or a symbol
  1907. `todo' or `done', to indicate the general type of state.
  1908. :to new state, like in :from")
  1909. (defcustom org-enforce-todo-dependencies nil
  1910. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1911. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1912. be blocked if any prior sibling is not yet done.
  1913. Finally, if the parent is blocked because of ordered siblings of its own,
  1914. the child will also be blocked."
  1915. :set (lambda (var val)
  1916. (set var val)
  1917. (if val
  1918. (add-hook 'org-blocker-hook
  1919. 'org-block-todo-from-children-or-siblings-or-parent)
  1920. (remove-hook 'org-blocker-hook
  1921. 'org-block-todo-from-children-or-siblings-or-parent)))
  1922. :group 'org-todo
  1923. :type 'boolean)
  1924. (defcustom org-enforce-todo-checkbox-dependencies nil
  1925. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1926. When this is nil, checkboxes have no influence on switching TODO states.
  1927. When non-nil, you first need to check off all check boxes before the TODO
  1928. entry can be switched to DONE.
  1929. This variable needs to be set before org.el is loaded, and you need to
  1930. restart Emacs after a change to make the change effective. The only way
  1931. to change it while Emacs is running is through the customize interface."
  1932. :set (lambda (var val)
  1933. (set var val)
  1934. (if val
  1935. (add-hook 'org-blocker-hook
  1936. 'org-block-todo-from-checkboxes)
  1937. (remove-hook 'org-blocker-hook
  1938. 'org-block-todo-from-checkboxes)))
  1939. :group 'org-todo
  1940. :type 'boolean)
  1941. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1942. "Non-nil means inserting a TODO heading is treated as state change.
  1943. So when the command `\\[org-insert-todo-heading]' is used, state change
  1944. logging will apply if appropriate. When nil, the new TODO item will
  1945. be inserted directly, and no logging will take place."
  1946. :group 'org-todo
  1947. :type 'boolean)
  1948. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1949. "Non-nil means switching TODO states with S-cursor counts as state change.
  1950. This is the default behavior. However, setting this to nil allows a
  1951. convenient way to select a TODO state and bypass any logging associated
  1952. with that."
  1953. :group 'org-todo
  1954. :type 'boolean)
  1955. (defcustom org-todo-state-tags-triggers nil
  1956. "Tag changes that should be triggered by TODO state changes.
  1957. This is a list. Each entry is
  1958. (state-change (tag . flag) .......)
  1959. State-change can be a string with a state, and empty string to indicate the
  1960. state that has no TODO keyword, or it can be one of the symbols `todo'
  1961. or `done', meaning any not-done or done state, respectively."
  1962. :group 'org-todo
  1963. :group 'org-tags
  1964. :type '(repeat
  1965. (cons (choice :tag "When changing to"
  1966. (const :tag "Not-done state" todo)
  1967. (const :tag "Done state" done)
  1968. (string :tag "State"))
  1969. (repeat
  1970. (cons :tag "Tag action"
  1971. (string :tag "Tag")
  1972. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1973. (defcustom org-log-done nil
  1974. "Information to record when a task moves to the DONE state.
  1975. Possible values are:
  1976. nil Don't add anything, just change the keyword
  1977. time Add a time stamp to the task
  1978. note Prompt for a note and add it with template `org-log-note-headings'
  1979. This option can also be set with on a per-file-basis with
  1980. #+STARTUP: nologdone
  1981. #+STARTUP: logdone
  1982. #+STARTUP: lognotedone
  1983. You can have local logging settings for a subtree by setting the LOGGING
  1984. property to one or more of these keywords."
  1985. :group 'org-todo
  1986. :group 'org-progress
  1987. :type '(choice
  1988. (const :tag "No logging" nil)
  1989. (const :tag "Record CLOSED timestamp" time)
  1990. (const :tag "Record CLOSED timestamp with note." note)))
  1991. ;; Normalize old uses of org-log-done.
  1992. (cond
  1993. ((eq org-log-done t) (setq org-log-done 'time))
  1994. ((and (listp org-log-done) (memq 'done org-log-done))
  1995. (setq org-log-done 'note)))
  1996. (defcustom org-log-reschedule nil
  1997. "Information to record when the scheduling date of a task is modified.
  1998. Possible values are:
  1999. nil Don't add anything, just change the date
  2000. time Add a time stamp to the task
  2001. note Prompt for a note and add it with template `org-log-note-headings'
  2002. This option can also be set with on a per-file-basis with
  2003. #+STARTUP: nologreschedule
  2004. #+STARTUP: logreschedule
  2005. #+STARTUP: lognotereschedule
  2006. You can have local logging settings for a subtree by setting the LOGGING
  2007. property to one or more of these keywords.
  2008. This variable has an effect when calling `org-schedule' or
  2009. `org-agenda-schedule' only."
  2010. :group 'org-todo
  2011. :group 'org-progress
  2012. :type '(choice
  2013. (const :tag "No logging" nil)
  2014. (const :tag "Record timestamp" time)
  2015. (const :tag "Record timestamp with note" note)))
  2016. (defcustom org-log-redeadline nil
  2017. "Information to record when the deadline date of a task is modified.
  2018. Possible values are:
  2019. nil Don't add anything, just change the date
  2020. time Add a time stamp to the task
  2021. note Prompt for a note and add it with template `org-log-note-headings'
  2022. This option can also be set with on a per-file-basis with
  2023. #+STARTUP: nologredeadline
  2024. #+STARTUP: logredeadline
  2025. #+STARTUP: lognoteredeadline
  2026. You can have local logging settings for a subtree by setting the LOGGING
  2027. property to one or more of these keywords.
  2028. This variable has an effect when calling `org-deadline' or
  2029. `org-agenda-deadline' only."
  2030. :group 'org-todo
  2031. :group 'org-progress
  2032. :type '(choice
  2033. (const :tag "No logging" nil)
  2034. (const :tag "Record timestamp" time)
  2035. (const :tag "Record timestamp with note." note)))
  2036. (defcustom org-log-note-clock-out nil
  2037. "Non-nil means record a note when clocking out of an item.
  2038. This can also be configured on a per-file basis by adding one of
  2039. the following lines anywhere in the buffer:
  2040. #+STARTUP: lognoteclock-out
  2041. #+STARTUP: nolognoteclock-out"
  2042. :group 'org-todo
  2043. :group 'org-progress
  2044. :type 'boolean)
  2045. (defcustom org-log-done-with-time t
  2046. "Non-nil means the CLOSED time stamp will contain date and time.
  2047. When nil, only the date will be recorded."
  2048. :group 'org-progress
  2049. :type 'boolean)
  2050. (defcustom org-log-note-headings
  2051. '((done . "CLOSING NOTE %t")
  2052. (state . "State %-12s from %-12S %t")
  2053. (note . "Note taken on %t")
  2054. (reschedule . "Rescheduled from %S on %t")
  2055. (delschedule . "Not scheduled, was %S on %t")
  2056. (redeadline . "New deadline from %S on %t")
  2057. (deldeadline . "Removed deadline, was %S on %t")
  2058. (refile . "Refiled on %t")
  2059. (clock-out . ""))
  2060. "Headings for notes added to entries.
  2061. The value is an alist, with the car being a symbol indicating the
  2062. note context, and the cdr is the heading to be used. The heading
  2063. may also be the empty string. The following placeholders can be
  2064. used:
  2065. %t a time stamp.
  2066. %T an active time stamp instead the default inactive one
  2067. %d a short-format time stamp.
  2068. %D an active short-format time stamp.
  2069. %s the new TODO state or time stamp (inactive), in double quotes.
  2070. %S the old TODO state or time stamp (inactive), in double quotes.
  2071. %u the user name.
  2072. %U full user name.
  2073. In fact, it is not a good idea to change the `state' entry,
  2074. because Agenda Log mode depends on the format of these entries."
  2075. :group 'org-todo
  2076. :group 'org-progress
  2077. :type '(list :greedy t
  2078. (cons (const :tag "Heading when closing an item" done) string)
  2079. (cons (const :tag
  2080. "Heading when changing todo state (todo sequence only)"
  2081. state) string)
  2082. (cons (const :tag "Heading when just taking a note" note) string)
  2083. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2084. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2085. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2086. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2087. (cons (const :tag "Heading when refiling" refile) string)
  2088. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2089. (unless (assq 'note org-log-note-headings)
  2090. (push '(note . "%t") org-log-note-headings))
  2091. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2092. (defcustom org-log-into-drawer nil
  2093. "Non-nil means insert state change notes and time stamps into a drawer.
  2094. When nil, state changes notes will be inserted after the headline and
  2095. any scheduling and clock lines, but not inside a drawer.
  2096. The value of this variable should be the name of the drawer to use.
  2097. LOGBOOK is proposed as the default drawer for this purpose, you can
  2098. also set this to a string to define the drawer of your choice.
  2099. A value of t is also allowed, representing \"LOGBOOK\".
  2100. A value of t or nil can also be set with on a per-file-basis with
  2101. #+STARTUP: logdrawer
  2102. #+STARTUP: nologdrawer
  2103. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2104. will be ignored.
  2105. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2106. a subtree.
  2107. Do not check directly this variable in a Lisp program. Call
  2108. function `org-log-into-drawer' instead."
  2109. :group 'org-todo
  2110. :group 'org-progress
  2111. :type '(choice
  2112. (const :tag "Not into a drawer" nil)
  2113. (const :tag "LOGBOOK" t)
  2114. (string :tag "Other")))
  2115. (defun org-log-into-drawer ()
  2116. "Name of the log drawer, as a string, or nil.
  2117. This is the value of `org-log-into-drawer'. However, if the
  2118. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2119. be used instead of the default value."
  2120. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2121. (cond ((equal p "nil") nil)
  2122. ((equal p "t") "LOGBOOK")
  2123. ((stringp p) p)
  2124. (p "LOGBOOK")
  2125. ((stringp org-log-into-drawer) org-log-into-drawer)
  2126. (org-log-into-drawer "LOGBOOK"))))
  2127. (defcustom org-log-state-notes-insert-after-drawers nil
  2128. "Non-nil means insert state change notes after any drawers in entry.
  2129. Only the drawers that *immediately* follow the headline and the
  2130. deadline/scheduled line are skipped.
  2131. When nil, insert notes right after the heading and perhaps the line
  2132. with deadline/scheduling if present.
  2133. This variable will have no effect if `org-log-into-drawer' is
  2134. set."
  2135. :group 'org-todo
  2136. :group 'org-progress
  2137. :type 'boolean)
  2138. (defcustom org-log-states-order-reversed t
  2139. "Non-nil means the latest state note will be directly after heading.
  2140. When nil, the state change notes will be ordered according to time.
  2141. This option can also be set with on a per-file-basis with
  2142. #+STARTUP: logstatesreversed
  2143. #+STARTUP: nologstatesreversed"
  2144. :group 'org-todo
  2145. :group 'org-progress
  2146. :type 'boolean)
  2147. (defcustom org-todo-repeat-to-state nil
  2148. "The TODO state to which a repeater should return the repeating task.
  2149. By default this is the first task of a TODO sequence or the
  2150. previous state of a TYPE_TODO set. But you can specify to use
  2151. the previous state in a TODO sequence or a string.
  2152. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2153. entry, which has precedence over this option."
  2154. :group 'org-todo
  2155. :version "24.1"
  2156. :type '(choice (const :tag "Use the previous TODO state" t)
  2157. (const :tag "Use the head of the TODO sequence" nil)
  2158. (string :tag "Use a specific TODO state")))
  2159. (defcustom org-log-repeat 'time
  2160. "Non-nil means record moving through the DONE state when triggering repeat.
  2161. An auto-repeating task is immediately switched back to TODO when
  2162. marked DONE. If you are not logging state changes (by adding \"@\"
  2163. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2164. record a closing note, there will be no record of the task moving
  2165. through DONE. This variable forces taking a note anyway.
  2166. nil Don't force a record
  2167. time Record a time stamp
  2168. note Prompt for a note and add it with template `org-log-note-headings'
  2169. This option can also be set with on a per-file-basis with
  2170. #+STARTUP: nologrepeat
  2171. #+STARTUP: logrepeat
  2172. #+STARTUP: lognoterepeat
  2173. You can have local logging settings for a subtree by setting the LOGGING
  2174. property to one or more of these keywords."
  2175. :group 'org-todo
  2176. :group 'org-progress
  2177. :type '(choice
  2178. (const :tag "Don't force a record" nil)
  2179. (const :tag "Force recording the DONE state" time)
  2180. (const :tag "Force recording a note with the DONE state" note)))
  2181. (defcustom org-todo-repeat-hook nil
  2182. "Hook that is run after a task has been repeated."
  2183. :package-version '(Org . "9.2")
  2184. :group 'org-todo
  2185. :type 'hook)
  2186. (defgroup org-priorities nil
  2187. "Priorities in Org mode."
  2188. :tag "Org Priorities"
  2189. :group 'org-todo)
  2190. (defcustom org-enable-priority-commands t
  2191. "Non-nil means priority commands are active.
  2192. When nil, these commands will be disabled, so that you never accidentally
  2193. set a priority."
  2194. :group 'org-priorities
  2195. :type 'boolean)
  2196. (defcustom org-highest-priority ?A
  2197. "The highest priority of TODO items. A character like ?A, ?B etc.
  2198. Must have a smaller ASCII number than `org-lowest-priority'."
  2199. :group 'org-priorities
  2200. :type 'character)
  2201. (defcustom org-lowest-priority ?C
  2202. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2203. Must have a larger ASCII number than `org-highest-priority'."
  2204. :group 'org-priorities
  2205. :type 'character)
  2206. (defcustom org-default-priority ?B
  2207. "The default priority of TODO items.
  2208. This is the priority an item gets if no explicit priority is given.
  2209. When starting to cycle on an empty priority the first step in the cycle
  2210. depends on `org-priority-start-cycle-with-default'. The resulting first
  2211. step priority must not exceed the range from `org-highest-priority' to
  2212. `org-lowest-priority' which means that `org-default-priority' has to be
  2213. in this range exclusive or inclusive the range boundaries. Else the
  2214. first step refuses to set the default and the second will fall back
  2215. to (depending on the command used) the highest or lowest priority."
  2216. :group 'org-priorities
  2217. :type 'character)
  2218. (defcustom org-priority-start-cycle-with-default t
  2219. "Non-nil means start with default priority when starting to cycle.
  2220. When this is nil, the first step in the cycle will be (depending on the
  2221. command used) one higher or lower than the default priority.
  2222. See also `org-default-priority'."
  2223. :group 'org-priorities
  2224. :type 'boolean)
  2225. (defcustom org-get-priority-function nil
  2226. "Function to extract the priority from a string.
  2227. The string is normally the headline. If this is nil Org computes the
  2228. priority from the priority cookie like [#A] in the headline. It returns
  2229. an integer, increasing by 1000 for each priority level.
  2230. The user can set a different function here, which should take a string
  2231. as an argument and return the numeric priority."
  2232. :group 'org-priorities
  2233. :version "24.1"
  2234. :type '(choice
  2235. (const nil)
  2236. (function)))
  2237. (defgroup org-time nil
  2238. "Options concerning time stamps and deadlines in Org mode."
  2239. :tag "Org Time"
  2240. :group 'org)
  2241. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2242. "Number of minutes to round time stamps to.
  2243. \\<org-mode-map>\
  2244. These are two values, the first applies when first creating a time stamp.
  2245. The second applies when changing it with the commands `S-up' and `S-down'.
  2246. When changing the time stamp, this means that it will change in steps
  2247. of N minutes, as given by the second value.
  2248. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2249. numbers should be factors of 60, so for example 5, 10, 15.
  2250. When this is larger than 1, you can still force an exact time stamp by using
  2251. a double prefix argument to a time stamp command like \
  2252. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2253. and by using a prefix arg to `S-up/down' to specify the exact number
  2254. of minutes to shift."
  2255. :group 'org-time
  2256. :get (lambda (var) ; Make sure both elements are there
  2257. (if (integerp (default-value var))
  2258. (list (default-value var) 5)
  2259. (default-value var)))
  2260. :type '(list
  2261. (integer :tag "when inserting times")
  2262. (integer :tag "when modifying times")))
  2263. ;; Normalize old customizations of this variable.
  2264. (when (integerp org-time-stamp-rounding-minutes)
  2265. (setq org-time-stamp-rounding-minutes
  2266. (list org-time-stamp-rounding-minutes
  2267. org-time-stamp-rounding-minutes)))
  2268. (defcustom org-display-custom-times nil
  2269. "Non-nil means overlay custom formats over all time stamps.
  2270. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2271. To turn this on on a per-file basis, insert anywhere in the file:
  2272. #+STARTUP: customtime"
  2273. :group 'org-time
  2274. :set 'set-default
  2275. :type 'sexp)
  2276. (make-variable-buffer-local 'org-display-custom-times)
  2277. (defcustom org-time-stamp-custom-formats
  2278. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2279. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2280. These are overlaid over the default ISO format if the variable
  2281. `org-display-custom-times' is set. Time like %H:%M should be at the
  2282. end of the second format. The custom formats are also honored by export
  2283. commands, if custom time display is turned on at the time of export."
  2284. :group 'org-time
  2285. :type 'sexp)
  2286. (defun org-time-stamp-format (&optional long inactive)
  2287. "Get the right format for a time string."
  2288. (let ((f (if long (cdr org-time-stamp-formats)
  2289. (car org-time-stamp-formats))))
  2290. (if inactive
  2291. (concat "[" (substring f 1 -1) "]")
  2292. f)))
  2293. (defcustom org-deadline-warning-days 14
  2294. "Number of days before expiration during which a deadline becomes active.
  2295. This variable governs the display in sparse trees and in the agenda.
  2296. When 0 or negative, it means use this number (the absolute value of it)
  2297. even if a deadline has a different individual lead time specified.
  2298. Custom commands can set this variable in the options section."
  2299. :group 'org-time
  2300. :group 'org-agenda-daily/weekly
  2301. :type 'integer)
  2302. (defcustom org-scheduled-delay-days 0
  2303. "Number of days before a scheduled item becomes active.
  2304. This variable governs the display in sparse trees and in the agenda.
  2305. The default value (i.e. 0) means: don't delay scheduled item.
  2306. When negative, it means use this number (the absolute value of it)
  2307. even if a scheduled item has a different individual delay time
  2308. specified.
  2309. Custom commands can set this variable in the options section."
  2310. :group 'org-time
  2311. :group 'org-agenda-daily/weekly
  2312. :version "24.4"
  2313. :package-version '(Org . "8.0")
  2314. :type 'integer)
  2315. (defcustom org-read-date-prefer-future t
  2316. "Non-nil means assume future for incomplete date input from user.
  2317. This affects the following situations:
  2318. 1. The user gives a month but not a year.
  2319. For example, if it is April and you enter \"feb 2\", this will be read
  2320. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2321. 2. The user gives a day, but no month.
  2322. For example, if today is the 15th, and you enter \"3\", Org will read
  2323. this as the third of *next* month. However, if you enter \"17\",
  2324. it will be considered as *this* month.
  2325. If you set this variable to the symbol `time', then also the following
  2326. will work:
  2327. 3. If the user gives a time.
  2328. If the time is before now, it will be interpreted as tomorrow.
  2329. Currently none of this works for ISO week specifications.
  2330. When this option is nil, the current day, month and year will always be
  2331. used as defaults.
  2332. See also `org-agenda-jump-prefer-future'."
  2333. :group 'org-time
  2334. :type '(choice
  2335. (const :tag "Never" nil)
  2336. (const :tag "Check month and day" t)
  2337. (const :tag "Check month, day, and time" time)))
  2338. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2339. "Should the agenda jump command prefer the future for incomplete dates?
  2340. The default is to do the same as configured in `org-read-date-prefer-future'.
  2341. But you can also set a deviating value here.
  2342. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2343. :group 'org-agenda
  2344. :group 'org-time
  2345. :version "24.1"
  2346. :type '(choice
  2347. (const :tag "Use org-read-date-prefer-future"
  2348. org-read-date-prefer-future)
  2349. (const :tag "Never" nil)
  2350. (const :tag "Always" t)))
  2351. (defcustom org-read-date-force-compatible-dates t
  2352. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2353. Depending on the system Emacs is running on, certain dates cannot
  2354. be represented with the type used internally to represent time.
  2355. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2356. correctly. Some systems allow for earlier dates, some for later,
  2357. some for both. One way to find out is to insert any date into an
  2358. Org buffer, putting the cursor on the year and hitting S-up and
  2359. S-down to test the range.
  2360. When this variable is set to t, the date/time prompt will not let
  2361. you specify dates outside the 1970-2037 range, so it is certain that
  2362. these dates will work in whatever version of Emacs you are
  2363. running, and also that you can move a file from one Emacs implementation
  2364. to another. Whenever Org is forcing the year for you, it will display
  2365. a message and beep.
  2366. When this variable is nil, Org will check if the date is
  2367. representable in the specific Emacs implementation you are using.
  2368. If not, it will force a year, usually the current year, and beep
  2369. to remind you. Currently this setting is not recommended because
  2370. the likelihood that you will open your Org files in an Emacs that
  2371. has limited date range is not negligible.
  2372. A workaround for this problem is to use diary sexp dates for time
  2373. stamps outside of this range."
  2374. :group 'org-time
  2375. :version "24.1"
  2376. :type 'boolean)
  2377. (defcustom org-read-date-display-live t
  2378. "Non-nil means display current interpretation of date prompt live.
  2379. This display will be in an overlay, in the minibuffer."
  2380. :group 'org-time
  2381. :type 'boolean)
  2382. (defvaralias 'org-popup-calendar-for-date-prompt
  2383. 'org-read-date-popup-calendar)
  2384. (defcustom org-read-date-popup-calendar t
  2385. "Non-nil means pop up a calendar when prompting for a date.
  2386. In the calendar, the date can be selected with mouse-1. However, the
  2387. minibuffer will also be active, and you can simply enter the date as well.
  2388. When nil, only the minibuffer will be available."
  2389. :group 'org-time
  2390. :type 'boolean)
  2391. (defcustom org-extend-today-until 0
  2392. "The hour when your day really ends. Must be an integer.
  2393. This has influence for the following applications:
  2394. - When switching the agenda to \"today\". If it is still earlier than
  2395. the time given here, the day recognized as TODAY is actually yesterday.
  2396. - When a date is read from the user and it is still before the time given
  2397. here, the current date and time will be assumed to be yesterday, 23:59.
  2398. Also, timestamps inserted in capture templates follow this rule.
  2399. IMPORTANT: This is a feature whose implementation is and likely will
  2400. remain incomplete. Really, it is only here because past midnight seems to
  2401. be the favorite working time of John Wiegley :-)"
  2402. :group 'org-time
  2403. :type 'integer)
  2404. (defcustom org-use-effective-time nil
  2405. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2406. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2407. \"effective time\" of any timestamps between midnight and 8am will be
  2408. 23:59 of the previous day."
  2409. :group 'org-time
  2410. :version "24.1"
  2411. :type 'boolean)
  2412. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2413. "When non-nil, use the last clock out time for `org-todo'.
  2414. Note that this option has precedence over the combined use of
  2415. `org-use-effective-time' and `org-extend-today-until'."
  2416. :group 'org-time
  2417. :version "24.4"
  2418. :package-version '(Org . "8.0")
  2419. :type 'boolean)
  2420. (defcustom org-edit-timestamp-down-means-later nil
  2421. "Non-nil means S-down will increase the time in a time stamp.
  2422. When nil, S-up will increase."
  2423. :group 'org-time
  2424. :type 'boolean)
  2425. (defcustom org-calendar-follow-timestamp-change t
  2426. "Non-nil means make the calendar window follow timestamp changes.
  2427. When a timestamp is modified and the calendar window is visible, it will be
  2428. moved to the new date."
  2429. :group 'org-time
  2430. :type 'boolean)
  2431. (defgroup org-tags nil
  2432. "Options concerning tags in Org mode."
  2433. :tag "Org Tags"
  2434. :group 'org)
  2435. (defcustom org-tag-alist nil
  2436. "Default tags available in Org files.
  2437. The value of this variable is an alist. Associations either:
  2438. (TAG)
  2439. (TAG . SELECT)
  2440. (SPECIAL)
  2441. where TAG is a tag as a string, SELECT is character, used to
  2442. select that tag through the fast tag selection interface, and
  2443. SPECIAL is one of the following keywords: `:startgroup',
  2444. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2445. `:newline'. These keywords are used to define a hierarchy of
  2446. tags. See manual for details.
  2447. When this variable is nil, Org mode bases tag input on what is
  2448. already in the buffer. The value can be overridden locally by
  2449. using a TAGS keyword, e.g.,
  2450. #+TAGS: tag1 tag2
  2451. See also `org-tag-persistent-alist' to sidestep this behavior."
  2452. :group 'org-tags
  2453. :type '(repeat
  2454. (choice
  2455. (cons :tag "Tag with key"
  2456. (string :tag "Tag name")
  2457. (character :tag "Access char"))
  2458. (list :tag "Tag" (string :tag "Tag name"))
  2459. (const :tag "Start radio group" (:startgroup))
  2460. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2461. (const :tag "Group tags delimiter" (:grouptags))
  2462. (const :tag "End radio group" (:endgroup))
  2463. (const :tag "End tag group, non distinct" (:endgrouptag))
  2464. (const :tag "New line" (:newline)))))
  2465. (defcustom org-tag-persistent-alist nil
  2466. "Tags always available in Org files.
  2467. The value of this variable is an alist. Associations either:
  2468. (TAG)
  2469. (TAG . SELECT)
  2470. (SPECIAL)
  2471. where TAG is a tag as a string, SELECT is a character, used to
  2472. select that tag through the fast tag selection interface, and
  2473. SPECIAL is one of the following keywords: `:startgroup',
  2474. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2475. `:newline'. These keywords are used to define a hierarchy of
  2476. tags. See manual for details.
  2477. Unlike to `org-tag-alist', tags defined in this variable do not
  2478. depend on a local TAGS keyword. Instead, to disable these tags
  2479. on a per-file basis, insert anywhere in the file:
  2480. #+STARTUP: noptag"
  2481. :group 'org-tags
  2482. :type '(repeat
  2483. (choice
  2484. (cons :tag "Tag with key"
  2485. (string :tag "Tag name")
  2486. (character :tag "Access char"))
  2487. (list :tag "Tag" (string :tag "Tag name"))
  2488. (const :tag "Start radio group" (:startgroup))
  2489. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2490. (const :tag "Group tags delimiter" (:grouptags))
  2491. (const :tag "End radio group" (:endgroup))
  2492. (const :tag "End tag group, non distinct" (:endgrouptag))
  2493. (const :tag "New line" (:newline)))))
  2494. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2495. "If non-nil, always offer completion for all tags of all agenda files.
  2496. Setting this variable locally allows for dynamic generation of tag
  2497. completions in capture buffers.
  2498. (add-hook \\='org-capture-mode-hook
  2499. (lambda ()
  2500. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2501. :group 'org-tags
  2502. :version "24.1"
  2503. :type 'boolean)
  2504. (defvar org-file-tags nil
  2505. "List of tags that can be inherited by all entries in the file.
  2506. The tags will be inherited if the variable `org-use-tag-inheritance'
  2507. says they should be.
  2508. This variable is populated from #+FILETAGS lines.")
  2509. (defcustom org-use-fast-tag-selection 'auto
  2510. "Non-nil means use fast tag selection scheme.
  2511. This is a special interface to select and deselect tags with single keys.
  2512. When nil, fast selection is never used.
  2513. When the symbol `auto', fast selection is used if and only if selection
  2514. characters for tags have been configured, either through the variable
  2515. `org-tag-alist' or through a #+TAGS line in the buffer.
  2516. When t, fast selection is always used and selection keys are assigned
  2517. automatically if necessary."
  2518. :group 'org-tags
  2519. :type '(choice
  2520. (const :tag "Always" t)
  2521. (const :tag "Never" nil)
  2522. (const :tag "When selection characters are configured" auto)))
  2523. (defcustom org-fast-tag-selection-single-key nil
  2524. "Non-nil means fast tag selection exits after first change.
  2525. When nil, you have to press RET to exit it.
  2526. During fast tag selection, you can toggle this flag with `C-c'.
  2527. This variable can also have the value `expert'. In this case, the window
  2528. displaying the tags menu is not even shown, until you press C-c again."
  2529. :group 'org-tags
  2530. :type '(choice
  2531. (const :tag "No" nil)
  2532. (const :tag "Yes" t)
  2533. (const :tag "Expert" expert)))
  2534. (defvar org-fast-tag-selection-include-todo nil
  2535. "Non-nil means fast tags selection interface will also offer TODO states.
  2536. This is an undocumented feature, you should not rely on it.")
  2537. (defcustom org-tags-column -77
  2538. "The column to which tags should be indented in a headline.
  2539. If this number is positive, it specifies the column. If it is negative,
  2540. it means that the tags should be flushright to that column. For example,
  2541. -80 works well for a normal 80 character screen.
  2542. When 0, place tags directly after headline text, with only one space in
  2543. between."
  2544. :group 'org-tags
  2545. :type 'integer)
  2546. (defcustom org-auto-align-tags t
  2547. "Non-nil keeps tags aligned when modifying headlines.
  2548. Some operations (i.e. demoting) change the length of a headline and
  2549. therefore shift the tags around. With this option turned on, after
  2550. each such operation the tags are again aligned to `org-tags-column'."
  2551. :group 'org-tags
  2552. :type 'boolean)
  2553. (defcustom org-use-tag-inheritance t
  2554. "Non-nil means tags in levels apply also for sublevels.
  2555. When nil, only the tags directly given in a specific line apply there.
  2556. This may also be a list of tags that should be inherited, or a regexp that
  2557. matches tags that should be inherited. Additional control is possible
  2558. with the variable `org-tags-exclude-from-inheritance' which gives an
  2559. explicit list of tags to be excluded from inheritance, even if the value of
  2560. `org-use-tag-inheritance' would select it for inheritance.
  2561. If this option is t, a match early-on in a tree can lead to a large
  2562. number of matches in the subtree when constructing the agenda or creating
  2563. a sparse tree. If you only want to see the first match in a tree during
  2564. a search, check out the variable `org-tags-match-list-sublevels'."
  2565. :group 'org-tags
  2566. :type '(choice
  2567. (const :tag "Not" nil)
  2568. (const :tag "Always" t)
  2569. (repeat :tag "Specific tags" (string :tag "Tag"))
  2570. (regexp :tag "Tags matched by regexp")))
  2571. (defcustom org-tags-exclude-from-inheritance nil
  2572. "List of tags that should never be inherited.
  2573. This is a way to exclude a few tags from inheritance. For way to do
  2574. the opposite, to actively allow inheritance for selected tags,
  2575. see the variable `org-use-tag-inheritance'."
  2576. :group 'org-tags
  2577. :type '(repeat (string :tag "Tag")))
  2578. (defun org-tag-inherit-p (tag)
  2579. "Check if TAG is one that should be inherited."
  2580. (cond
  2581. ((member tag org-tags-exclude-from-inheritance) nil)
  2582. ((eq org-use-tag-inheritance t) t)
  2583. ((not org-use-tag-inheritance) nil)
  2584. ((stringp org-use-tag-inheritance)
  2585. (string-match org-use-tag-inheritance tag))
  2586. ((listp org-use-tag-inheritance)
  2587. (member tag org-use-tag-inheritance))
  2588. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2589. (defcustom org-tags-match-list-sublevels t
  2590. "Non-nil means list also sublevels of headlines matching a search.
  2591. This variable applies to tags/property searches, and also to stuck
  2592. projects because this search is based on a tags match as well.
  2593. When set to the symbol `indented', sublevels are indented with
  2594. leading dots.
  2595. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2596. the sublevels of a headline matching a tag search often also match
  2597. the same search. Listing all of them can create very long lists.
  2598. Setting this variable to nil causes subtrees of a match to be skipped.
  2599. This variable is semi-obsolete and probably should always be true. It
  2600. is better to limit inheritance to certain tags using the variables
  2601. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2602. :group 'org-tags
  2603. :type '(choice
  2604. (const :tag "No, don't list them" nil)
  2605. (const :tag "Yes, do list them" t)
  2606. (const :tag "List them, indented with leading dots" indented)))
  2607. (defcustom org-tags-sort-function nil
  2608. "When set, tags are sorted using this function as a comparator."
  2609. :group 'org-tags
  2610. :type '(choice
  2611. (const :tag "No sorting" nil)
  2612. (const :tag "Alphabetical" org-string-collate-lessp)
  2613. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2614. (function :tag "Custom function" nil)))
  2615. (defvar org-tags-history nil
  2616. "History of minibuffer reads for tags.")
  2617. (defvar org-last-tags-completion-table nil
  2618. "The last used completion table for tags.")
  2619. (defvar org-after-tags-change-hook nil
  2620. "Hook that is run after the tags in a line have changed.")
  2621. (defgroup org-properties nil
  2622. "Options concerning properties in Org mode."
  2623. :tag "Org Properties"
  2624. :group 'org)
  2625. (defcustom org-property-format "%-10s %s"
  2626. "How property key/value pairs should be formatted by `indent-line'.
  2627. When `indent-line' hits a property definition, it will format the line
  2628. according to this format, mainly to make sure that the values are
  2629. lined-up with respect to each other."
  2630. :group 'org-properties
  2631. :type 'string)
  2632. (defcustom org-properties-postprocess-alist nil
  2633. "Alist of properties and functions to adjust inserted values.
  2634. Elements of this alist must be of the form
  2635. ([string] [function])
  2636. where [string] must be a property name and [function] must be a
  2637. lambda expression: this lambda expression must take one argument,
  2638. the value to adjust, and return the new value as a string.
  2639. For example, this element will allow the property \"Remaining\"
  2640. to be updated wrt the relation between the \"Effort\" property
  2641. and the clock summary:
  2642. ((\"Remaining\" (lambda(value)
  2643. (let ((clocksum (org-clock-sum-current-item))
  2644. (effort (org-duration-to-minutes
  2645. (org-entry-get (point) \"Effort\"))))
  2646. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2647. :group 'org-properties
  2648. :version "24.1"
  2649. :type '(alist :key-type (string :tag "Property")
  2650. :value-type (function :tag "Function")))
  2651. (defcustom org-use-property-inheritance nil
  2652. "Non-nil means properties apply also for sublevels.
  2653. This setting is chiefly used during property searches. Turning it on can
  2654. cause significant overhead when doing a search, which is why it is not
  2655. on by default.
  2656. When nil, only the properties directly given in the current entry count.
  2657. When t, every property is inherited. The value may also be a list of
  2658. properties that should have inheritance, or a regular expression matching
  2659. properties that should be inherited.
  2660. However, note that some special properties use inheritance under special
  2661. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2662. and the properties ending in \"_ALL\" when they are used as descriptor
  2663. for valid values of a property.
  2664. Note for programmers:
  2665. When querying an entry with `org-entry-get', you can control if inheritance
  2666. should be used. By default, `org-entry-get' looks only at the local
  2667. properties. You can request inheritance by setting the inherit argument
  2668. to t (to force inheritance) or to `selective' (to respect the setting
  2669. in this variable)."
  2670. :group 'org-properties
  2671. :type '(choice
  2672. (const :tag "Not" nil)
  2673. (const :tag "Always" t)
  2674. (repeat :tag "Specific properties" (string :tag "Property"))
  2675. (regexp :tag "Properties matched by regexp")))
  2676. (defun org-property-inherit-p (property)
  2677. "Return a non-nil value if PROPERTY should be inherited."
  2678. (cond
  2679. ((eq org-use-property-inheritance t) t)
  2680. ((not org-use-property-inheritance) nil)
  2681. ((stringp org-use-property-inheritance)
  2682. (string-match org-use-property-inheritance property))
  2683. ((listp org-use-property-inheritance)
  2684. (member-ignore-case property org-use-property-inheritance))
  2685. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2686. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2687. "The default column format, if no other format has been defined.
  2688. This variable can be set on the per-file basis by inserting a line
  2689. #+COLUMNS: %25ITEM ....."
  2690. :group 'org-properties
  2691. :type 'string)
  2692. (defcustom org-columns-default-format-for-agenda nil
  2693. "The default column format in an agenda buffer.
  2694. This will be used for column view in the agenda unless a format has
  2695. been set by adding `org-overriding-columns-format' to the local
  2696. settings list of a custom agenda view. When nil, the columns format
  2697. for the first item in the agenda list will be used, or as a fall-back,
  2698. `org-columns-default-format'."
  2699. :group 'org-properties
  2700. :type '(choice
  2701. (const :tag "No default" nil)
  2702. (string :tag "Format string")))
  2703. (defcustom org-columns-ellipses ".."
  2704. "The ellipses to be used when a field in column view is truncated.
  2705. When this is the empty string, as many characters as possible are shown,
  2706. but then there will be no visual indication that the field has been truncated.
  2707. When this is a string of length N, the last N characters of a truncated
  2708. field are replaced by this string. If the column is narrower than the
  2709. ellipses string, only part of the ellipses string will be shown."
  2710. :group 'org-properties
  2711. :type 'string)
  2712. (defconst org-global-properties-fixed
  2713. '(("VISIBILITY_ALL" . "folded children content all")
  2714. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2715. "List of property/value pairs that can be inherited by any entry.
  2716. These are fixed values, for the preset properties. The user variable
  2717. that can be used to add to this list is `org-global-properties'.
  2718. The entries in this list are cons cells where the car is a property
  2719. name and cdr is a string with the value. If the value represents
  2720. multiple items like an \"_ALL\" property, separate the items by
  2721. spaces.")
  2722. (defcustom org-global-properties nil
  2723. "List of property/value pairs that can be inherited by any entry.
  2724. This list will be combined with the constant `org-global-properties-fixed'.
  2725. The entries in this list are cons cells where the car is a property
  2726. name and cdr is a string with the value.
  2727. You can set buffer-local values for the same purpose in the variable
  2728. `org-file-properties' this by adding lines like
  2729. #+PROPERTY: NAME VALUE"
  2730. :group 'org-properties
  2731. :type '(repeat
  2732. (cons (string :tag "Property")
  2733. (string :tag "Value"))))
  2734. (defvar-local org-file-properties nil
  2735. "List of property/value pairs that can be inherited by any entry.
  2736. Valid for the current buffer.
  2737. This variable is populated from #+PROPERTY lines.")
  2738. (defgroup org-agenda nil
  2739. "Options concerning agenda views in Org mode."
  2740. :tag "Org Agenda"
  2741. :group 'org)
  2742. (defvar-local org-category nil
  2743. "Variable used by Org files to set a category for agenda display.
  2744. Such files should use a file variable to set it, for example
  2745. # -*- mode: org; org-category: \"ELisp\"
  2746. or contain a special line
  2747. #+CATEGORY: ELisp
  2748. If the file does not specify a category, then file's base name
  2749. is used instead.")
  2750. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2751. (defcustom org-agenda-files nil
  2752. "The files to be used for agenda display.
  2753. If an entry is a directory, all files in that directory that are matched
  2754. by `org-agenda-file-regexp' will be part of the file list.
  2755. If the value of the variable is not a list but a single file name, then
  2756. the list of agenda files is actually stored and maintained in that file,
  2757. one agenda file per line. In this file paths can be given relative to
  2758. `org-directory'. Tilde expansion and environment variable substitution
  2759. are also made.
  2760. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2761. and removed with `\\[org-remove-file]'."
  2762. :group 'org-agenda
  2763. :type '(choice
  2764. (repeat :tag "List of files and directories" file)
  2765. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2766. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2767. "Regular expression to match files for `org-agenda-files'.
  2768. If any element in the list in that variable contains a directory instead
  2769. of a normal file, all files in that directory that are matched by this
  2770. regular expression will be included."
  2771. :group 'org-agenda
  2772. :type 'regexp)
  2773. (defvaralias 'org-agenda-multi-occur-extra-files
  2774. 'org-agenda-text-search-extra-files)
  2775. (defcustom org-agenda-text-search-extra-files nil
  2776. "List of extra files to be searched by text search commands.
  2777. These files will be searched in addition to the agenda files by the
  2778. commands `org-search-view' (`\\[org-agenda] s') \
  2779. and `org-occur-in-agenda-files'.
  2780. Note that these files will only be searched for text search commands,
  2781. not for the other agenda views like todo lists, tag searches or the weekly
  2782. agenda. This variable is intended to list notes and possibly archive files
  2783. that should also be searched by these two commands.
  2784. In fact, if the first element in the list is the symbol `agenda-archives',
  2785. then all archive files of all agenda files will be added to the search
  2786. scope."
  2787. :group 'org-agenda
  2788. :type '(set :greedy t
  2789. (const :tag "Agenda Archives" agenda-archives)
  2790. (repeat :inline t (file))))
  2791. (defcustom org-agenda-skip-unavailable-files nil
  2792. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2793. A nil value means to remove them, after a query, from the list."
  2794. :group 'org-agenda
  2795. :type 'boolean)
  2796. (defgroup org-latex nil
  2797. "Options for embedding LaTeX code into Org mode."
  2798. :tag "Org LaTeX"
  2799. :group 'org)
  2800. (defcustom org-format-latex-options
  2801. '(:foreground default :background default :scale 1.0
  2802. :html-foreground "Black" :html-background "Transparent"
  2803. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2804. "Options for creating images from LaTeX fragments.
  2805. This is a property list with the following properties:
  2806. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2807. `default' means use the foreground of the default face.
  2808. `auto' means use the foreground from the text face.
  2809. :background the background color, or \"Transparent\".
  2810. `default' means use the background of the default face.
  2811. `auto' means use the background from the text face.
  2812. :scale a scaling factor for the size of the images, to get more pixels
  2813. :html-foreground, :html-background, :html-scale
  2814. the same numbers for HTML export.
  2815. :matchers a list indicating which matchers should be used to
  2816. find LaTeX fragments. Valid members of this list are:
  2817. \"begin\" find environments
  2818. \"$1\" find single characters surrounded by $.$
  2819. \"$\" find math expressions surrounded by $...$
  2820. \"$$\" find math expressions surrounded by $$....$$
  2821. \"\\(\" find math expressions surrounded by \\(...\\)
  2822. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2823. :group 'org-latex
  2824. :type 'plist)
  2825. (defcustom org-format-latex-signal-error t
  2826. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2827. When nil, just push out a message."
  2828. :group 'org-latex
  2829. :version "24.1"
  2830. :type 'boolean)
  2831. (defcustom org-latex-to-mathml-jar-file nil
  2832. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2833. Use this to specify additional executable file say a jar file.
  2834. When using MathToWeb as the converter, specify the full-path to
  2835. your mathtoweb.jar file."
  2836. :group 'org-latex
  2837. :version "24.1"
  2838. :type '(choice
  2839. (const :tag "None" nil)
  2840. (file :tag "JAR file" :must-match t)))
  2841. (defcustom org-latex-to-mathml-convert-command nil
  2842. "Command to convert LaTeX fragments to MathML.
  2843. Replace format-specifiers in the command as noted below and use
  2844. `shell-command' to convert LaTeX to MathML.
  2845. %j: Executable file in fully expanded form as specified by
  2846. `org-latex-to-mathml-jar-file'.
  2847. %I: Input LaTeX file in fully expanded form.
  2848. %i: The latex fragment to be converted.
  2849. %o: Output MathML file.
  2850. This command is used by `org-create-math-formula'.
  2851. When using MathToWeb as the converter, set this option to
  2852. \"java -jar %j -unicode -force -df %o %I\".
  2853. When using LaTeXML set this option to
  2854. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2855. :group 'org-latex
  2856. :version "24.1"
  2857. :type '(choice
  2858. (const :tag "None" nil)
  2859. (string :tag "\nShell command")))
  2860. (defcustom org-preview-latex-default-process 'dvipng
  2861. "The default process to convert LaTeX fragments to image files.
  2862. All available processes and theirs documents can be found in
  2863. `org-preview-latex-process-alist', which see."
  2864. :group 'org-latex
  2865. :version "26.1"
  2866. :package-version '(Org . "9.0")
  2867. :type 'symbol)
  2868. (defcustom org-preview-latex-process-alist
  2869. '((dvipng
  2870. :programs ("latex" "dvipng")
  2871. :description "dvi > png"
  2872. :message "you need to install the programs: latex and dvipng."
  2873. :image-input-type "dvi"
  2874. :image-output-type "png"
  2875. :image-size-adjust (1.0 . 1.0)
  2876. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2877. :image-converter ("dvipng -D %D -T tight -o %O %f"))
  2878. (dvisvgm
  2879. :programs ("latex" "dvisvgm")
  2880. :description "dvi > svg"
  2881. :message "you need to install the programs: latex and dvisvgm."
  2882. :image-input-type "dvi"
  2883. :image-output-type "svg"
  2884. :image-size-adjust (1.7 . 1.5)
  2885. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2886. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2887. (imagemagick
  2888. :programs ("latex" "convert")
  2889. :description "pdf > png"
  2890. :message "you need to install the programs: latex and imagemagick."
  2891. :image-input-type "pdf"
  2892. :image-output-type "png"
  2893. :image-size-adjust (1.0 . 1.0)
  2894. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2895. :image-converter
  2896. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2897. "Definitions of external processes for LaTeX previewing.
  2898. Org mode can use some external commands to generate TeX snippet's images for
  2899. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2900. `org-create-formula-image' how to call them.
  2901. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2902. PROPERTIES accepts the following attributes:
  2903. :programs list of strings, required programs.
  2904. :description string, describe the process.
  2905. :message string, message it when required programs cannot be found.
  2906. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2907. :image-output-type string, output file type of image converter (e.g., \"png\").
  2908. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2909. image size showed in buffer and the cdr element is for
  2910. HTML file. This option is only useful for process
  2911. developers, users should use variable
  2912. `org-format-latex-options' instead.
  2913. :post-clean list of strings, files matched are to be cleaned up once
  2914. the image is generated. When nil, the files with \".dvi\",
  2915. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2916. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2917. be cleaned up.
  2918. :latex-header list of strings, the LaTeX header of the snippet file.
  2919. When nil, the fallback value is used instead, which is
  2920. controlled by `org-format-latex-header',
  2921. `org-latex-default-packages-alist' and
  2922. `org-latex-packages-alist', which see.
  2923. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2924. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2925. replaced with values defined below.
  2926. :image-converter list of image converter commands strings. Each of them is
  2927. given to the shell and supports any of the following
  2928. place-holders defined below.
  2929. Place-holders used by `:image-converter' and `:latex-compiler':
  2930. %f input file name
  2931. %b base name of input file
  2932. %o base directory of input file
  2933. %O absolute output file name
  2934. Place-holders only used by `:image-converter':
  2935. %D dpi, which is used to adjust image size by some processing commands.
  2936. %S the image size scale ratio, which is used to adjust image size by some
  2937. processing commands."
  2938. :group 'org-latex
  2939. :version "26.1"
  2940. :package-version '(Org . "9.0")
  2941. :type '(alist :tag "LaTeX to image backends"
  2942. :value-type (plist)))
  2943. (defcustom org-preview-latex-image-directory "ltximg/"
  2944. "Path to store latex preview images.
  2945. A relative path here creates many directories relative to the
  2946. processed Org files paths. An absolute path puts all preview
  2947. images at the same place."
  2948. :group 'org-latex
  2949. :version "26.1"
  2950. :package-version '(Org . "9.0")
  2951. :type 'string)
  2952. (defun org-format-latex-mathml-available-p ()
  2953. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2954. (save-match-data
  2955. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2956. org-latex-to-mathml-convert-command)
  2957. (let ((executable (car (split-string
  2958. org-latex-to-mathml-convert-command))))
  2959. (when (executable-find executable)
  2960. (if (string-match
  2961. "%j" org-latex-to-mathml-convert-command)
  2962. (file-readable-p org-latex-to-mathml-jar-file)
  2963. t))))))
  2964. (defcustom org-format-latex-header "\\documentclass{article}
  2965. \\usepackage[usenames]{color}
  2966. \[PACKAGES]
  2967. \[DEFAULT-PACKAGES]
  2968. \\pagestyle{empty} % do not remove
  2969. % The settings below are copied from fullpage.sty
  2970. \\setlength{\\textwidth}{\\paperwidth}
  2971. \\addtolength{\\textwidth}{-3cm}
  2972. \\setlength{\\oddsidemargin}{1.5cm}
  2973. \\addtolength{\\oddsidemargin}{-2.54cm}
  2974. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2975. \\setlength{\\textheight}{\\paperheight}
  2976. \\addtolength{\\textheight}{-\\headheight}
  2977. \\addtolength{\\textheight}{-\\headsep}
  2978. \\addtolength{\\textheight}{-\\footskip}
  2979. \\addtolength{\\textheight}{-3cm}
  2980. \\setlength{\\topmargin}{1.5cm}
  2981. \\addtolength{\\topmargin}{-2.54cm}"
  2982. "The document header used for processing LaTeX fragments.
  2983. It is imperative that this header make sure that no page number
  2984. appears on the page. The package defined in the variables
  2985. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2986. will either replace the placeholder \"[PACKAGES]\" in this
  2987. header, or they will be appended."
  2988. :group 'org-latex
  2989. :type 'string)
  2990. (defun org-set-packages-alist (var val)
  2991. "Set the packages alist and make sure it has 3 elements per entry."
  2992. (set var (mapcar (lambda (x)
  2993. (if (and (consp x) (= (length x) 2))
  2994. (list (car x) (nth 1 x) t)
  2995. x))
  2996. val)))
  2997. (defun org-get-packages-alist (var)
  2998. "Get the packages alist and make sure it has 3 elements per entry."
  2999. (mapcar (lambda (x)
  3000. (if (and (consp x) (= (length x) 2))
  3001. (list (car x) (nth 1 x) t)
  3002. x))
  3003. (default-value var)))
  3004. (defcustom org-latex-default-packages-alist
  3005. '(("AUTO" "inputenc" t ("pdflatex"))
  3006. ("T1" "fontenc" t ("pdflatex"))
  3007. ("" "graphicx" t)
  3008. ("" "grffile" t)
  3009. ("" "longtable" nil)
  3010. ("" "wrapfig" nil)
  3011. ("" "rotating" nil)
  3012. ("normalem" "ulem" t)
  3013. ("" "amsmath" t)
  3014. ("" "textcomp" t)
  3015. ("" "amssymb" t)
  3016. ("" "capt-of" nil)
  3017. ("" "hyperref" nil))
  3018. "Alist of default packages to be inserted in the header.
  3019. Change this only if one of the packages here causes an
  3020. incompatibility with another package you are using.
  3021. The packages in this list are needed by one part or another of
  3022. Org mode to function properly:
  3023. - inputenc, fontenc: for basic font and character selection
  3024. - graphicx: for including images
  3025. - grffile: allow periods and spaces in graphics file names
  3026. - longtable: For multipage tables
  3027. - wrapfig: for figure placement
  3028. - rotating: for sideways figures and tables
  3029. - ulem: for underline and strike-through
  3030. - amsmath: for subscript and superscript and math environments
  3031. - textcomp, amssymb: for various symbols used
  3032. for interpreting the entities in `org-entities'. You can skip
  3033. some of these packages if you don't use any of their symbols.
  3034. - capt-of: for captions outside of floats
  3035. - hyperref: for cross references
  3036. Therefore you should not modify this variable unless you know
  3037. what you are doing. The one reason to change it anyway is that
  3038. you might be loading some other package that conflicts with one
  3039. of the default packages. Each element is either a cell or
  3040. a string.
  3041. A cell is of the format
  3042. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3043. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3044. when compiling LaTeX snippets into images for inclusion into
  3045. non-LaTeX output.
  3046. COMPILERS is a list of compilers that should include the package,
  3047. see `org-latex-compiler'. If the document compiler is not in the
  3048. list, and the list is non-nil, the package will not be inserted
  3049. in the final document.
  3050. A string will be inserted as-is in the header of the document."
  3051. :group 'org-latex
  3052. :group 'org-export-latex
  3053. :set 'org-set-packages-alist
  3054. :get 'org-get-packages-alist
  3055. :version "26.1"
  3056. :package-version '(Org . "8.3")
  3057. :type '(repeat
  3058. (choice
  3059. (list :tag "options/package pair"
  3060. (string :tag "options")
  3061. (string :tag "package")
  3062. (boolean :tag "Snippet")
  3063. (choice
  3064. (const :tag "For all compilers" nil)
  3065. (repeat :tag "Allowed compiler" string)))
  3066. (string :tag "A line of LaTeX"))))
  3067. (defcustom org-latex-packages-alist nil
  3068. "Alist of packages to be inserted in every LaTeX header.
  3069. These will be inserted after `org-latex-default-packages-alist'.
  3070. Each element is either a cell or a string.
  3071. A cell is of the format:
  3072. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3073. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3074. needed when turning LaTeX snippets into images for inclusion into
  3075. non-LaTeX output.
  3076. COMPILERS is a list of compilers that should include the package,
  3077. see `org-latex-compiler'. If the document compiler is not in the
  3078. list, and the list is non-nil, the package will not be inserted
  3079. in the final document.
  3080. A string will be inserted as-is in the header of the document.
  3081. Make sure that you only list packages here which:
  3082. - you want in every file;
  3083. - do not conflict with the setup in `org-format-latex-header';
  3084. - do not conflict with the default packages in
  3085. `org-latex-default-packages-alist'."
  3086. :group 'org-latex
  3087. :group 'org-export-latex
  3088. :set 'org-set-packages-alist
  3089. :get 'org-get-packages-alist
  3090. :type '(repeat
  3091. (choice
  3092. (list :tag "options/package pair"
  3093. (string :tag "options")
  3094. (string :tag "package")
  3095. (boolean :tag "Snippet"))
  3096. (string :tag "A line of LaTeX"))))
  3097. (defgroup org-appearance nil
  3098. "Settings for Org mode appearance."
  3099. :tag "Org Appearance"
  3100. :group 'org)
  3101. (defcustom org-level-color-stars-only nil
  3102. "Non-nil means fontify only the stars in each headline.
  3103. When nil, the entire headline is fontified.
  3104. Changing it requires restart of `font-lock-mode' to become effective
  3105. also in regions already fontified."
  3106. :group 'org-appearance
  3107. :type 'boolean)
  3108. (defcustom org-hide-leading-stars nil
  3109. "Non-nil means hide the first N-1 stars in a headline.
  3110. This works by using the face `org-hide' for these stars. This
  3111. face is white for a light background, and black for a dark
  3112. background. You may have to customize the face `org-hide' to
  3113. make this work.
  3114. Changing it requires restart of `font-lock-mode' to become effective
  3115. also in regions already fontified.
  3116. You may also set this on a per-file basis by adding one of the following
  3117. lines to the buffer:
  3118. #+STARTUP: hidestars
  3119. #+STARTUP: showstars"
  3120. :group 'org-appearance
  3121. :type 'boolean)
  3122. (defcustom org-hidden-keywords nil
  3123. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3124. For example, a value \\='(title) for this list makes the document's title
  3125. appear in the buffer without the initial \"#+TITLE:\" part."
  3126. :group 'org-appearance
  3127. :version "24.1"
  3128. :type '(set (const :tag "#+AUTHOR" author)
  3129. (const :tag "#+DATE" date)
  3130. (const :tag "#+EMAIL" email)
  3131. (const :tag "#+TITLE" title)))
  3132. (defcustom org-custom-properties nil
  3133. "List of properties (as strings) with a special meaning.
  3134. The default use of these custom properties is to let the user
  3135. hide them with `org-toggle-custom-properties-visibility'."
  3136. :group 'org-properties
  3137. :group 'org-appearance
  3138. :version "24.3"
  3139. :type '(repeat (string :tag "Property Name")))
  3140. (defcustom org-fontify-done-headline nil
  3141. "Non-nil means change the face of a headline if it is marked DONE.
  3142. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3143. When this is non-nil, the headline after the keyword is set to the
  3144. `org-headline-done' as an additional indication."
  3145. :group 'org-appearance
  3146. :type 'boolean)
  3147. (defcustom org-fontify-emphasized-text t
  3148. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3149. Changing this variable requires a restart of Emacs to take effect."
  3150. :group 'org-appearance
  3151. :type 'boolean)
  3152. (defcustom org-fontify-whole-heading-line nil
  3153. "Non-nil means fontify the whole line for headings.
  3154. This is useful when setting a background color for the
  3155. org-level-* faces."
  3156. :group 'org-appearance
  3157. :type 'boolean)
  3158. (defcustom org-fontify-whole-block-delimiter-line t
  3159. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3160. This is useful when setting a background color for the
  3161. org-block-begin-line and org-block-end-line faces."
  3162. :group 'org-appearance
  3163. :type 'boolean)
  3164. (defcustom org-highlight-latex-and-related nil
  3165. "Non-nil means highlight LaTeX related syntax in the buffer.
  3166. When non-nil, the value should be a list containing any of the
  3167. following symbols:
  3168. `native' Highlight LaTeX snippets and environments natively.
  3169. `latex' Highlight LaTeX snippets and environments.
  3170. `script' Highlight subscript and superscript.
  3171. `entities' Highlight entities."
  3172. :group 'org-appearance
  3173. :version "24.4"
  3174. :package-version '(Org . "8.0")
  3175. :type '(choice
  3176. (const :tag "No highlighting" nil)
  3177. (set :greedy t :tag "Highlight"
  3178. (const :tag "LaTeX snippets and environments (native)" native)
  3179. (const :tag "LaTeX snippets and environments" latex)
  3180. (const :tag "Subscript and superscript" script)
  3181. (const :tag "Entities" entities))))
  3182. (defcustom org-hide-emphasis-markers nil
  3183. "Non-nil mean font-lock should hide the emphasis marker characters."
  3184. :group 'org-appearance
  3185. :type 'boolean
  3186. :safe #'booleanp)
  3187. (defcustom org-hide-macro-markers nil
  3188. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3189. :group 'org-appearance
  3190. :type 'boolean)
  3191. (defcustom org-pretty-entities nil
  3192. "Non-nil means show entities as UTF8 characters.
  3193. When nil, the \\name form remains in the buffer."
  3194. :group 'org-appearance
  3195. :version "24.1"
  3196. :type 'boolean)
  3197. (defcustom org-pretty-entities-include-sub-superscripts t
  3198. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3199. :group 'org-appearance
  3200. :version "24.1"
  3201. :type 'boolean)
  3202. (defvar org-emph-re nil
  3203. "Regular expression for matching emphasis.
  3204. After a match, the match groups contain these elements:
  3205. 0 The match of the full regular expression, including the characters
  3206. before and after the proper match
  3207. 1 The character before the proper match, or empty at beginning of line
  3208. 2 The proper match, including the leading and trailing markers
  3209. 3 The leading marker like * or /, indicating the type of highlighting
  3210. 4 The text between the emphasis markers, not including the markers
  3211. 5 The character after the match, empty at the end of a line")
  3212. (defvar org-verbatim-re nil
  3213. "Regular expression for matching verbatim text.")
  3214. (defvar org-emphasis-regexp-components) ; defined just below
  3215. (defvar org-emphasis-alist) ; defined just below
  3216. (defun org-set-emph-re (var val)
  3217. "Set variable and compute the emphasis regular expression."
  3218. (set var val)
  3219. (when (and (boundp 'org-emphasis-alist)
  3220. (boundp 'org-emphasis-regexp-components)
  3221. org-emphasis-alist org-emphasis-regexp-components)
  3222. (pcase-let*
  3223. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3224. (body (if (<= nl 0) body
  3225. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3226. (template
  3227. (format (concat "\\([%s]\\|^\\)" ;before markers
  3228. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3229. "\\([%s]\\|$\\)") ;after markers
  3230. pre border border body border post)))
  3231. (setq org-emph-re (format template "*/_+"))
  3232. (setq org-verbatim-re (format template "=~")))))
  3233. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3234. ;; set this option proved cumbersome. See this message/thread:
  3235. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3236. (defvar org-emphasis-regexp-components
  3237. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3238. "Components used to build the regular expression for emphasis.
  3239. This is a list with five entries. Terminology: In an emphasis string
  3240. like \" *strong word* \", we call the initial space PREMATCH, the final
  3241. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3242. and \"trong wor\" is the body. The different components in this variable
  3243. specify what is allowed/forbidden in each part:
  3244. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3245. post Chars allowed as postmatch. End of line will be allowed too.
  3246. border The chars *forbidden* as border characters.
  3247. body-regexp A regexp like \".\" to match a body character. Don't use
  3248. non-shy groups here, and don't allow newline here.
  3249. newline The maximum number of newlines allowed in an emphasis exp.
  3250. You need to reload Org or to restart Emacs after setting this.")
  3251. (defcustom org-emphasis-alist
  3252. '(("*" bold)
  3253. ("/" italic)
  3254. ("_" underline)
  3255. ("=" org-verbatim verbatim)
  3256. ("~" org-code verbatim)
  3257. ("+" (:strike-through t)))
  3258. "Alist of characters and faces to emphasize text.
  3259. Text starting and ending with a special character will be emphasized,
  3260. for example *bold*, _underlined_ and /italic/. This variable sets the
  3261. marker characters and the face to be used by font-lock for highlighting
  3262. in Org buffers.
  3263. You need to reload Org or to restart Emacs after customizing this."
  3264. :group 'org-appearance
  3265. :set 'org-set-emph-re
  3266. :version "24.4"
  3267. :package-version '(Org . "8.0")
  3268. :type '(repeat
  3269. (list
  3270. (string :tag "Marker character")
  3271. (choice
  3272. (face :tag "Font-lock-face")
  3273. (plist :tag "Face property list"))
  3274. (option (const verbatim)))))
  3275. (defvar org-protecting-blocks '("src" "example" "export")
  3276. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3277. This is needed for font-lock setup.")
  3278. ;;; Functions and variables from their packages
  3279. ;; Declared here to avoid compiler warnings
  3280. (defvar mark-active)
  3281. ;; Various packages
  3282. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3283. (declare-function calendar-forward-day "cal-move" (arg))
  3284. (declare-function calendar-goto-date "cal-move" (date))
  3285. (declare-function calendar-goto-today "cal-move" ())
  3286. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3287. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3288. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3289. (declare-function cdlatex-tab "ext:cdlatex" ())
  3290. (declare-function dired-get-filename
  3291. "dired"
  3292. (&optional localp no-error-if-not-filep))
  3293. (declare-function iswitchb-read-buffer
  3294. "iswitchb"
  3295. (prompt &optional
  3296. default require-match _predicate start matches-set))
  3297. (declare-function org-agenda-change-all-lines
  3298. "org-agenda"
  3299. (newhead hdmarker &optional fixface just-this))
  3300. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3301. "org-agenda"
  3302. (&optional end))
  3303. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3304. (declare-function org-agenda-format-item
  3305. "org-agenda"
  3306. (extra txt &optional level category tags dotime
  3307. remove-re habitp))
  3308. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3309. (declare-function org-agenda-save-markers-for-cut-and-paste
  3310. "org-agenda"
  3311. (beg end))
  3312. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3313. (declare-function org-agenda-skip "org-agenda" ())
  3314. (declare-function org-attach-expand "org-attach" (file))
  3315. (declare-function org-attach-reveal "org-attach" ())
  3316. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3317. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3318. (declare-function org-indent-mode "org-indent" (&optional arg))
  3319. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3320. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3321. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3322. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3323. (declare-function parse-time-string "parse-time" (string))
  3324. (defvar align-mode-rules-list)
  3325. (defvar calc-embedded-close-formula)
  3326. (defvar calc-embedded-open-formula)
  3327. (defvar calc-embedded-open-mode)
  3328. (defvar font-lock-unfontify-region-function)
  3329. (defvar iswitchb-temp-buflist)
  3330. (defvar org-agenda-tags-todo-honor-ignore-options)
  3331. (defvar remember-data-file)
  3332. (defvar texmathp-why)
  3333. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3334. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3335. (declare-function org-resolve-clocks "org-clock"
  3336. (&optional also-non-dangling-p prompt last-valid))
  3337. (defvar org-clock-start-time)
  3338. (defvar org-clock-marker (make-marker)
  3339. "Marker recording the last clock-in.")
  3340. (defvar org-clock-hd-marker (make-marker)
  3341. "Marker recording the last clock-in, but the headline position.")
  3342. (defvar org-clock-heading ""
  3343. "The heading of the current clock entry.")
  3344. (defun org-clock-is-active ()
  3345. "Return the buffer where the clock is currently running.
  3346. Return nil if no clock is running."
  3347. (marker-buffer org-clock-marker))
  3348. (defun org-check-running-clock ()
  3349. "Check if the current buffer contains the running clock.
  3350. If yes, offer to stop it and to save the buffer with the changes."
  3351. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3352. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3353. (buffer-name))))
  3354. (org-clock-out)
  3355. (when (y-or-n-p "Save changed buffer?")
  3356. (save-buffer))))
  3357. (defun org-clocktable-try-shift (dir n)
  3358. "Check if this line starts a clock table, if yes, shift the time block."
  3359. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3360. (org-clocktable-shift dir n)))
  3361. ;;;###autoload
  3362. (defun org-clock-persistence-insinuate ()
  3363. "Set up hooks for clock persistence."
  3364. (require 'org-clock)
  3365. (add-hook 'org-mode-hook 'org-clock-load)
  3366. (add-hook 'kill-emacs-hook 'org-clock-save))
  3367. (defgroup org-archive nil
  3368. "Options concerning archiving in Org mode."
  3369. :tag "Org Archive"
  3370. :group 'org-structure)
  3371. (defcustom org-archive-location "%s_archive::"
  3372. "The location where subtrees should be archived.
  3373. The value of this variable is a string, consisting of two parts,
  3374. separated by a double-colon. The first part is a filename and
  3375. the second part is a headline.
  3376. When the filename is omitted, archiving happens in the same file.
  3377. %s in the filename will be replaced by the current file
  3378. name (without the directory part). Archiving to a different file
  3379. is useful to keep archived entries from contributing to the
  3380. Org Agenda.
  3381. The archived entries will be filed as subtrees of the specified
  3382. headline. When the headline is omitted, the subtrees are simply
  3383. filed away at the end of the file, as top-level entries. Also in
  3384. the heading you can use %s to represent the file name, this can be
  3385. useful when using the same archive for a number of different files.
  3386. Here are a few examples:
  3387. \"%s_archive::\"
  3388. If the current file is Projects.org, archive in file
  3389. Projects.org_archive, as top-level trees. This is the default.
  3390. \"::* Archived Tasks\"
  3391. Archive in the current file, under the top-level headline
  3392. \"* Archived Tasks\".
  3393. \"~/org/archive.org::\"
  3394. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3395. \"~/org/archive.org::* From %s\"
  3396. Archive in file ~/org/archive.org (absolute path), under headlines
  3397. \"From FILENAME\" where file name is the current file name.
  3398. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3399. The \"datetree/\" string is special, signifying to archive
  3400. items to the datetree. Items are placed in either the CLOSED
  3401. date of the item, or the current date if there is no CLOSED date.
  3402. The heading will be a subentry to the current date. There doesn't
  3403. need to be a heading, but there always needs to be a slash after
  3404. datetree. For example, to store archived items directly in the
  3405. datetree, use \"~/org/datetree.org::datetree/\".
  3406. \"basement::** Finished Tasks\"
  3407. Archive in file ./basement (relative path), as level 3 trees
  3408. below the level 2 heading \"** Finished Tasks\".
  3409. You may set this option on a per-file basis by adding to the buffer a
  3410. line like
  3411. #+ARCHIVE: basement::** Finished Tasks
  3412. You may also define it locally for a subtree by setting an ARCHIVE property
  3413. in the entry. If such a property is found in an entry, or anywhere up
  3414. the hierarchy, it will be used."
  3415. :group 'org-archive
  3416. :type 'string)
  3417. (defcustom org-agenda-skip-archived-trees t
  3418. "Non-nil means the agenda will skip any items located in archived trees.
  3419. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3420. variable is no longer recommended, you should leave it at the value t.
  3421. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3422. :group 'org-archive
  3423. :group 'org-agenda-skip
  3424. :type 'boolean)
  3425. (defcustom org-columns-skip-archived-trees t
  3426. "Non-nil means ignore archived trees when creating column view."
  3427. :group 'org-archive
  3428. :group 'org-properties
  3429. :type 'boolean)
  3430. (defcustom org-cycle-open-archived-trees nil
  3431. "Non-nil means `org-cycle' will open archived trees.
  3432. An archived tree is a tree marked with the tag ARCHIVE.
  3433. When nil, archived trees will stay folded. You can still open them with
  3434. normal outline commands like `show-all', but not with the cycling commands."
  3435. :group 'org-archive
  3436. :group 'org-cycle
  3437. :type 'boolean)
  3438. (defcustom org-sparse-tree-open-archived-trees nil
  3439. "Non-nil means sparse tree construction shows matches in archived trees.
  3440. When nil, matches in these trees are highlighted, but the trees are kept in
  3441. collapsed state."
  3442. :group 'org-archive
  3443. :group 'org-sparse-trees
  3444. :type 'boolean)
  3445. (defcustom org-sparse-tree-default-date-type nil
  3446. "The default date type when building a sparse tree.
  3447. When this is nil, a date is a scheduled or a deadline timestamp.
  3448. Otherwise, these types are allowed:
  3449. all: all timestamps
  3450. active: only active timestamps (<...>)
  3451. inactive: only inactive timestamps ([...])
  3452. scheduled: only scheduled timestamps
  3453. deadline: only deadline timestamps"
  3454. :type '(choice (const :tag "Scheduled or deadline" nil)
  3455. (const :tag "All timestamps" all)
  3456. (const :tag "Only active timestamps" active)
  3457. (const :tag "Only inactive timestamps" inactive)
  3458. (const :tag "Only scheduled timestamps" scheduled)
  3459. (const :tag "Only deadline timestamps" deadline)
  3460. (const :tag "Only closed timestamps" closed))
  3461. :version "26.1"
  3462. :package-version '(Org . "8.3")
  3463. :group 'org-sparse-trees)
  3464. (defun org-cycle-hide-archived-subtrees (state)
  3465. "Re-hide all archived subtrees after a visibility state change.
  3466. STATE should be one of the symbols listed in the docstring of
  3467. `org-cycle-hook'."
  3468. (when (and (not org-cycle-open-archived-trees)
  3469. (not (memq state '(overview folded))))
  3470. (save-excursion
  3471. (let* ((globalp (memq state '(contents all)))
  3472. (beg (if globalp (point-min) (point)))
  3473. (end (if globalp (point-max) (org-end-of-subtree t))))
  3474. (org-hide-archived-subtrees beg end)
  3475. (goto-char beg)
  3476. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3477. (message "%s" (substitute-command-keys
  3478. "Subtree is archived and stays closed. Use \
  3479. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3480. (defun org-force-cycle-archived ()
  3481. "Cycle subtree even if it is archived."
  3482. (interactive)
  3483. (setq this-command 'org-cycle)
  3484. (let ((org-cycle-open-archived-trees t))
  3485. (call-interactively 'org-cycle)))
  3486. (defun org-hide-archived-subtrees (beg end)
  3487. "Re-hide all archived subtrees after a visibility state change."
  3488. (org-with-wide-buffer
  3489. (let ((case-fold-search nil)
  3490. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3491. (goto-char beg)
  3492. ;; Include headline point is currently on.
  3493. (beginning-of-line)
  3494. (while (and (< (point) end) (re-search-forward re end t))
  3495. (when (member org-archive-tag (org-get-tags nil t))
  3496. (org-flag-subtree t)
  3497. (org-end-of-subtree t))))))
  3498. (defun org-flag-subtree (flag)
  3499. (save-excursion
  3500. (org-back-to-heading t)
  3501. (org-flag-region (line-end-position)
  3502. (progn (org-end-of-subtree t) (point))
  3503. flag
  3504. 'outline)))
  3505. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3506. ;; Declare Column View Code
  3507. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3508. (declare-function org-columns-compute "org-colview" (property))
  3509. ;; Declare ID code
  3510. (declare-function org-id-store-link "org-id")
  3511. (declare-function org-id-locations-load "org-id")
  3512. (declare-function org-id-locations-save "org-id")
  3513. (defvar org-id-track-globally)
  3514. ;;; Variables for pre-computed regular expressions, all buffer local
  3515. (defvar-local org-todo-regexp nil
  3516. "Matches any of the TODO state keywords.
  3517. Since TODO keywords are case-sensitive, `case-fold-search' is
  3518. expected to be bound to nil when matching against this regexp.")
  3519. (defvar-local org-not-done-regexp nil
  3520. "Matches any of the TODO state keywords except the last one.
  3521. Since TODO keywords are case-sensitive, `case-fold-search' is
  3522. expected to be bound to nil when matching against this regexp.")
  3523. (defvar-local org-not-done-heading-regexp nil
  3524. "Matches a TODO headline that is not done.
  3525. Since TODO keywords are case-sensitive, `case-fold-search' is
  3526. expected to be bound to nil when matching against this regexp.")
  3527. (defvar-local org-todo-line-regexp nil
  3528. "Matches a headline and puts TODO state into group 2 if present.
  3529. Since TODO keywords are case-sensitive, `case-fold-search' is
  3530. expected to be bound to nil when matching against this regexp.")
  3531. (defvar-local org-complex-heading-regexp nil
  3532. "Matches a headline and puts everything into groups:
  3533. group 1: Stars
  3534. group 2: The TODO keyword, maybe
  3535. group 3: Priority cookie
  3536. group 4: True headline
  3537. group 5: Tags
  3538. Since TODO keywords are case-sensitive, `case-fold-search' is
  3539. expected to be bound to nil when matching against this regexp.")
  3540. (defvar-local org-complex-heading-regexp-format nil
  3541. "Printf format to make regexp to match an exact headline.
  3542. This regexp will match the headline of any node which has the
  3543. exact headline text that is put into the format, but may have any
  3544. TODO state, priority and tags.")
  3545. (defvar-local org-todo-line-tags-regexp nil
  3546. "Matches a headline and puts TODO state into group 2 if present.
  3547. Also put tags into group 4 if tags are present.")
  3548. (defconst org-plain-time-of-day-regexp
  3549. (concat
  3550. "\\(\\<[012]?[0-9]"
  3551. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3552. "\\(--?"
  3553. "\\(\\<[012]?[0-9]"
  3554. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3555. "\\)?")
  3556. "Regular expression to match a plain time or time range.
  3557. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3558. groups carry important information:
  3559. 0 the full match
  3560. 1 the first time, range or not
  3561. 8 the second time, if it is a range.")
  3562. (defconst org-plain-time-extension-regexp
  3563. (concat
  3564. "\\(\\<[012]?[0-9]"
  3565. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3566. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3567. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3568. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3569. groups carry important information:
  3570. 0 the full match
  3571. 7 hours of duration
  3572. 9 minutes of duration")
  3573. (defconst org-stamp-time-of-day-regexp
  3574. (concat
  3575. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3576. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  3577. "\\(--?"
  3578. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3579. "Regular expression to match a timestamp time or time range.
  3580. After a match, the following groups carry important information:
  3581. 0 the full match
  3582. 1 date plus weekday, for back referencing to make sure both times are on the same day
  3583. 2 the first time, range or not
  3584. 4 the second time, if it is a range.")
  3585. (defconst org-startup-options
  3586. '(("fold" org-startup-folded t)
  3587. ("overview" org-startup-folded t)
  3588. ("nofold" org-startup-folded nil)
  3589. ("showall" org-startup-folded nil)
  3590. ("showeverything" org-startup-folded showeverything)
  3591. ("content" org-startup-folded content)
  3592. ("indent" org-startup-indented t)
  3593. ("noindent" org-startup-indented nil)
  3594. ("hidestars" org-hide-leading-stars t)
  3595. ("showstars" org-hide-leading-stars nil)
  3596. ("odd" org-odd-levels-only t)
  3597. ("oddeven" org-odd-levels-only nil)
  3598. ("align" org-startup-align-all-tables t)
  3599. ("noalign" org-startup-align-all-tables nil)
  3600. ("shrink" org-startup-shrink-all-tables t)
  3601. ("inlineimages" org-startup-with-inline-images t)
  3602. ("noinlineimages" org-startup-with-inline-images nil)
  3603. ("latexpreview" org-startup-with-latex-preview t)
  3604. ("nolatexpreview" org-startup-with-latex-preview nil)
  3605. ("customtime" org-display-custom-times t)
  3606. ("logdone" org-log-done time)
  3607. ("lognotedone" org-log-done note)
  3608. ("nologdone" org-log-done nil)
  3609. ("lognoteclock-out" org-log-note-clock-out t)
  3610. ("nolognoteclock-out" org-log-note-clock-out nil)
  3611. ("logrepeat" org-log-repeat state)
  3612. ("lognoterepeat" org-log-repeat note)
  3613. ("logdrawer" org-log-into-drawer t)
  3614. ("nologdrawer" org-log-into-drawer nil)
  3615. ("logstatesreversed" org-log-states-order-reversed t)
  3616. ("nologstatesreversed" org-log-states-order-reversed nil)
  3617. ("nologrepeat" org-log-repeat nil)
  3618. ("logreschedule" org-log-reschedule time)
  3619. ("lognotereschedule" org-log-reschedule note)
  3620. ("nologreschedule" org-log-reschedule nil)
  3621. ("logredeadline" org-log-redeadline time)
  3622. ("lognoteredeadline" org-log-redeadline note)
  3623. ("nologredeadline" org-log-redeadline nil)
  3624. ("logrefile" org-log-refile time)
  3625. ("lognoterefile" org-log-refile note)
  3626. ("nologrefile" org-log-refile nil)
  3627. ("fninline" org-footnote-define-inline t)
  3628. ("nofninline" org-footnote-define-inline nil)
  3629. ("fnlocal" org-footnote-section nil)
  3630. ("fnauto" org-footnote-auto-label t)
  3631. ("fnprompt" org-footnote-auto-label nil)
  3632. ("fnconfirm" org-footnote-auto-label confirm)
  3633. ("fnplain" org-footnote-auto-label plain)
  3634. ("fnadjust" org-footnote-auto-adjust t)
  3635. ("nofnadjust" org-footnote-auto-adjust nil)
  3636. ("constcgs" constants-unit-system cgs)
  3637. ("constSI" constants-unit-system SI)
  3638. ("noptag" org-tag-persistent-alist nil)
  3639. ("hideblocks" org-hide-block-startup t)
  3640. ("nohideblocks" org-hide-block-startup nil)
  3641. ("beamer" org-startup-with-beamer-mode t)
  3642. ("entitiespretty" org-pretty-entities t)
  3643. ("entitiesplain" org-pretty-entities nil))
  3644. "Variable associated with STARTUP options for Org.
  3645. Each element is a list of three items: the startup options (as written
  3646. in the #+STARTUP line), the corresponding variable, and the value to set
  3647. this variable to if the option is found. An optional forth element PUSH
  3648. means to push this value onto the list in the variable.")
  3649. (defcustom org-group-tags t
  3650. "When non-nil (the default), use group tags.
  3651. This can be turned on/off through `org-toggle-tags-groups'."
  3652. :group 'org-tags
  3653. :group 'org-startup
  3654. :type 'boolean)
  3655. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3656. (defun org-toggle-tags-groups ()
  3657. "Toggle support for group tags.
  3658. Support for group tags is controlled by the option
  3659. `org-group-tags', which is non-nil by default."
  3660. (interactive)
  3661. (setq org-group-tags (not org-group-tags))
  3662. (cond ((and (derived-mode-p 'org-agenda-mode)
  3663. org-group-tags)
  3664. (org-agenda-redo))
  3665. ((derived-mode-p 'org-mode)
  3666. (let ((org-inhibit-startup t)) (org-mode))))
  3667. (message "Groups tags support has been turned %s"
  3668. (if org-group-tags "on" "off")))
  3669. (defun org--tag-add-to-alist (alist1 alist2)
  3670. "Merge tags from ALIST1 into ALIST2.
  3671. Duplicates tags outside a group are removed. Keywords and order
  3672. are preserved.
  3673. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3674. See `org-tag-alist' for their structure."
  3675. (cond
  3676. ((null alist2) alist1)
  3677. ((null alist1) alist2)
  3678. (t
  3679. (let ((to-add nil)
  3680. (group-flag nil))
  3681. (dolist (tag-pair alist1)
  3682. (pcase tag-pair
  3683. (`(,(or :startgrouptag :startgroup))
  3684. (setq group-flag t)
  3685. (push tag-pair to-add))
  3686. (`(,(or :endgrouptag :endgroup))
  3687. (setq group-flag nil)
  3688. (push tag-pair to-add))
  3689. (`(,(or :grouptags :newline))
  3690. (push tag-pair to-add))
  3691. (`(,tag . ,_)
  3692. ;; Remove duplicates from ALIST1, unless they are in
  3693. ;; a group. Indeed, it makes sense to have a tag appear in
  3694. ;; multiple groups.
  3695. (when (or group-flag (not (assoc tag alist2)))
  3696. (push tag-pair to-add)))
  3697. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3698. ;; Preserve order of ALIST1.
  3699. (append (nreverse to-add) alist2)))))
  3700. (defun org-set-regexps-and-options (&optional tags-only)
  3701. "Precompute regular expressions used in the current buffer.
  3702. When optional argument TAGS-ONLY is non-nil, only compute tags
  3703. related expressions."
  3704. (when (derived-mode-p 'org-mode)
  3705. (let ((alist (org--setup-collect-keywords
  3706. (org-make-options-regexp
  3707. (append '("FILETAGS" "TAGS" "SETUPFILE")
  3708. (and (not tags-only)
  3709. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3710. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3711. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  3712. ;; Startup options. Get this early since it does change
  3713. ;; behavior for other options (e.g., tags).
  3714. (let ((startup (cdr (assq 'startup alist))))
  3715. (dolist (option startup)
  3716. (let ((entry (assoc-string option org-startup-options t)))
  3717. (when entry
  3718. (let ((var (nth 1 entry))
  3719. (val (nth 2 entry)))
  3720. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  3721. (unless (listp (symbol-value var))
  3722. (set (make-local-variable var) nil))
  3723. (add-to-list var val)))))))
  3724. (setq-local org-file-tags
  3725. (mapcar #'org-add-prop-inherited
  3726. (cdr (assq 'filetags alist))))
  3727. (setq org-current-tag-alist
  3728. (org--tag-add-to-alist
  3729. org-tag-persistent-alist
  3730. (let ((tags (cdr (assq 'tags alist))))
  3731. (if tags (org-tag-string-to-alist tags)
  3732. org-tag-alist))))
  3733. (setq org-tag-groups-alist
  3734. (org-tag-alist-to-groups org-current-tag-alist))
  3735. (unless tags-only
  3736. ;; File properties.
  3737. (setq-local org-file-properties (cdr (assq 'property alist)))
  3738. ;; Archive location.
  3739. (let ((archive (cdr (assq 'archive alist))))
  3740. (when archive (setq-local org-archive-location archive)))
  3741. ;; Category.
  3742. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  3743. (when cat
  3744. (setq-local org-category (intern cat))
  3745. (setq-local org-file-properties
  3746. (org--update-property-plist
  3747. "CATEGORY" cat org-file-properties))))
  3748. ;; Columns.
  3749. (let ((column (cdr (assq 'columns alist))))
  3750. (when column (setq-local org-columns-default-format column)))
  3751. ;; Constants.
  3752. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  3753. ;; Link abbreviations.
  3754. (let ((links (cdr (assq 'link alist))))
  3755. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3756. ;; Priorities.
  3757. (let ((priorities (cdr (assq 'priorities alist))))
  3758. (when priorities
  3759. (setq-local org-highest-priority (nth 0 priorities))
  3760. (setq-local org-lowest-priority (nth 1 priorities))
  3761. (setq-local org-default-priority (nth 2 priorities))))
  3762. ;; Scripts.
  3763. (let ((scripts (assq 'scripts alist)))
  3764. (when scripts
  3765. (setq-local org-use-sub-superscripts (cdr scripts))))
  3766. ;; TODO keywords.
  3767. (setq-local org-todo-kwd-alist nil)
  3768. (setq-local org-todo-key-alist nil)
  3769. (setq-local org-todo-key-trigger nil)
  3770. (setq-local org-todo-keywords-1 nil)
  3771. (setq-local org-done-keywords nil)
  3772. (setq-local org-todo-heads nil)
  3773. (setq-local org-todo-sets nil)
  3774. (setq-local org-todo-log-states nil)
  3775. (let ((todo-sequences
  3776. (or (nreverse (cdr (assq 'todo alist)))
  3777. (let ((d (default-value 'org-todo-keywords)))
  3778. (if (not (stringp (car d))) d
  3779. ;; XXX: Backward compatibility code.
  3780. (list (cons org-todo-interpretation d)))))))
  3781. (dolist (sequence todo-sequences)
  3782. (let* ((sequence (or (run-hook-with-args-until-success
  3783. 'org-todo-setup-filter-hook sequence)
  3784. sequence))
  3785. (sequence-type (car sequence))
  3786. (keywords (cdr sequence))
  3787. (sep (member "|" keywords))
  3788. names alist)
  3789. (dolist (k (remove "|" keywords))
  3790. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3791. k)
  3792. (error "Invalid TODO keyword %s" k))
  3793. (let ((name (match-string 1 k))
  3794. (key (match-string 2 k))
  3795. (log (org-extract-log-state-settings k)))
  3796. (push name names)
  3797. (push (cons name (and key (string-to-char key))) alist)
  3798. (when log (push log org-todo-log-states))))
  3799. (let* ((names (nreverse names))
  3800. (done (if sep (org-remove-keyword-keys (cdr sep))
  3801. (last names)))
  3802. (head (car names))
  3803. (tail (list sequence-type head (car done) (org-last done))))
  3804. (add-to-list 'org-todo-heads head 'append)
  3805. (push names org-todo-sets)
  3806. (setq org-done-keywords (append org-done-keywords done nil))
  3807. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3808. (setq org-todo-key-alist
  3809. (append org-todo-key-alist
  3810. (and alist
  3811. (append '((:startgroup))
  3812. (nreverse alist)
  3813. '((:endgroup))))))
  3814. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3815. (setq org-todo-sets (nreverse org-todo-sets)
  3816. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3817. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3818. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3819. ;; Compute the regular expressions and other local variables.
  3820. ;; Using `org-outline-regexp-bol' would complicate them much,
  3821. ;; because of the fixed white space at the end of that string.
  3822. (unless org-done-keywords
  3823. (setq org-done-keywords
  3824. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3825. (setq org-not-done-keywords
  3826. (org-delete-all org-done-keywords
  3827. (copy-sequence org-todo-keywords-1))
  3828. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3829. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3830. org-not-done-heading-regexp
  3831. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3832. org-todo-line-regexp
  3833. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3834. org-complex-heading-regexp
  3835. (concat "^\\(\\*+\\)"
  3836. "\\(?: +" org-todo-regexp "\\)?"
  3837. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3838. "\\(?: +\\(.*?\\)\\)??"
  3839. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3840. "[ \t]*$")
  3841. org-complex-heading-regexp-format
  3842. (concat "^\\(\\*+\\)"
  3843. "\\(?: +" org-todo-regexp "\\)?"
  3844. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3845. "\\(?: +"
  3846. ;; Stats cookies can be stuck to body.
  3847. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3848. "\\(%s\\)"
  3849. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3850. "\\)"
  3851. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3852. "[ \t]*$")
  3853. org-todo-line-tags-regexp
  3854. (concat "^\\(\\*+\\)"
  3855. "\\(?: +" org-todo-regexp "\\)?"
  3856. "\\(?: +\\(.*?\\)\\)??"
  3857. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3858. "[ \t]*$"))
  3859. (org-compute-latex-and-related-regexp)))))
  3860. (defun org--setup-collect-keywords (regexp &optional files alist)
  3861. "Return setup keywords values as an alist.
  3862. REGEXP matches a subset of setup keywords. FILES is a list of
  3863. file names already visited. It is used to avoid circular setup
  3864. files. ALIST, when non-nil, is the alist computed so far.
  3865. Return value contains the following keys: `archive', `category',
  3866. `columns', `constants', `filetags', `link', `priorities',
  3867. `property', `scripts', `startup', `tags' and `todo'."
  3868. (org-with-wide-buffer
  3869. (goto-char (point-min))
  3870. (let ((case-fold-search t))
  3871. (while (re-search-forward regexp nil t)
  3872. (let ((element (org-element-at-point)))
  3873. (when (eq (org-element-type element) 'keyword)
  3874. (let ((key (org-element-property :key element))
  3875. (value (org-element-property :value element)))
  3876. (cond
  3877. ((equal key "ARCHIVE")
  3878. (when (org-string-nw-p value)
  3879. (push (cons 'archive value) alist)))
  3880. ((equal key "CATEGORY") (push (cons 'category value) alist))
  3881. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  3882. ((equal key "CONSTANTS")
  3883. (let* ((constants (assq 'constants alist))
  3884. (store (cdr constants)))
  3885. (dolist (pair (split-string value))
  3886. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  3887. pair)
  3888. (let* ((name (match-string 1 pair))
  3889. (value (match-string 2 pair))
  3890. (old (assoc name store)))
  3891. (if old (setcdr old value)
  3892. (push (cons name value) store)))))
  3893. (if constants (setcdr constants store)
  3894. (push (cons 'constants store) alist))))
  3895. ((equal key "FILETAGS")
  3896. (when (org-string-nw-p value)
  3897. (let ((old (assq 'filetags alist))
  3898. (new (apply #'nconc
  3899. (mapcar (lambda (x) (org-split-string x ":"))
  3900. (split-string value)))))
  3901. (if old (setcdr old (append new (cdr old)))
  3902. (push (cons 'filetags new) alist)))))
  3903. ((equal key "LINK")
  3904. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3905. (let ((links (assq 'link alist))
  3906. (pair (cons (match-string-no-properties 1 value)
  3907. (match-string-no-properties 2 value))))
  3908. (if links (push pair (cdr links))
  3909. (push (list 'link pair) alist)))))
  3910. ((equal key "OPTIONS")
  3911. (when (and (org-string-nw-p value)
  3912. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  3913. (push (cons 'scripts (read (match-string 1 value))) alist)))
  3914. ((equal key "PRIORITIES")
  3915. (push (cons 'priorities
  3916. (let ((prio (split-string value)))
  3917. (if (< (length prio) 3) '(?A ?C ?B)
  3918. (mapcar #'string-to-char prio))))
  3919. alist))
  3920. ((equal key "PROPERTY")
  3921. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3922. (let* ((property (assq 'property alist))
  3923. (value (org--update-property-plist
  3924. (match-string-no-properties 1 value)
  3925. (match-string-no-properties 2 value)
  3926. (cdr property))))
  3927. (if property (setcdr property value)
  3928. (push (cons 'property value) alist)))))
  3929. ((equal key "STARTUP")
  3930. (let ((startup (assq 'startup alist)))
  3931. (if startup
  3932. (setcdr startup
  3933. (append (cdr startup) (split-string value)))
  3934. (push (cons 'startup (split-string value)) alist))))
  3935. ((equal key "TAGS")
  3936. (let ((tag-cell (assq 'tags alist)))
  3937. (if tag-cell
  3938. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  3939. (push (cons 'tags value) alist))))
  3940. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  3941. (let ((todo (assq 'todo alist))
  3942. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  3943. (split-string value))))
  3944. (if todo (push value (cdr todo))
  3945. (push (list 'todo value) alist))))
  3946. ((equal key "SETUPFILE")
  3947. (unless buffer-read-only ; Do not check in Gnus messages.
  3948. (let ((f (and (org-string-nw-p value)
  3949. (expand-file-name (org-strip-quotes value)))))
  3950. (when (and f (file-readable-p f) (not (member f files)))
  3951. (with-temp-buffer
  3952. (setq default-directory (file-name-directory f))
  3953. (insert-file-contents f)
  3954. (setq alist
  3955. ;; Fake Org mode to benefit from cache
  3956. ;; without recurring needlessly.
  3957. (let ((major-mode 'org-mode))
  3958. (org--setup-collect-keywords
  3959. regexp (cons f files) alist)))))))))))))))
  3960. alist)
  3961. (defun org-tag-string-to-alist (s)
  3962. "Return tag alist associated to string S.
  3963. S is a value for TAGS keyword or produced with
  3964. `org-tag-alist-to-string'. Return value is an alist suitable for
  3965. `org-tag-alist' or `org-tag-persistent-alist'."
  3966. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3967. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3968. "\\(?:(\\(.\\))\\)?\\'"))
  3969. alist group-flag)
  3970. (dolist (tokens lines (cdr (nreverse alist)))
  3971. (push '(:newline) alist)
  3972. (while tokens
  3973. (let ((token (pop tokens)))
  3974. (pcase token
  3975. ("{"
  3976. (push '(:startgroup) alist)
  3977. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3978. ("}"
  3979. (push '(:endgroup) alist)
  3980. (setq group-flag nil))
  3981. ("["
  3982. (push '(:startgrouptag) alist)
  3983. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3984. ("]"
  3985. (push '(:endgrouptag) alist)
  3986. (setq group-flag nil))
  3987. (":"
  3988. (push '(:grouptags) alist))
  3989. ((guard (string-match tag-re token))
  3990. (let ((tag (match-string 1 token))
  3991. (key (and (match-beginning 2)
  3992. (string-to-char (match-string 2 token)))))
  3993. ;; Push all tags in groups, no matter if they already
  3994. ;; appear somewhere else in the list.
  3995. (when (or group-flag (not (assoc tag alist)))
  3996. (push (cons tag key) alist))))))))))
  3997. (defun org-tag-alist-to-string (alist &optional skip-key)
  3998. "Return tag string associated to ALIST.
  3999. ALIST is an alist, as defined in `org-tag-alist' or
  4000. `org-tag-persistent-alist', or produced with
  4001. `org-tag-string-to-alist'.
  4002. Return value is a string suitable as a value for \"TAGS\"
  4003. keyword.
  4004. When optional argument SKIP-KEY is non-nil, skip selection keys
  4005. next to tags."
  4006. (mapconcat (lambda (token)
  4007. (pcase token
  4008. (`(:startgroup) "{")
  4009. (`(:endgroup) "}")
  4010. (`(:startgrouptag) "[")
  4011. (`(:endgrouptag) "]")
  4012. (`(:grouptags) ":")
  4013. (`(:newline) "\\n")
  4014. ((and
  4015. (guard (not skip-key))
  4016. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4017. (format "%s(%c)" tag key))
  4018. (`(,(and tag (pred stringp)) . ,_) tag)
  4019. (_ (user-error "Invalid tag token: %S" token))))
  4020. alist
  4021. " "))
  4022. (defun org-tag-alist-to-groups (alist)
  4023. "Return group alist from tag ALIST.
  4024. ALIST is an alist, as defined in `org-tag-alist' or
  4025. `org-tag-persistent-alist', or produced with
  4026. `org-tag-string-to-alist'. Return value is an alist following
  4027. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4028. a string, summarizing TAGS, as a list of strings."
  4029. (let (groups group-status current-group)
  4030. (dolist (token alist (nreverse groups))
  4031. (pcase token
  4032. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4033. (`(,(or :endgroup :endgrouptag))
  4034. (when (eq group-status 'append)
  4035. (push (nreverse current-group) groups))
  4036. (setq group-status nil current-group nil))
  4037. (`(:grouptags) (setq group-status 'append))
  4038. ((and `(,tag . ,_) (guard group-status))
  4039. (if (eq group-status 'append) (push tag current-group)
  4040. (setq current-group (list tag))))
  4041. (_ nil)))))
  4042. (defvar org--file-cache (make-hash-table :test #'equal)
  4043. "Hash table to store contents of files referenced via a URL.
  4044. This is the cache of file URLs read using `org-file-contents'.")
  4045. (defun org-reset-file-cache ()
  4046. "Reset the cache of files downloaded by `org-file-contents'."
  4047. (clrhash org--file-cache))
  4048. (defun org-file-url-p (file)
  4049. "Non-nil if FILE is a URL."
  4050. (require 'ffap)
  4051. (string-match-p ffap-url-regexp file))
  4052. (defun org-file-contents (file &optional noerror nocache)
  4053. "Return the contents of FILE, as a string.
  4054. FILE can be a file name or URL.
  4055. If FILE is a URL, download the contents. If the URL contents are
  4056. already cached in the `org--file-cache' hash table, the download step
  4057. is skipped.
  4058. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4059. from file or URL.
  4060. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4061. is available. This option applies only if FILE is a URL."
  4062. (let* ((is-url (org-file-url-p file))
  4063. (cache (and is-url
  4064. (not nocache)
  4065. (gethash file org--file-cache))))
  4066. (cond
  4067. (cache)
  4068. (is-url
  4069. (with-current-buffer (url-retrieve-synchronously file)
  4070. (goto-char (point-min))
  4071. ;; Move point to after the url-retrieve header.
  4072. (search-forward "\n\n" nil :move)
  4073. ;; Search for the success code only in the url-retrieve header.
  4074. (if (save-excursion
  4075. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4076. ;; Update the cache `org--file-cache' and return contents.
  4077. (puthash file
  4078. (buffer-substring-no-properties (point) (point-max))
  4079. org--file-cache)
  4080. (funcall (if noerror #'message #'user-error)
  4081. "Unable to fetch file from %S"
  4082. file))))
  4083. (t
  4084. (with-temp-buffer
  4085. (condition-case nil
  4086. (progn
  4087. (insert-file-contents file)
  4088. (buffer-string))
  4089. (file-error
  4090. (funcall (if noerror #'message #'user-error)
  4091. "Unable to read file %S"
  4092. file))))))))
  4093. (defun org-extract-log-state-settings (x)
  4094. "Extract the log state setting from a TODO keyword string.
  4095. This will extract info from a string like \"WAIT(w@/!)\"."
  4096. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4097. (let ((kw (match-string 1 x))
  4098. (log1 (and (match-end 3) (match-string 3 x)))
  4099. (log2 (and (match-end 4) (match-string 4 x))))
  4100. (and (or log1 log2)
  4101. (list kw
  4102. (and log1 (if (equal log1 "!") 'time 'note))
  4103. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4104. (defun org-remove-keyword-keys (list)
  4105. "Remove a pair of parenthesis at the end of each string in LIST."
  4106. (mapcar (lambda (x)
  4107. (if (string-match "(.*)$" x)
  4108. (substring x 0 (match-beginning 0))
  4109. x))
  4110. list))
  4111. (defun org-assign-fast-keys (alist)
  4112. "Assign fast keys to a keyword-key alist.
  4113. Respect keys that are already there."
  4114. (let (new e (alt ?0))
  4115. (while (setq e (pop alist))
  4116. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4117. (cdr e)) ;; Key already assigned.
  4118. (push e new)
  4119. (let ((clist (string-to-list (downcase (car e))))
  4120. (used (append new alist)))
  4121. (when (= (car clist) ?@)
  4122. (pop clist))
  4123. (while (and clist (rassoc (car clist) used))
  4124. (pop clist))
  4125. (unless clist
  4126. (while (rassoc alt used)
  4127. (cl-incf alt)))
  4128. (push (cons (car e) (or (car clist) alt)) new))))
  4129. (nreverse new)))
  4130. ;;; Some variables used in various places
  4131. (defvar org-window-configuration nil
  4132. "Used in various places to store a window configuration.")
  4133. (defvar org-selected-window nil
  4134. "Used in various places to store a window configuration.")
  4135. (defvar org-finish-function nil
  4136. "Function to be called when `C-c C-c' is used.
  4137. This is for getting out of special buffers like capture.")
  4138. (defvar org-last-state)
  4139. ;; Defined somewhere in this file, but used before definition.
  4140. (defvar org-entities) ;; defined in org-entities.el
  4141. (defvar org-struct-menu)
  4142. (defvar org-org-menu)
  4143. (defvar org-tbl-menu)
  4144. ;;;; Define the Org mode
  4145. (defun org-before-change-function (_beg _end)
  4146. "Every change indicates that a table might need an update."
  4147. (setq org-table-may-need-update t))
  4148. (defvar org-mode-map)
  4149. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4150. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4151. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4152. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4153. (defvar bidi-paragraph-direction)
  4154. (defvar buffer-face-mode-face)
  4155. (require 'outline)
  4156. ;; Other stuff we need.
  4157. (require 'time-date)
  4158. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4159. (require 'easymenu)
  4160. (autoload 'easy-menu-add "easymenu")
  4161. (require 'overlay)
  4162. ;; (require 'org-macs) moved higher up in the file before it is first used
  4163. (require 'org-entities)
  4164. ;; (require 'org-compat) moved higher up in the file before it is first used
  4165. (require 'org-faces)
  4166. (require 'org-list)
  4167. (require 'org-pcomplete)
  4168. (require 'org-src)
  4169. (require 'org-footnote)
  4170. (require 'org-macro)
  4171. ;; babel
  4172. (require 'ob)
  4173. ;;;###autoload
  4174. (define-derived-mode org-mode outline-mode "Org"
  4175. "Outline-based notes management and organizer, alias
  4176. \"Carsten's outline-mode for keeping track of everything.\"
  4177. Org mode develops organizational tasks around a NOTES file which
  4178. contains information about projects as plain text. Org mode is
  4179. implemented on top of Outline mode, which is ideal to keep the content
  4180. of large files well structured. It supports ToDo items, deadlines and
  4181. time stamps, which magically appear in the diary listing of the Emacs
  4182. calendar. Tables are easily created with a built-in table editor.
  4183. Plain text URL-like links connect to websites, emails (VM), Usenet
  4184. messages (Gnus), BBDB entries, and any files related to the project.
  4185. For printing and sharing of notes, an Org file (or a part of it)
  4186. can be exported as a structured ASCII or HTML file.
  4187. The following commands are available:
  4188. \\{org-mode-map}"
  4189. (org-load-modules-maybe)
  4190. (org-install-agenda-files-menu)
  4191. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4192. (add-to-invisibility-spec '(org-hide-block . t))
  4193. (add-to-invisibility-spec '(org-hide-drawer . t))
  4194. (setq-local outline-regexp org-outline-regexp)
  4195. (setq-local outline-level 'org-outline-level)
  4196. (setq bidi-paragraph-direction 'left-to-right)
  4197. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4198. (unless org-display-table
  4199. (setq org-display-table (make-display-table)))
  4200. (set-display-table-slot
  4201. org-display-table 4
  4202. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4203. org-ellipsis)))
  4204. (setq buffer-display-table org-display-table))
  4205. (org-set-regexps-and-options)
  4206. (org-set-font-lock-defaults)
  4207. (when (and org-tag-faces (not org-tags-special-faces-re))
  4208. ;; tag faces set outside customize.... force initialization.
  4209. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4210. ;; Calc embedded
  4211. (setq-local calc-embedded-open-mode "# ")
  4212. ;; Modify a few syntax entries
  4213. (modify-syntax-entry ?\" "\"")
  4214. (modify-syntax-entry ?\\ "_")
  4215. (modify-syntax-entry ?~ "_")
  4216. (modify-syntax-entry ?< "(>")
  4217. (modify-syntax-entry ?> ")<")
  4218. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4219. ;; Activate before-change-function
  4220. (setq-local org-table-may-need-update t)
  4221. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4222. ;; Check for running clock before killing a buffer
  4223. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4224. ;; Initialize macros templates.
  4225. (org-macro-initialize-templates)
  4226. ;; Initialize radio targets.
  4227. (org-update-radio-target-regexp)
  4228. ;; Indentation.
  4229. (setq-local indent-line-function 'org-indent-line)
  4230. (setq-local indent-region-function 'org-indent-region)
  4231. ;; Filling and auto-filling.
  4232. (org-setup-filling)
  4233. ;; Comments.
  4234. (org-setup-comments-handling)
  4235. ;; Initialize cache.
  4236. (org-element-cache-reset)
  4237. ;; Beginning/end of defun
  4238. (setq-local beginning-of-defun-function 'org-backward-element)
  4239. (setq-local end-of-defun-function
  4240. (lambda ()
  4241. (if (not (org-at-heading-p))
  4242. (org-forward-element)
  4243. (org-forward-element)
  4244. (forward-char -1))))
  4245. ;; Next error for sparse trees
  4246. (setq-local next-error-function 'org-occur-next-match)
  4247. ;; Make commit log messages from Org documents easier.
  4248. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4249. ;; Make sure dependence stuff works reliably, even for users who set it
  4250. ;; too late :-(
  4251. (if org-enforce-todo-dependencies
  4252. (add-hook 'org-blocker-hook
  4253. 'org-block-todo-from-children-or-siblings-or-parent)
  4254. (remove-hook 'org-blocker-hook
  4255. 'org-block-todo-from-children-or-siblings-or-parent))
  4256. (if org-enforce-todo-checkbox-dependencies
  4257. (add-hook 'org-blocker-hook
  4258. 'org-block-todo-from-checkboxes)
  4259. (remove-hook 'org-blocker-hook
  4260. 'org-block-todo-from-checkboxes))
  4261. ;; Align options lines
  4262. (setq-local
  4263. align-mode-rules-list
  4264. '((org-in-buffer-settings
  4265. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4266. (modes . '(org-mode)))))
  4267. ;; Make isearch reveal context
  4268. (setq-local outline-isearch-open-invisible-function
  4269. (lambda (&rest _) (org-show-context 'isearch)))
  4270. ;; Setup the pcomplete hooks
  4271. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4272. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4273. (setq-local pcomplete-default-completion-function #'ignore)
  4274. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4275. (setq-local pcomplete-termination-string "")
  4276. (add-hook 'completion-at-point-functions
  4277. #'pcomplete-completions-at-point nil t)
  4278. (setq-local buffer-face-mode-face 'org-default)
  4279. ;; If empty file that did not turn on Org mode automatically, make
  4280. ;; it to.
  4281. (when (and org-insert-mode-line-in-empty-file
  4282. (called-interactively-p 'any)
  4283. (= (point-min) (point-max)))
  4284. (insert "# -*- mode: org -*-\n\n"))
  4285. (unless org-inhibit-startup
  4286. (org-unmodified
  4287. (when org-startup-with-beamer-mode (org-beamer-mode))
  4288. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4289. (org-table-map-tables
  4290. (cond ((and org-startup-align-all-tables
  4291. org-startup-shrink-all-tables)
  4292. (lambda () (org-table-align) (org-table-shrink)))
  4293. (org-startup-align-all-tables #'org-table-align)
  4294. (t #'org-table-shrink))
  4295. t))
  4296. (when org-startup-with-inline-images (org-display-inline-images))
  4297. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4298. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4299. (when org-startup-truncated (setq truncate-lines t))
  4300. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4301. ;; Try to set `org-hide' face correctly.
  4302. (let ((foreground (org-find-invisible-foreground)))
  4303. (when foreground
  4304. (set-face-foreground 'org-hide foreground))))
  4305. ;; Update `customize-package-emacs-version-alist'
  4306. (add-to-list 'customize-package-emacs-version-alist
  4307. '(Org ("8.0" . "24.4")
  4308. ("8.1" . "24.4")
  4309. ("8.2" . "24.4")
  4310. ("8.2.7" . "24.4")
  4311. ("8.3" . "26.1")
  4312. ("9.0" . "26.1")
  4313. ("9.1" . "26.1")
  4314. ("9.2" . "27.1")
  4315. ("9.3" . "27.1")))
  4316. (defvar org-mode-transpose-word-syntax-table
  4317. (let ((st (make-syntax-table text-mode-syntax-table)))
  4318. (dolist (c org-emphasis-alist st)
  4319. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4320. (when (fboundp 'abbrev-table-put)
  4321. (abbrev-table-put org-mode-abbrev-table
  4322. :parents (list text-mode-abbrev-table)))
  4323. (defun org-find-invisible-foreground ()
  4324. (let ((candidates (remove
  4325. "unspecified-bg"
  4326. (nconc
  4327. (list (face-background 'default)
  4328. (face-background 'org-default))
  4329. (mapcar
  4330. (lambda (alist)
  4331. (when (boundp alist)
  4332. (cdr (assq 'background-color (symbol-value alist)))))
  4333. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4334. (list (face-foreground 'org-hide))))))
  4335. (car (remove nil candidates))))
  4336. (defun org-current-time (&optional rounding-minutes past)
  4337. "Current time, possibly rounded to ROUNDING-MINUTES.
  4338. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4339. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4340. the rounding returns a past time."
  4341. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4342. (car org-time-stamp-rounding-minutes)))
  4343. (now (current-time)))
  4344. (if (< r 1)
  4345. now
  4346. (let* ((time (decode-time now))
  4347. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4348. (nthcdr 2 time))))
  4349. (if (or (not past) (org-time-less-p res now))
  4350. res
  4351. (org-time-subtract res (* r 60)))))))
  4352. (defun org-today ()
  4353. "Return today date, considering `org-extend-today-until'."
  4354. (time-to-days
  4355. (org-time-since (* 3600 org-extend-today-until))))
  4356. ;;;; Font-Lock stuff, including the activators
  4357. (require 'font-lock)
  4358. (defconst org-match-sexp-depth 3
  4359. "Number of stacked braces for sub/superscript matching.")
  4360. (defun org-create-multibrace-regexp (left right n)
  4361. "Create a regular expression which will match a balanced sexp.
  4362. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4363. as single character strings.
  4364. The regexp returned will match the entire expression including the
  4365. delimiters. It will also define a single group which contains the
  4366. match except for the outermost delimiters. The maximum depth of
  4367. stacked delimiters is N. Escaping delimiters is not possible."
  4368. (let* ((nothing (concat "[^" left right "]*?"))
  4369. (or "\\|")
  4370. (re nothing)
  4371. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4372. (while (> n 1)
  4373. (setq n (1- n)
  4374. re (concat re or next)
  4375. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4376. (concat left "\\(" re "\\)" right)))
  4377. (defconst org-match-substring-regexp
  4378. (concat
  4379. "\\(\\S-\\)\\([_^]\\)\\("
  4380. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4381. "\\|"
  4382. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4383. "\\|"
  4384. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4385. "The regular expression matching a sub- or superscript.")
  4386. (defconst org-match-substring-with-braces-regexp
  4387. (concat
  4388. "\\(\\S-\\)\\([_^]\\)"
  4389. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4390. "The regular expression matching a sub- or superscript, forcing braces.")
  4391. (defvar org-emph-face nil)
  4392. (defun org-do-emphasis-faces (limit)
  4393. "Run through the buffer and emphasize strings."
  4394. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4395. (car org-emphasis-regexp-components))))
  4396. (catch :exit
  4397. (while (re-search-forward quick-re limit t)
  4398. (let* ((marker (match-string 2))
  4399. (verbatim? (member marker '("~" "="))))
  4400. (when (save-excursion
  4401. (goto-char (match-beginning 0))
  4402. (and
  4403. ;; Do not match table hlines.
  4404. (not (and (equal marker "+")
  4405. (org-match-line
  4406. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4407. ;; Do not match headline stars. Do not consider
  4408. ;; stars of a headline as closing marker for bold
  4409. ;; markup either.
  4410. (not (and (equal marker "*")
  4411. (save-excursion
  4412. (forward-char)
  4413. (skip-chars-backward "*")
  4414. (looking-at-p org-outline-regexp-bol))))
  4415. ;; Match full emphasis markup regexp.
  4416. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4417. ;; Do not span over paragraph boundaries.
  4418. (not (string-match-p org-element-paragraph-separate
  4419. (match-string 2)))
  4420. ;; Do not span over cells in table rows.
  4421. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4422. (string-match-p "|" (match-string 4))))))
  4423. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4424. (m (if org-hide-emphasis-markers 4 2)))
  4425. (font-lock-prepend-text-property
  4426. (match-beginning m) (match-end m) 'face face)
  4427. (when verbatim?
  4428. (org-remove-flyspell-overlays-in
  4429. (match-beginning 0) (match-end 0))
  4430. (remove-text-properties (match-beginning 2) (match-end 2)
  4431. '(display t invisible t intangible t)))
  4432. (add-text-properties (match-beginning 2) (match-end 2)
  4433. '(font-lock-multiline t org-emphasis t))
  4434. (when org-hide-emphasis-markers
  4435. (add-text-properties (match-end 4) (match-beginning 5)
  4436. '(invisible org-link))
  4437. (add-text-properties (match-beginning 3) (match-end 3)
  4438. '(invisible org-link)))
  4439. (throw :exit t))))))))
  4440. (defun org-emphasize (&optional char)
  4441. "Insert or change an emphasis, i.e. a font like bold or italic.
  4442. If there is an active region, change that region to a new emphasis.
  4443. If there is no region, just insert the marker characters and position
  4444. the cursor between them.
  4445. CHAR should be the marker character. If it is a space, it means to
  4446. remove the emphasis of the selected region.
  4447. If CHAR is not given (for example in an interactive call) it will be
  4448. prompted for."
  4449. (interactive)
  4450. (let ((erc org-emphasis-regexp-components)
  4451. (string "") beg end move s)
  4452. (if (org-region-active-p)
  4453. (setq beg (region-beginning)
  4454. end (region-end)
  4455. string (buffer-substring beg end))
  4456. (setq move t))
  4457. (unless char
  4458. (message "Emphasis marker or tag: [%s]"
  4459. (mapconcat #'car org-emphasis-alist ""))
  4460. (setq char (read-char-exclusive)))
  4461. (if (equal char ?\s)
  4462. (setq s ""
  4463. move nil)
  4464. (unless (assoc (char-to-string char) org-emphasis-alist)
  4465. (user-error "No such emphasis marker: \"%c\"" char))
  4466. (setq s (char-to-string char)))
  4467. (while (and (> (length string) 1)
  4468. (equal (substring string 0 1) (substring string -1))
  4469. (assoc (substring string 0 1) org-emphasis-alist))
  4470. (setq string (substring string 1 -1)))
  4471. (setq string (concat s string s))
  4472. (when beg (delete-region beg end))
  4473. (unless (or (bolp)
  4474. (string-match (concat "[" (nth 0 erc) "\n]")
  4475. (char-to-string (char-before (point)))))
  4476. (insert " "))
  4477. (unless (or (eobp)
  4478. (string-match (concat "[" (nth 1 erc) "\n]")
  4479. (char-to-string (char-after (point)))))
  4480. (insert " ") (backward-char 1))
  4481. (insert string)
  4482. (and move (backward-char 1))))
  4483. (defconst org-nonsticky-props
  4484. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4485. (defsubst org-rear-nonsticky-at (pos)
  4486. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4487. (defun org-activate-links (limit)
  4488. "Add link properties to links.
  4489. This includes angle, plain, and bracket links."
  4490. (catch :exit
  4491. (while (re-search-forward org-link-any-re limit t)
  4492. (let* ((start (match-beginning 0))
  4493. (end (match-end 0))
  4494. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4495. (visible-end (or (match-end 3) (match-end 2)))
  4496. (style (cond ((eq ?< (char-after start)) 'angle)
  4497. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4498. (t 'plain))))
  4499. (when (and (memq style org-highlight-links)
  4500. ;; Do not span over paragraph boundaries.
  4501. (not (string-match-p org-element-paragraph-separate
  4502. (match-string 0)))
  4503. ;; Do not confuse plain links with tags.
  4504. (not (and (eq style 'plain)
  4505. (let ((face (get-text-property
  4506. (max (1- start) (point-min)) 'face)))
  4507. (if (consp face) (memq 'org-tag face)
  4508. (eq 'org-tag face))))))
  4509. (let* ((link-object (save-excursion
  4510. (goto-char start)
  4511. (save-match-data (org-element-link-parser))))
  4512. (link (org-element-property :raw-link link-object))
  4513. (type (org-element-property :type link-object))
  4514. (path (org-element-property :path link-object))
  4515. (properties ;for link's visible part
  4516. (list
  4517. 'face (pcase (org-link-get-parameter type :face)
  4518. ((and (pred functionp) face) (funcall face path))
  4519. ((and (pred facep) face) face)
  4520. ((and (pred consp) face) face) ;anonymous
  4521. (_ 'org-link))
  4522. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4523. 'highlight)
  4524. 'keymap (or (org-link-get-parameter type :keymap)
  4525. org-mouse-map)
  4526. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4527. ((and (pred stringp) echo) echo)
  4528. ((and (pred functionp) echo) echo)
  4529. (_ (concat "LINK: " link)))
  4530. 'htmlize-link (pcase (org-link-get-parameter type
  4531. :htmlize-link)
  4532. ((and (pred functionp) f) (funcall f))
  4533. (_ `(:uri ,link)))
  4534. 'font-lock-multiline t)))
  4535. (org-remove-flyspell-overlays-in start end)
  4536. (org-rear-nonsticky-at end)
  4537. (if (not (eq 'bracket style))
  4538. (add-text-properties start end properties)
  4539. ;; Handle invisible parts in bracket links.
  4540. (remove-text-properties start end '(invisible nil))
  4541. (let ((hidden
  4542. (append `(invisible
  4543. ,(or (org-link-get-parameter type :display)
  4544. 'org-link))
  4545. properties)))
  4546. (add-text-properties start visible-start hidden)
  4547. (add-text-properties visible-start visible-end properties)
  4548. (add-text-properties visible-end end hidden)
  4549. (org-rear-nonsticky-at visible-start)
  4550. (org-rear-nonsticky-at visible-end)))
  4551. (let ((f (org-link-get-parameter type :activate-func)))
  4552. (when (functionp f)
  4553. (funcall f start end path (eq style 'bracket))))
  4554. (throw :exit t))))) ;signal success
  4555. nil))
  4556. (defun org-activate-code (limit)
  4557. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4558. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4559. (remove-text-properties (match-beginning 0) (match-end 0)
  4560. '(display t invisible t intangible t))
  4561. t))
  4562. (defcustom org-src-fontify-natively t
  4563. "When non-nil, fontify code in code blocks.
  4564. See also the `org-block' face."
  4565. :type 'boolean
  4566. :version "26.1"
  4567. :package-version '(Org . "8.3")
  4568. :group 'org-appearance
  4569. :group 'org-babel)
  4570. (defcustom org-allow-promoting-top-level-subtree nil
  4571. "When non-nil, allow promoting a top level subtree.
  4572. The leading star of the top level headline will be replaced
  4573. by a #."
  4574. :type 'boolean
  4575. :version "24.1"
  4576. :group 'org-appearance)
  4577. (defun org-fontify-meta-lines-and-blocks (limit)
  4578. (condition-case nil
  4579. (org-fontify-meta-lines-and-blocks-1 limit)
  4580. (error (message "Org mode fontification error in %S at %d"
  4581. (current-buffer)
  4582. (line-number-at-pos)))))
  4583. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4584. "Fontify #+ lines and blocks."
  4585. (let ((case-fold-search t))
  4586. (when (re-search-forward
  4587. (rx bol (group (zero-or-more blank) "#"
  4588. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4589. space
  4590. eol))
  4591. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4592. (zero-or-more blank)
  4593. (group (group (zero-or-more (not (any " \t\n"))))
  4594. (zero-or-more blank)
  4595. (group (zero-or-more any)))))
  4596. limit t)
  4597. (let ((beg (match-beginning 0))
  4598. (end-of-beginline (match-end 0))
  4599. (block-start (match-end 0)) ; includes the \n at end of #+begin line
  4600. (block-end nil) ; will include \n after end of block content
  4601. (lang (match-string 7)) ; the language, if it is an src block
  4602. (bol-after-beginline (line-beginning-position 2))
  4603. (dc1 (downcase (match-string 2)))
  4604. (dc3 (downcase (match-string 3)))
  4605. (whole-blockline org-fontify-whole-block-delimiter-line)
  4606. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4607. (cond
  4608. ((and (match-end 4) (equal dc3 "+begin"))
  4609. ;; Truly a block
  4610. (setq block-type (downcase (match-string 5))
  4611. quoting (member block-type org-protecting-blocks)) ; src, example, export, maybe more
  4612. (when (re-search-forward
  4613. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4614. (seq (zero-or-more blank)
  4615. "#+end"
  4616. ,(match-string 4)
  4617. word-end
  4618. (zero-or-more any)))))
  4619. nil t) ;; on purpose, we look further than LIMIT
  4620. ;; We do have a matching #+end line
  4621. (setq beg-of-endline (match-beginning 0)
  4622. end-of-endline (match-end 0)
  4623. nl-before-endline (1- (match-beginning 0)))
  4624. (setq block-end (match-beginning 0)) ; includes the final newline.
  4625. (when quoting
  4626. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4627. (remove-text-properties beg end-of-endline
  4628. '(display t invisible t intangible t)))
  4629. (add-text-properties
  4630. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4631. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4632. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4633. (cond
  4634. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4635. (org-src-font-lock-fontify-block lang block-start block-end)
  4636. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4637. (quoting
  4638. (add-text-properties
  4639. bol-after-beginline beg-of-endline
  4640. (list 'face
  4641. (list :inherit
  4642. (let ((face-name
  4643. (intern (format "org-block-%s" lang))))
  4644. (append (and (facep face-name) (list face-name))
  4645. '(org-block)))))))
  4646. ((not org-fontify-quote-and-verse-blocks))
  4647. ((string= block-type "quote")
  4648. (add-face-text-property
  4649. bol-after-beginline beg-of-endline 'org-quote t))
  4650. ((string= block-type "verse")
  4651. (add-face-text-property
  4652. bol-after-beginline beg-of-endline 'org-verse t)))
  4653. ;; Fontify the #+begin and #+end lines of the blocks
  4654. (add-text-properties
  4655. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4656. '(face org-block-begin-line))
  4657. (unless (string-prefix-p "*" (match-string 1))
  4658. (add-text-properties
  4659. beg-of-endline
  4660. (if whole-blockline
  4661. (let ((beg-of-next-line (1+ end-of-endline)))
  4662. (min (point-max) beg-of-next-line))
  4663. (min (point-max) end-of-endline))
  4664. '(face org-block-end-line)))
  4665. t))
  4666. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  4667. (org-remove-flyspell-overlays-in
  4668. (match-beginning 0)
  4669. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4670. (add-text-properties
  4671. beg (match-end 3)
  4672. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4673. '(font-lock-fontified t invisible t)
  4674. '(font-lock-fontified t face org-document-info-keyword)))
  4675. (add-text-properties
  4676. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4677. (if (string-equal dc1 "+title:")
  4678. '(font-lock-fontified t face org-document-title)
  4679. '(font-lock-fontified t face org-document-info))))
  4680. ((string-prefix-p "+caption" dc1)
  4681. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4682. (remove-text-properties (match-beginning 0) (match-end 0)
  4683. '(display t invisible t intangible t))
  4684. ;; Handle short captions.
  4685. (save-excursion
  4686. (beginning-of-line)
  4687. (looking-at (rx (group (zero-or-more blank)
  4688. "#+caption"
  4689. (optional "[" (zero-or-more any) "]")
  4690. ":")
  4691. (zero-or-more blank))))
  4692. (add-text-properties (line-beginning-position) (match-end 1)
  4693. '(font-lock-fontified t face org-meta-line))
  4694. (add-text-properties (match-end 0) (line-end-position)
  4695. '(font-lock-fontified t face org-block))
  4696. t)
  4697. ((member dc3 '(" " ""))
  4698. ; Just a comment, the plus was not there
  4699. (org-remove-flyspell-overlays-in beg (match-end 0))
  4700. (add-text-properties
  4701. beg (match-end 0)
  4702. '(font-lock-fontified t face font-lock-comment-face)))
  4703. (t ;; just any other in-buffer setting, but not indented
  4704. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4705. (remove-text-properties (match-beginning 0) (match-end 0)
  4706. '(display t invisible t intangible t))
  4707. (add-text-properties beg (match-end 0)
  4708. '(font-lock-fontified t face org-meta-line))
  4709. t))))))
  4710. (defun org-fontify-drawers (limit)
  4711. "Fontify drawers."
  4712. (when (re-search-forward org-drawer-regexp limit t)
  4713. (add-text-properties
  4714. (line-beginning-position) (line-beginning-position 2)
  4715. '(font-lock-fontified t face org-drawer))
  4716. (org-remove-flyspell-overlays-in
  4717. (line-beginning-position) (line-beginning-position 2))
  4718. t))
  4719. (defun org-fontify-macros (limit)
  4720. "Fontify macros."
  4721. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4722. (let ((begin (match-beginning 0))
  4723. (opening-end (match-beginning 1)))
  4724. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4725. (match-string 1))
  4726. (let ((end (match-end 1))
  4727. (closing-start (match-beginning 1)))
  4728. (add-text-properties
  4729. begin end
  4730. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4731. (org-remove-flyspell-overlays-in begin end)
  4732. (when org-hide-macro-markers
  4733. (add-text-properties begin opening-end '(invisible t))
  4734. (add-text-properties closing-start end '(invisible t)))
  4735. t)))))
  4736. (defun org-fontify-extend-region (beg end _old-len)
  4737. (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4738. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4739. (extend (lambda (r1 r2 dir)
  4740. (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
  4741. (replace-regexp-in-string "[][]" r2
  4742. (match-string-no-properties 0)))))
  4743. (re-search-forward (regexp-quote re) nil t dir)))))
  4744. (save-match-data
  4745. (save-excursion
  4746. (goto-char beg)
  4747. (back-to-indentation)
  4748. (cond ((looking-at end-re)
  4749. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4750. ((looking-at begin-re)
  4751. (cons beg (or (funcall extend "end" "]" 1) end)))
  4752. (t (cons beg end)))))))
  4753. (defun org-activate-footnote-links (limit)
  4754. "Add text properties for footnotes."
  4755. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4756. (when fn
  4757. (let* ((beg (nth 1 fn))
  4758. (end (nth 2 fn))
  4759. (label (car fn))
  4760. (referencep (/= (line-beginning-position) beg)))
  4761. (when (and referencep (nth 3 fn))
  4762. (save-excursion
  4763. (goto-char beg)
  4764. (search-forward (or label "fn:"))
  4765. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4766. (add-text-properties beg end
  4767. (list 'mouse-face 'highlight
  4768. 'keymap org-mouse-map
  4769. 'help-echo
  4770. (if referencep "Footnote reference"
  4771. "Footnote definition")
  4772. 'font-lock-fontified t
  4773. 'font-lock-multiline t
  4774. 'face 'org-footnote))))))
  4775. (defun org-activate-dates (limit)
  4776. "Add text properties for dates."
  4777. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4778. (not (equal (char-before (match-beginning 0)) 91)))
  4779. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4780. (add-text-properties (match-beginning 0) (match-end 0)
  4781. (list 'mouse-face 'highlight
  4782. 'keymap org-mouse-map))
  4783. (org-rear-nonsticky-at (match-end 0))
  4784. (when org-display-custom-times
  4785. ;; If it's a date range, activate custom time for second date.
  4786. (when (match-end 3)
  4787. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4788. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4789. t))
  4790. (defun org-activate-target-links (limit)
  4791. "Add text properties for target matches."
  4792. (when org-target-link-regexp
  4793. (let ((case-fold-search t))
  4794. ;; `org-target-link-regexp' matches one character before the
  4795. ;; actual target.
  4796. (unless (bolp) (forward-char -1))
  4797. (when (re-search-forward org-target-link-regexp limit t)
  4798. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4799. (add-text-properties (match-beginning 1) (match-end 1)
  4800. (list 'mouse-face 'highlight
  4801. 'keymap org-mouse-map
  4802. 'help-echo "Radio target link"
  4803. 'org-linked-text t))
  4804. (org-rear-nonsticky-at (match-end 1))
  4805. t))))
  4806. (defvar org-latex-and-related-regexp nil
  4807. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4808. (defun org-compute-latex-and-related-regexp ()
  4809. "Compute regular expression for LaTeX, entities and sub/superscript.
  4810. Result depends on variable `org-highlight-latex-and-related'."
  4811. (let ((re-sub
  4812. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4813. ((eq org-use-sub-superscripts '{})
  4814. (list org-match-substring-with-braces-regexp))
  4815. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4816. (re-latex
  4817. (when (or (memq 'latex org-highlight-latex-and-related)
  4818. (memq 'native org-highlight-latex-and-related))
  4819. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4820. (delq nil
  4821. (mapcar (lambda (x)
  4822. (and (member (car x) matchers) (nth 1 x)))
  4823. org-latex-regexps)))))
  4824. (re-entities
  4825. (when (memq 'entities org-highlight-latex-and-related)
  4826. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4827. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4828. (setq-local org-latex-and-related-regexp
  4829. (mapconcat #'identity
  4830. (append re-latex re-entities re-sub)
  4831. "\\|"))))
  4832. (defun org-do-latex-and-related (_limit)
  4833. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4834. Stop at first highlighted object, if any. Return t if some
  4835. highlighting was done, nil otherwise."
  4836. (when (org-string-nw-p org-latex-and-related-regexp)
  4837. (catch 'found
  4838. (while (re-search-forward org-latex-and-related-regexp
  4839. nil t) ;; on purpose, we ignore LIMIT
  4840. (unless (cl-some (lambda (f) (memq f '(org-code org-verbatim underline
  4841. org-special-keyword)))
  4842. (save-excursion
  4843. (goto-char (1+ (match-beginning 0)))
  4844. (face-at-point nil t)))
  4845. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4846. '(?_ ?^))
  4847. 1
  4848. 0))
  4849. (start (+ offset (match-beginning 0)))
  4850. (end (match-end 0)))
  4851. (if (memq 'native org-highlight-latex-and-related)
  4852. (org-src-font-lock-fontify-block "latex" start end)
  4853. (font-lock-prepend-text-property start end
  4854. 'face 'org-latex-and-related))
  4855. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4856. '(font-lock-multiline t)))
  4857. (throw 'found t)))
  4858. nil)))
  4859. (defun org-restart-font-lock ()
  4860. "Restart `font-lock-mode', to force refontification."
  4861. (when (and (boundp 'font-lock-mode) font-lock-mode)
  4862. (font-lock-mode -1)
  4863. (font-lock-mode 1)))
  4864. (defun org-activate-tags (limit)
  4865. (when (re-search-forward org-tag-line-re limit t)
  4866. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4867. (add-text-properties (match-beginning 1) (match-end 1)
  4868. (list 'mouse-face 'highlight
  4869. 'keymap org-mouse-map))
  4870. (org-rear-nonsticky-at (match-end 1))
  4871. t))
  4872. (defun org-outline-level ()
  4873. "Compute the outline level of the heading at point.
  4874. If this is called at a normal headline, the level is the number
  4875. of stars. Use `org-reduced-level' to remove the effect of
  4876. `org-odd-levels'. Unlike to `org-current-level', this function
  4877. takes into consideration inlinetasks."
  4878. (org-with-wide-buffer
  4879. (end-of-line)
  4880. (if (re-search-backward org-outline-regexp-bol nil t)
  4881. (1- (- (match-end 0) (match-beginning 0)))
  4882. 0)))
  4883. (defvar org-font-lock-keywords nil)
  4884. (defsubst org-re-property (property &optional literal allow-null value)
  4885. "Return a regexp matching a PROPERTY line.
  4886. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4887. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4888. non-nil, match properties even without a value.
  4889. Match group 3 is set to the value when it exists. If there is no
  4890. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4891. With optional argument VALUE, match only property lines with
  4892. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4893. unless LITERAL is non-nil."
  4894. (concat
  4895. "^\\(?4:[ \t]*\\)"
  4896. (format "\\(?1::\\(?2:%s\\):\\)"
  4897. (if literal property (regexp-quote property)))
  4898. (cond (value
  4899. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4900. (if literal value (regexp-quote value))))
  4901. (allow-null
  4902. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4903. (t
  4904. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4905. (defconst org-property-re
  4906. (org-re-property "\\S-+" 'literal t)
  4907. "Regular expression matching a property line.
  4908. There are four matching groups:
  4909. 1: :PROPKEY: including the leading and trailing colon,
  4910. 2: PROPKEY without the leading and trailing colon,
  4911. 3: PROPVAL without leading or trailing spaces,
  4912. 4: the indentation of the current line,
  4913. 5: trailing whitespace.")
  4914. (defvar org-font-lock-hook nil
  4915. "Functions to be called for special font lock stuff.")
  4916. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4917. (defvar org-font-lock-set-keywords-hook nil
  4918. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4919. This is called after `org-font-lock-extra-keywords' is defined, but before
  4920. it is installed to be used by font lock. This can be useful if something
  4921. needs to be inserted at a specific position in the font-lock sequence.")
  4922. (defun org-font-lock-hook (limit)
  4923. "Run `org-font-lock-hook' within LIMIT."
  4924. (run-hook-with-args 'org-font-lock-hook limit))
  4925. (defun org-set-font-lock-defaults ()
  4926. "Set font lock defaults for the current buffer."
  4927. (let* ((em org-fontify-emphasized-text)
  4928. (lk org-highlight-links)
  4929. (org-font-lock-extra-keywords
  4930. (list
  4931. ;; Call the hook
  4932. '(org-font-lock-hook)
  4933. ;; Headlines
  4934. `(,(if org-fontify-whole-heading-line
  4935. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4936. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4937. (1 (org-get-level-face 1))
  4938. (2 (org-get-level-face 2))
  4939. (3 (org-get-level-face 3)))
  4940. ;; Table lines
  4941. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4942. (1 'org-table t))
  4943. ;; Table internals
  4944. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4945. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4946. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4947. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4948. ;; Properties
  4949. (list org-property-re
  4950. '(1 'org-special-keyword t)
  4951. '(3 'org-property-value t))
  4952. ;; Drawers
  4953. '(org-fontify-drawers)
  4954. ;; Link related fontification.
  4955. '(org-activate-links)
  4956. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  4957. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  4958. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  4959. (when (memq 'footnote lk) '(org-activate-footnote-links))
  4960. ;; Targets.
  4961. (list org-radio-target-regexp '(0 'org-target t))
  4962. (list org-target-regexp '(0 'org-target t))
  4963. ;; Diary sexps.
  4964. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  4965. ;; Macro
  4966. '(org-fontify-macros)
  4967. ;; TODO keyword
  4968. (list (format org-heading-keyword-regexp-format
  4969. org-todo-regexp)
  4970. '(2 (org-get-todo-face 2) t))
  4971. ;; DONE
  4972. (if org-fontify-done-headline
  4973. (list (format org-heading-keyword-regexp-format
  4974. (concat
  4975. "\\(?:"
  4976. (mapconcat 'regexp-quote org-done-keywords "\\|")
  4977. "\\)"))
  4978. '(2 'org-headline-done t))
  4979. nil)
  4980. ;; Priorities
  4981. '(org-font-lock-add-priority-faces)
  4982. ;; Tags
  4983. '(org-font-lock-add-tag-faces)
  4984. ;; Tags groups
  4985. (when (and org-group-tags org-tag-groups-alist)
  4986. (list (concat org-outline-regexp-bol ".+\\(:"
  4987. (regexp-opt (mapcar 'car org-tag-groups-alist))
  4988. ":\\).*$")
  4989. '(1 'org-tag-group prepend)))
  4990. ;; Special keywords
  4991. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  4992. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  4993. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  4994. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  4995. ;; Emphasis
  4996. (when em '(org-do-emphasis-faces))
  4997. ;; Checkboxes
  4998. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  4999. 1 'org-checkbox prepend)
  5000. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5001. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5002. (0 (org-get-checkbox-statistics-face) t)))
  5003. ;; Description list items
  5004. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5005. 1 'org-list-dt prepend)
  5006. ;; ARCHIVEd headings
  5007. (list (concat
  5008. org-outline-regexp-bol
  5009. "\\(.*:" org-archive-tag ":.*\\)")
  5010. '(1 'org-archived prepend))
  5011. ;; Specials
  5012. '(org-do-latex-and-related)
  5013. '(org-fontify-entities)
  5014. '(org-raise-scripts)
  5015. ;; Code
  5016. '(org-activate-code (1 'org-code t))
  5017. ;; COMMENT
  5018. (list (format
  5019. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5020. org-todo-regexp
  5021. org-comment-string)
  5022. '(9 'org-special-keyword t))
  5023. ;; Blocks and meta lines
  5024. '(org-fontify-meta-lines-and-blocks))))
  5025. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5026. (run-hooks 'org-font-lock-set-keywords-hook)
  5027. ;; Now set the full font-lock-keywords
  5028. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5029. (setq-local font-lock-defaults
  5030. '(org-font-lock-keywords t nil nil backward-paragraph))
  5031. (setq-local font-lock-extend-after-change-region-function
  5032. #'org-fontify-extend-region)
  5033. (kill-local-variable 'font-lock-keywords)
  5034. nil))
  5035. (defun org-toggle-pretty-entities ()
  5036. "Toggle the composition display of entities as UTF8 characters."
  5037. (interactive)
  5038. (setq-local org-pretty-entities (not org-pretty-entities))
  5039. (org-restart-font-lock)
  5040. (if org-pretty-entities
  5041. (message "Entities are now displayed as UTF8 characters")
  5042. (save-restriction
  5043. (widen)
  5044. (decompose-region (point-min) (point-max))
  5045. (message "Entities are now displayed as plain text"))))
  5046. (defvar-local org-custom-properties-overlays nil
  5047. "List of overlays used for custom properties.")
  5048. (defun org-toggle-custom-properties-visibility ()
  5049. "Display or hide properties in `org-custom-properties'."
  5050. (interactive)
  5051. (if org-custom-properties-overlays
  5052. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5053. (setq org-custom-properties-overlays nil))
  5054. (when org-custom-properties
  5055. (org-with-wide-buffer
  5056. (goto-char (point-min))
  5057. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5058. (while (re-search-forward regexp nil t)
  5059. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5060. (when (and end (< (point) end))
  5061. ;; Hide first custom property in current drawer.
  5062. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5063. (overlay-put o 'invisible t)
  5064. (overlay-put o 'org-custom-property t)
  5065. (push o org-custom-properties-overlays))
  5066. ;; Hide additional custom properties in the same drawer.
  5067. (while (re-search-forward regexp end t)
  5068. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5069. (overlay-put o 'invisible t)
  5070. (overlay-put o 'org-custom-property t)
  5071. (push o org-custom-properties-overlays)))))
  5072. ;; Each entry is limited to a single property drawer.
  5073. (outline-next-heading)))))))
  5074. (defun org-fontify-entities (limit)
  5075. "Find an entity to fontify."
  5076. (let (ee)
  5077. (when org-pretty-entities
  5078. (catch 'match
  5079. ;; "\_ "-family is left out on purpose. Only the first one,
  5080. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5081. ;; confusing when adding a second white space character.
  5082. (while (re-search-forward
  5083. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5084. limit t)
  5085. (when (and (not (org-at-comment-p))
  5086. (setq ee (org-entity-get (match-string 1)))
  5087. (= (length (nth 6 ee)) 1))
  5088. (let* ((end (if (equal (match-string 2) "{}")
  5089. (match-end 2)
  5090. (match-end 1))))
  5091. (add-text-properties
  5092. (match-beginning 0) end
  5093. (list 'font-lock-fontified t))
  5094. (compose-region (match-beginning 0) end
  5095. (nth 6 ee) nil)
  5096. (backward-char 1)
  5097. (throw 'match t))))
  5098. nil))))
  5099. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5100. "Fontify string S like in Org mode."
  5101. (with-temp-buffer
  5102. (insert s)
  5103. (let ((org-odd-levels-only odd-levels))
  5104. (org-mode)
  5105. (org-font-lock-ensure)
  5106. (buffer-string))))
  5107. (defvar org-m nil)
  5108. (defvar org-l nil)
  5109. (defvar org-f nil)
  5110. (defun org-get-level-face (n)
  5111. "Get the right face for match N in font-lock matching of headlines."
  5112. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5113. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5114. (if org-cycle-level-faces
  5115. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5116. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5117. (cond
  5118. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5119. ((eq n 2) org-f)
  5120. (t (unless org-level-color-stars-only org-f))))
  5121. (defun org-face-from-face-or-color (context inherit face-or-color)
  5122. "Create a face list that inherits INHERIT, but sets the foreground color.
  5123. When FACE-OR-COLOR is not a string, just return it."
  5124. (if (stringp face-or-color)
  5125. (list :inherit inherit
  5126. (cdr (assoc context org-faces-easy-properties))
  5127. face-or-color)
  5128. face-or-color))
  5129. (defun org-get-todo-face (kwd)
  5130. "Get the right face for a TODO keyword KWD.
  5131. If KWD is a number, get the corresponding match group."
  5132. (when (numberp kwd) (setq kwd (match-string kwd)))
  5133. (or (org-face-from-face-or-color
  5134. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5135. (and (member kwd org-done-keywords) 'org-done)
  5136. 'org-todo))
  5137. (defun org-get-priority-face (priority)
  5138. "Get the right face for PRIORITY.
  5139. PRIORITY is a character."
  5140. (or (org-face-from-face-or-color
  5141. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5142. 'org-priority))
  5143. (defun org-get-tag-face (tag)
  5144. "Get the right face for TAG.
  5145. If TAG is a number, get the corresponding match group."
  5146. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5147. (or (org-face-from-face-or-color
  5148. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5149. 'org-tag)))
  5150. (defun org-font-lock-add-priority-faces (limit)
  5151. "Add the special priority faces."
  5152. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5153. (add-text-properties
  5154. (match-beginning 1) (match-end 1)
  5155. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5156. 'font-lock-fontified t))))
  5157. (defun org-font-lock-add-tag-faces (limit)
  5158. "Add the special tag faces."
  5159. (when (and org-tag-faces org-tags-special-faces-re)
  5160. (while (re-search-forward org-tags-special-faces-re limit t)
  5161. (add-text-properties (match-beginning 1) (match-end 1)
  5162. (list 'face (org-get-tag-face 1)
  5163. 'font-lock-fontified t))
  5164. (backward-char 1))))
  5165. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5166. "Remove fontification and activation overlays from links."
  5167. (font-lock-default-unfontify-region beg end)
  5168. (let* ((buffer-undo-list t)
  5169. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5170. (inhibit-modification-hooks t)
  5171. deactivate-mark buffer-file-name buffer-file-truename)
  5172. (decompose-region beg end)
  5173. (remove-text-properties beg end
  5174. '(mouse-face t keymap t org-linked-text t
  5175. invisible t intangible t
  5176. org-emphasis t))
  5177. (org-remove-font-lock-display-properties beg end)))
  5178. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5179. ((raise 0.3) (height 0.7))
  5180. ((raise -0.5))
  5181. ((raise 0.5)))
  5182. "Display properties for showing superscripts and subscripts.")
  5183. (defun org-remove-font-lock-display-properties (beg end)
  5184. "Remove specific display properties that have been added by font lock.
  5185. The will remove the raise properties that are used to show superscripts
  5186. and subscripts."
  5187. (let (next prop)
  5188. (while (< beg end)
  5189. (setq next (next-single-property-change beg 'display nil end)
  5190. prop (get-text-property beg 'display))
  5191. (when (member prop org-script-display)
  5192. (put-text-property beg next 'display nil))
  5193. (setq beg next))))
  5194. (defun org-raise-scripts (limit)
  5195. "Add raise properties to sub/superscripts."
  5196. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5197. (re-search-forward
  5198. (if (eq org-use-sub-superscripts t)
  5199. org-match-substring-regexp
  5200. org-match-substring-with-braces-regexp)
  5201. limit t))
  5202. (let* ((pos (point)) table-p comment-p
  5203. (mpos (match-beginning 3))
  5204. (emph-p (get-text-property mpos 'org-emphasis))
  5205. (link-p (get-text-property mpos 'mouse-face))
  5206. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5207. (goto-char (point-at-bol))
  5208. (setq table-p (looking-at-p org-table-dataline-regexp)
  5209. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5210. (goto-char pos)
  5211. ;; Handle a_b^c
  5212. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5213. (unless (or comment-p emph-p link-p keyw-p)
  5214. (put-text-property (match-beginning 3) (match-end 0)
  5215. 'display
  5216. (if (equal (char-after (match-beginning 2)) ?^)
  5217. (nth (if table-p 3 1) org-script-display)
  5218. (nth (if table-p 2 0) org-script-display)))
  5219. (add-text-properties (match-beginning 2) (match-end 2)
  5220. (list 'invisible t))
  5221. (when (and (eq (char-after (match-beginning 3)) ?{)
  5222. (eq (char-before (match-end 3)) ?}))
  5223. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5224. (list 'invisible t))
  5225. (add-text-properties (1- (match-end 3)) (match-end 3)
  5226. (list 'invisible t))))
  5227. t)))
  5228. (defun org-remove-empty-overlays-at (pos)
  5229. "Remove outline overlays that do not contain non-white stuff."
  5230. (dolist (o (overlays-at pos))
  5231. (and (eq 'outline (overlay-get o 'invisible))
  5232. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5233. (overlay-end o))))
  5234. (delete-overlay o))))
  5235. (defun org-show-empty-lines-in-parent ()
  5236. "Move to the parent and re-show empty lines before visible headlines."
  5237. (save-excursion
  5238. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5239. (org-cycle-show-empty-lines context))))
  5240. (defun org-files-list ()
  5241. "Return `org-agenda-files' list, plus all open Org files.
  5242. This is useful for operations that need to scan all of a user's
  5243. open and agenda-wise Org files."
  5244. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5245. (dolist (buf (buffer-list))
  5246. (with-current-buffer buf
  5247. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5248. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5249. :test #'equal))))
  5250. files))
  5251. (defsubst org-entry-beginning-position ()
  5252. "Return the beginning position of the current entry."
  5253. (save-excursion (org-back-to-heading t) (point)))
  5254. (defsubst org-entry-end-position ()
  5255. "Return the end position of the current entry."
  5256. (save-excursion (outline-next-heading) (point)))
  5257. (defun org-subtree-end-visible-p ()
  5258. "Is the end of the current subtree visible?"
  5259. (pos-visible-in-window-p
  5260. (save-excursion (org-end-of-subtree t) (point))))
  5261. (defun org-first-headline-recenter ()
  5262. "Move cursor to the first headline and recenter the headline."
  5263. (let ((window (get-buffer-window)))
  5264. (when window
  5265. (goto-char (point-min))
  5266. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5267. (set-window-start window (line-beginning-position))))))
  5268. ;;; Visibility (headlines, blocks, drawers)
  5269. ;;;; Headlines visibility
  5270. (defun org-show-entry ()
  5271. "Show the body directly following this heading.
  5272. Show the heading too, if it is currently invisible."
  5273. (interactive)
  5274. (save-excursion
  5275. (ignore-errors
  5276. (org-back-to-heading t)
  5277. (org-flag-region
  5278. (line-end-position 0)
  5279. (save-excursion
  5280. (if (re-search-forward
  5281. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5282. (match-beginning 1)
  5283. (point-max)))
  5284. nil
  5285. 'outline))))
  5286. (defun org-show-children (&optional level)
  5287. "Show all direct subheadings of this heading.
  5288. Prefix arg LEVEL is how many levels below the current level
  5289. should be shown. Default is enough to cause the following
  5290. heading to appear."
  5291. (interactive "p")
  5292. (save-excursion
  5293. (org-back-to-heading t)
  5294. (let* ((current-level (funcall outline-level))
  5295. (max-level (org-get-valid-level
  5296. current-level
  5297. (if level (prefix-numeric-value level) 1)))
  5298. (end (save-excursion (org-end-of-subtree t t)))
  5299. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5300. (past-first-child nil)
  5301. ;; Make sure to skip inlinetasks.
  5302. (re (format regexp-fmt
  5303. current-level
  5304. (cond
  5305. ((not (featurep 'org-inlinetask)) "")
  5306. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5307. 3))
  5308. (t (1- org-inlinetask-min-level))))))
  5309. ;; Display parent heading.
  5310. (org-flag-heading nil)
  5311. (forward-line)
  5312. ;; Display children. First child may be deeper than expected
  5313. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5314. ;; MAX-LEVEL accordingly.
  5315. (while (re-search-forward re end t)
  5316. (unless past-first-child
  5317. (setq re (format regexp-fmt
  5318. current-level
  5319. (max (funcall outline-level) max-level)))
  5320. (setq past-first-child t))
  5321. (org-flag-heading nil)))))
  5322. (defun org-show-subtree ()
  5323. "Show everything after this heading at deeper levels."
  5324. (interactive)
  5325. (org-flag-region
  5326. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5327. ;;;; Blocks visibility
  5328. (defun org-hide-block-toggle-maybe ()
  5329. "Toggle visibility of block at point.
  5330. Unlike to `org-hide-block-toggle', this function does not throw
  5331. an error. Return a non-nil value when toggling is successful."
  5332. (interactive)
  5333. (ignore-errors (org-hide-block-toggle)))
  5334. (defun org-hide-block-toggle (&optional force)
  5335. "Toggle the visibility of the current block.
  5336. When optional argument FORCE is `off', make block visible. If it
  5337. is non-nil, hide it unconditionally. Throw an error when not at
  5338. a block. Return a non-nil value when toggling is successful."
  5339. (interactive)
  5340. (let ((element (org-element-at-point)))
  5341. (unless (memq (org-element-type element)
  5342. '(center-block comment-block dynamic-block example-block
  5343. export-block quote-block special-block
  5344. src-block verse-block))
  5345. (user-error "Not at a block"))
  5346. (let* ((post (org-element-property :post-affiliated element))
  5347. (start (save-excursion
  5348. (goto-char post)
  5349. (line-end-position)))
  5350. (end (save-excursion
  5351. (goto-char (org-element-property :end element))
  5352. (skip-chars-backward " \t\n")
  5353. (line-end-position))))
  5354. ;; Do nothing when not before or at the block opening line or at
  5355. ;; the block closing line.
  5356. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5357. (cond ((eq force 'off)
  5358. (org-flag-region start end nil 'org-hide-block))
  5359. (force
  5360. (org-flag-region start end t 'org-hide-block))
  5361. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5362. (org-flag-region start end nil 'org-hide-block))
  5363. (t
  5364. (org-flag-region start end t 'org-hide-block)))
  5365. ;; When the block is hidden away, make sure point is left in
  5366. ;; a visible part of the buffer.
  5367. (when (invisible-p (max (1- (point)) (point-min)))
  5368. (goto-char post))
  5369. ;; Signal success.
  5370. t))))
  5371. (defun org-hide-block-toggle-all ()
  5372. "Toggle the visibility of all blocks in the current buffer."
  5373. (org-block-map 'org-hide-block-toggle))
  5374. (defun org-hide-block-all ()
  5375. "Fold all blocks in the current buffer."
  5376. (interactive)
  5377. (org-show-all '(blocks))
  5378. (org-block-map 'org-hide-block-toggle-maybe))
  5379. ;;;; Drawers visibility
  5380. (defun org-cycle-hide-drawers (state &optional exceptions)
  5381. "Re-hide all drawers after a visibility state change.
  5382. STATE should be one of the symbols listed in the docstring of
  5383. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5384. a list of strings specifying which drawers should not be hidden."
  5385. (when (and (derived-mode-p 'org-mode)
  5386. (not (memq state '(overview folded contents))))
  5387. (save-excursion
  5388. (let* ((globalp (eq state 'all))
  5389. (beg (if globalp (point-min) (point)))
  5390. (end (if globalp (point-max)
  5391. (if (eq state 'children)
  5392. (save-excursion (outline-next-heading) (point))
  5393. (org-end-of-subtree t)))))
  5394. (goto-char beg)
  5395. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5396. (unless (member-ignore-case (match-string 1) exceptions)
  5397. (let ((drawer (org-element-at-point)))
  5398. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5399. (org-flag-drawer t drawer)
  5400. ;; Make sure to skip drawer entirely or we might flag
  5401. ;; it another time when matching its ending line with
  5402. ;; `org-drawer-regexp'.
  5403. (goto-char (org-element-property :end drawer))))))))))
  5404. (defun org-flag-drawer (flag &optional element beg end)
  5405. "When FLAG is non-nil, hide the drawer we are at.
  5406. Otherwise make it visible.
  5407. When optional argument ELEMENT is a parsed drawer, as returned by
  5408. `org-element-at-point', hide or show that drawer instead.
  5409. When buffer positions BEG and END are provided, hide or show that
  5410. region as a drawer without further ado."
  5411. (if (and beg end) (org-flag-region beg end flag 'org-hide-drawer)
  5412. (let ((drawer (or element
  5413. (and (save-excursion
  5414. (beginning-of-line)
  5415. (looking-at-p org-drawer-regexp))
  5416. (org-element-at-point)))))
  5417. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5418. (let ((post (org-element-property :post-affiliated drawer)))
  5419. (org-flag-region
  5420. (save-excursion (goto-char post) (line-end-position))
  5421. (save-excursion (goto-char (org-element-property :end drawer))
  5422. (skip-chars-backward " \t\n")
  5423. (line-end-position))
  5424. flag 'org-hide-drawer)
  5425. ;; When the drawer is hidden away, make sure point lies in
  5426. ;; a visible part of the buffer.
  5427. (when (invisible-p (max (1- (point)) (point-min)))
  5428. (goto-char post)))))))
  5429. ;;;; Visibility cycling
  5430. (defvar-local org-cycle-global-status nil)
  5431. (put 'org-cycle-global-status 'org-state t)
  5432. (defvar-local org-cycle-subtree-status nil)
  5433. (put 'org-cycle-subtree-status 'org-state t)
  5434. (defun org-show-all (&optional types)
  5435. "Show all contents in the visible part of the buffer.
  5436. By default, the function expands headings, blocks and drawers.
  5437. When optional argument TYPE is a list of symbols among `blocks',
  5438. `drawers' and `headings', to only expand one specific type."
  5439. (interactive)
  5440. (dolist (type (or types '(blocks drawers headings)))
  5441. (org-flag-region (point-min) (point-max) nil
  5442. (pcase type
  5443. (`blocks 'org-hide-block)
  5444. (`drawers 'org-hide-drawer)
  5445. (`headings 'outline)
  5446. (_ (error "Invalid type: %S" type))))))
  5447. ;;;###autoload
  5448. (defun org-cycle (&optional arg)
  5449. "TAB-action and visibility cycling for Org mode.
  5450. This is the command invoked in Org mode by the `TAB' key. Its main
  5451. purpose is outline visibility cycling, but it also invokes other actions
  5452. in special contexts.
  5453. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5454. the entire
  5455. buffer through 3 states (global cycling)
  5456. 1. OVERVIEW: Show only top-level headlines.
  5457. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5458. 3. SHOW ALL: Show everything.
  5459. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5460. switch to the startup visibility,
  5461. determined by the variable `org-startup-folded', and by any VISIBILITY
  5462. properties in the buffer.
  5463. With a `\\[universal-argument] \\[universal-argument] \
  5464. \\[universal-argument]' prefix argument, show the entire buffer, including
  5465. any drawers.
  5466. When inside a table, re-align the table and move to the next field.
  5467. When point is at the beginning of a headline, rotate the subtree started
  5468. by this line through 3 different states (local cycling)
  5469. 1. FOLDED: Only the main headline is shown.
  5470. 2. CHILDREN: The main headline and the direct children are shown.
  5471. From this state, you can move to one of the children
  5472. and zoom in further.
  5473. 3. SUBTREE: Show the entire subtree, including body text.
  5474. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5475. When point is at the beginning of an empty headline and the variable
  5476. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5477. of the headline by demoting and promoting it to likely levels. This
  5478. speeds up creation document structure by pressing `TAB' once or several
  5479. times right after creating a new headline.
  5480. When there is a numeric prefix, go up to a heading with level ARG, do
  5481. a `show-subtree' and return to the previous cursor position. If ARG
  5482. is negative, go up that many levels.
  5483. When point is not at the beginning of a headline, execute the global
  5484. binding for `TAB', which is re-indenting the line. See the option
  5485. `org-cycle-emulate-tab' for details.
  5486. As a special case, if point is at the beginning of the buffer and there is
  5487. no headline in line 1, this function will act as if called with prefix arg
  5488. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5489. prefix arg, but only
  5490. if the variable `org-cycle-global-at-bob' is t."
  5491. (interactive "P")
  5492. (org-load-modules-maybe)
  5493. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5494. (and org-cycle-level-after-item/entry-creation
  5495. (or (org-cycle-level)
  5496. (org-cycle-item-indentation))))
  5497. (let* ((limit-level
  5498. (or org-cycle-max-level
  5499. (and (boundp 'org-inlinetask-min-level)
  5500. org-inlinetask-min-level
  5501. (1- org-inlinetask-min-level))))
  5502. (nstars (and limit-level
  5503. (if org-odd-levels-only
  5504. (and limit-level (1- (* limit-level 2)))
  5505. limit-level)))
  5506. (org-outline-regexp
  5507. (if (not (derived-mode-p 'org-mode))
  5508. outline-regexp
  5509. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5510. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5511. (not (looking-at org-outline-regexp))))
  5512. (org-cycle-hook
  5513. (if bob-special
  5514. (delq 'org-optimize-window-after-visibility-change
  5515. (copy-sequence org-cycle-hook))
  5516. org-cycle-hook))
  5517. (pos (point)))
  5518. (cond
  5519. ((equal arg '(16))
  5520. (setq last-command 'dummy)
  5521. (org-set-startup-visibility)
  5522. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5523. ((equal arg '(64))
  5524. (org-show-all)
  5525. (org-unlogged-message "Entire buffer visible, including drawers"))
  5526. ((equal arg '(4)) (org-cycle-internal-global))
  5527. ;; Try hiding block at point.
  5528. ((org-hide-block-toggle-maybe))
  5529. ;; Try cdlatex TAB completion
  5530. ((org-try-cdlatex-tab))
  5531. ;; Table: enter it or move to the next field.
  5532. ((org-at-table-p 'any)
  5533. (if (org-at-table.el-p)
  5534. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5535. Use `\\[org-edit-special]' to edit table.el tables"))
  5536. (if arg (org-table-edit-field t)
  5537. (org-table-justify-field-maybe)
  5538. (call-interactively 'org-table-next-field))))
  5539. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5540. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5541. (bob-special (org-cycle-internal-global))
  5542. ;; Drawers: delegate to `org-flag-drawer'.
  5543. ((save-excursion
  5544. (beginning-of-line 1)
  5545. (looking-at org-drawer-regexp))
  5546. (org-flag-drawer ; toggle block visibility
  5547. (not (get-char-property (match-end 0) 'invisible))))
  5548. ;; Show-subtree, ARG levels up from here.
  5549. ((integerp arg)
  5550. (save-excursion
  5551. (org-back-to-heading)
  5552. (outline-up-heading (if (< arg 0) (- arg)
  5553. (- (funcall outline-level) arg)))
  5554. (org-show-subtree)))
  5555. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5556. ((and (featurep 'org-inlinetask)
  5557. (org-inlinetask-at-task-p)
  5558. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5559. (org-inlinetask-toggle-visibility))
  5560. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5561. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5562. (save-excursion (move-beginning-of-line 1)
  5563. (looking-at org-outline-regexp)))
  5564. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5565. (org-cycle-internal-local))
  5566. ;; From there: TAB emulation and template completion.
  5567. (buffer-read-only (org-back-to-heading))
  5568. ((run-hook-with-args-until-success
  5569. 'org-tab-after-check-for-cycling-hook))
  5570. ((run-hook-with-args-until-success
  5571. 'org-tab-before-tab-emulation-hook))
  5572. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5573. (or (not (bolp))
  5574. (not (looking-at org-outline-regexp))))
  5575. (call-interactively (global-key-binding "\t")))
  5576. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5577. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5578. (or (and (eq org-cycle-emulate-tab 'white)
  5579. (= (match-end 0) (point-at-eol)))
  5580. (and (eq org-cycle-emulate-tab 'whitestart)
  5581. (>= (match-end 0) pos))))
  5582. t
  5583. (eq org-cycle-emulate-tab t))
  5584. (call-interactively (global-key-binding "\t")))
  5585. (t (save-excursion
  5586. (org-back-to-heading)
  5587. (org-cycle)))))))
  5588. (defun org-cycle-internal-global ()
  5589. "Do the global cycling action."
  5590. ;; Hack to avoid display of messages for .org attachments in Gnus
  5591. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5592. (cond
  5593. ((and (eq last-command this-command)
  5594. (eq org-cycle-global-status 'overview))
  5595. ;; We just created the overview - now do table of contents
  5596. ;; This can be slow in very large buffers, so indicate action
  5597. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5598. (unless ga (org-unlogged-message "CONTENTS..."))
  5599. (org-content)
  5600. (unless ga (org-unlogged-message "CONTENTS...done"))
  5601. (setq org-cycle-global-status 'contents)
  5602. (run-hook-with-args 'org-cycle-hook 'contents))
  5603. ((and (eq last-command this-command)
  5604. (eq org-cycle-global-status 'contents))
  5605. ;; We just showed the table of contents - now show everything
  5606. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5607. (org-show-all '(headings blocks))
  5608. (unless ga (org-unlogged-message "SHOW ALL"))
  5609. (setq org-cycle-global-status 'all)
  5610. (run-hook-with-args 'org-cycle-hook 'all))
  5611. (t
  5612. ;; Default action: go to overview
  5613. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5614. (org-overview)
  5615. (unless ga (org-unlogged-message "OVERVIEW"))
  5616. (setq org-cycle-global-status 'overview)
  5617. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5618. (defvar org-called-with-limited-levels nil
  5619. "Non-nil when `org-with-limited-levels' is currently active.")
  5620. (defun org-cycle-internal-local ()
  5621. "Do the local cycling action."
  5622. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5623. ;; First, determine end of headline (EOH), end of subtree or item
  5624. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5625. (save-excursion
  5626. (if (org-at-item-p)
  5627. (progn
  5628. (beginning-of-line)
  5629. (setq struct (org-list-struct))
  5630. (setq eoh (point-at-eol))
  5631. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5632. (setq has-children (org-list-has-child-p (point) struct)))
  5633. (org-back-to-heading)
  5634. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5635. (setq eos (save-excursion (org-end-of-subtree t t)
  5636. (when (bolp) (backward-char)) (point)))
  5637. (setq has-children
  5638. (or
  5639. (save-excursion
  5640. (let ((level (funcall outline-level)))
  5641. (outline-next-heading)
  5642. (and (org-at-heading-p t)
  5643. (> (funcall outline-level) level))))
  5644. (and (eq org-cycle-include-plain-lists 'integrate)
  5645. (save-excursion
  5646. (org-list-search-forward (org-item-beginning-re) eos t))))))
  5647. ;; Determine end invisible part of buffer (EOL)
  5648. (beginning-of-line 2)
  5649. (while (and (not (eobp)) ;This is like `next-line'.
  5650. (get-char-property (1- (point)) 'invisible))
  5651. (goto-char (next-single-char-property-change (point) 'invisible))
  5652. (and (eolp) (beginning-of-line 2)))
  5653. (setq eol (point)))
  5654. ;; Find out what to do next and set `this-command'
  5655. (cond
  5656. ((= eos eoh)
  5657. ;; Nothing is hidden behind this heading
  5658. (unless (org-before-first-heading-p)
  5659. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5660. (org-unlogged-message "EMPTY ENTRY")
  5661. (setq org-cycle-subtree-status nil)
  5662. (save-excursion
  5663. (goto-char eos)
  5664. (outline-next-heading)
  5665. (when (org-invisible-p) (org-flag-heading nil))))
  5666. ((and (or (>= eol eos)
  5667. (not (string-match "\\S-" (buffer-substring eol eos))))
  5668. (or has-children
  5669. (not (setq children-skipped
  5670. org-cycle-skip-children-state-if-no-children))))
  5671. ;; Entire subtree is hidden in one line: children view
  5672. (unless (org-before-first-heading-p)
  5673. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5674. (if (org-at-item-p)
  5675. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5676. (org-show-entry)
  5677. (org-with-limited-levels (org-show-children))
  5678. (org-show-set-visibility 'canonical)
  5679. ;; Fold every list in subtree to top-level items.
  5680. (when (eq org-cycle-include-plain-lists 'integrate)
  5681. (save-excursion
  5682. (org-back-to-heading)
  5683. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5684. (beginning-of-line 1)
  5685. (let* ((struct (org-list-struct))
  5686. (prevs (org-list-prevs-alist struct))
  5687. (end (org-list-get-bottom-point struct)))
  5688. (dolist (e (org-list-get-all-items (point) struct prevs))
  5689. (org-list-set-item-visibility e struct 'folded))
  5690. (goto-char (if (< end eos) end eos)))))))
  5691. (org-unlogged-message "CHILDREN")
  5692. (save-excursion
  5693. (goto-char eos)
  5694. (outline-next-heading)
  5695. (when (org-invisible-p) (org-flag-heading nil)))
  5696. (setq org-cycle-subtree-status 'children)
  5697. (unless (org-before-first-heading-p)
  5698. (run-hook-with-args 'org-cycle-hook 'children)))
  5699. ((or children-skipped
  5700. (and (eq last-command this-command)
  5701. (eq org-cycle-subtree-status 'children)))
  5702. ;; We just showed the children, or no children are there,
  5703. ;; now show everything.
  5704. (unless (org-before-first-heading-p)
  5705. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5706. (org-flag-region eoh eos nil 'outline)
  5707. (org-unlogged-message
  5708. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5709. (setq org-cycle-subtree-status 'subtree)
  5710. (unless (org-before-first-heading-p)
  5711. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5712. (t
  5713. ;; Default action: hide the subtree.
  5714. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5715. (org-flag-region eoh eos t 'outline)
  5716. (org-unlogged-message "FOLDED")
  5717. (setq org-cycle-subtree-status 'folded)
  5718. (unless (org-before-first-heading-p)
  5719. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5720. ;;;###autoload
  5721. (defun org-global-cycle (&optional arg)
  5722. "Cycle the global visibility. For details see `org-cycle'.
  5723. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5724. With a numeric prefix, show all headlines up to that level."
  5725. (interactive "P")
  5726. (let ((org-cycle-include-plain-lists
  5727. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  5728. (cond
  5729. ((integerp arg)
  5730. (org-show-all '(headings blocks))
  5731. (outline-hide-sublevels arg)
  5732. (setq org-cycle-global-status 'contents))
  5733. ((equal arg '(4))
  5734. (org-set-startup-visibility)
  5735. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5736. (t
  5737. (org-cycle '(4))))))
  5738. (defun org-set-startup-visibility ()
  5739. "Set the visibility required by startup options and properties."
  5740. (cond
  5741. ((eq org-startup-folded t)
  5742. (org-overview))
  5743. ((eq org-startup-folded 'content)
  5744. (org-content))
  5745. ((or (eq org-startup-folded 'showeverything)
  5746. (eq org-startup-folded nil))
  5747. (org-show-all)))
  5748. (unless (eq org-startup-folded 'showeverything)
  5749. (when org-hide-block-startup (org-hide-block-all))
  5750. (org-set-visibility-according-to-property)
  5751. (org-cycle-hide-archived-subtrees 'all)
  5752. (org-cycle-hide-drawers 'all)
  5753. (org-cycle-show-empty-lines t)))
  5754. (defun org-set-visibility-according-to-property ()
  5755. "Switch subtree visibility according to VISIBILITY property."
  5756. (interactive)
  5757. (let ((regexp (org-re-property "VISIBILITY")))
  5758. (org-with-point-at 1
  5759. (while (re-search-forward regexp nil t)
  5760. (let ((state (match-string 3)))
  5761. (if (not (org-at-property-p)) (outline-next-heading)
  5762. (save-excursion
  5763. (org-back-to-heading t)
  5764. (org-flag-subtree t)
  5765. (org-reveal)
  5766. (pcase state
  5767. ("folded"
  5768. (org-flag-subtree t))
  5769. ("children"
  5770. (org-show-hidden-entry)
  5771. (org-show-children))
  5772. ("content"
  5773. (save-excursion
  5774. (save-restriction
  5775. (org-narrow-to-subtree)
  5776. (org-content))))
  5777. ((or "all" "showall")
  5778. (outline-show-subtree))
  5779. (_ nil)))
  5780. (org-end-of-subtree)))))))
  5781. (defun org-overview ()
  5782. "Switch to overview mode, showing only top-level headlines.
  5783. This shows all headlines with a level equal or greater than the level
  5784. of the first headline in the buffer. This is important, because if the
  5785. first headline is not level one, then (hide-sublevels 1) gives confusing
  5786. results."
  5787. (interactive)
  5788. (save-excursion
  5789. (let ((level
  5790. (save-excursion
  5791. (goto-char (point-min))
  5792. (when (re-search-forward org-outline-regexp-bol nil t)
  5793. (goto-char (match-beginning 0))
  5794. (funcall outline-level)))))
  5795. (and level (outline-hide-sublevels level)))))
  5796. (defun org-content (&optional arg)
  5797. "Show all headlines in the buffer, like a table of contents.
  5798. With numerical argument N, show content up to level N."
  5799. (interactive "P")
  5800. (org-overview)
  5801. (save-excursion
  5802. ;; Visit all headings and show their offspring
  5803. (and (integerp arg) (org-overview))
  5804. (goto-char (point-max))
  5805. (catch 'exit
  5806. (while (and (progn (condition-case nil
  5807. (outline-previous-visible-heading 1)
  5808. (error (goto-char (point-min))))
  5809. t)
  5810. (looking-at org-outline-regexp))
  5811. (if (integerp arg)
  5812. (org-show-children (1- arg))
  5813. (outline-show-branches))
  5814. (when (bobp) (throw 'exit nil))))))
  5815. (defun org-optimize-window-after-visibility-change (state)
  5816. "Adjust the window after a change in outline visibility.
  5817. This function is the default value of the hook `org-cycle-hook'."
  5818. (when (get-buffer-window (current-buffer))
  5819. (cond
  5820. ((eq state 'content) nil)
  5821. ((eq state 'all) nil)
  5822. ((eq state 'folded) nil)
  5823. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  5824. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  5825. (defun org-clean-visibility-after-subtree-move ()
  5826. "Fix visibility issues after moving a subtree."
  5827. ;; First, find a reasonable region to look at:
  5828. ;; Start two siblings above, end three below
  5829. (let* ((beg (save-excursion
  5830. (and (org-get-last-sibling)
  5831. (org-get-last-sibling))
  5832. (point)))
  5833. (end (save-excursion
  5834. (and (org-get-next-sibling)
  5835. (org-get-next-sibling)
  5836. (org-get-next-sibling))
  5837. (if (org-at-heading-p)
  5838. (point-at-eol)
  5839. (point))))
  5840. (level (looking-at "\\*+"))
  5841. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5842. (save-excursion
  5843. (save-restriction
  5844. (narrow-to-region beg end)
  5845. (when re
  5846. ;; Properly fold already folded siblings
  5847. (goto-char (point-min))
  5848. (while (re-search-forward re nil t)
  5849. (when (and (not (org-invisible-p))
  5850. (org-invisible-p (line-end-position)))
  5851. (outline-hide-entry))))
  5852. (org-cycle-hide-drawers 'all)
  5853. (org-cycle-show-empty-lines 'overview)))))
  5854. (defun org-cycle-show-empty-lines (state)
  5855. "Show empty lines above all visible headlines.
  5856. The region to be covered depends on STATE when called through
  5857. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5858. entire buffer covered. Note that an empty line is only shown if there
  5859. are at least `org-cycle-separator-lines' empty lines before the headline."
  5860. (when (/= org-cycle-separator-lines 0)
  5861. (save-excursion
  5862. (let* ((n (abs org-cycle-separator-lines))
  5863. (re (cond
  5864. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5865. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5866. (t (let ((ns (number-to-string (- n 2))))
  5867. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5868. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5869. beg end)
  5870. (cond
  5871. ((memq state '(overview contents t))
  5872. (setq beg (point-min) end (point-max)))
  5873. ((memq state '(children folded))
  5874. (setq beg (point)
  5875. end (progn (org-end-of-subtree t t)
  5876. (line-beginning-position 2)))))
  5877. (when beg
  5878. (goto-char beg)
  5879. (while (re-search-forward re end t)
  5880. (unless (get-char-property (match-end 1) 'invisible)
  5881. (let ((e (match-end 1))
  5882. (b (if (>= org-cycle-separator-lines 0)
  5883. (match-beginning 1)
  5884. (save-excursion
  5885. (goto-char (match-beginning 0))
  5886. (skip-chars-backward " \t\n")
  5887. (line-end-position)))))
  5888. (org-flag-region b e nil 'outline))))))))
  5889. ;; Never hide empty lines at the end of the file.
  5890. (save-excursion
  5891. (goto-char (point-max))
  5892. (outline-previous-heading)
  5893. (outline-end-of-heading)
  5894. (when (and (looking-at "[ \t\n]+")
  5895. (= (match-end 0) (point-max)))
  5896. (org-flag-region (point) (match-end 0) nil 'outline))))
  5897. ;;;; Reveal point location
  5898. (defun org-show-context (&optional key)
  5899. "Make sure point and context are visible.
  5900. Optional argument KEY, when non-nil, is a symbol. See
  5901. `org-show-context-detail' for allowed values and how much is to
  5902. be shown."
  5903. (org-show-set-visibility
  5904. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  5905. ((cdr (assq key org-show-context-detail)))
  5906. (t (cdr (assq 'default org-show-context-detail))))))
  5907. (defun org-show-set-visibility (detail)
  5908. "Set visibility around point according to DETAIL.
  5909. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  5910. `tree', `canonical' or t. See `org-show-context-detail' for more
  5911. information."
  5912. ;; Show current heading and possibly its entry, following headline
  5913. ;; or all children.
  5914. (if (and (org-at-heading-p) (not (eq detail 'local)))
  5915. (org-flag-heading nil)
  5916. (org-show-entry)
  5917. ;; If point is hidden within a drawer or a block, make sure to
  5918. ;; expose it.
  5919. (dolist (o (overlays-at (point)))
  5920. (when (memq (overlay-get o 'invisible)
  5921. '(org-hide-block org-hide-drawer outline))
  5922. (delete-overlay o)))
  5923. (unless (org-before-first-heading-p)
  5924. (org-with-limited-levels
  5925. (cl-case detail
  5926. ((tree canonical t) (org-show-children))
  5927. ((nil minimal ancestors))
  5928. (t (save-excursion
  5929. (outline-next-heading)
  5930. (org-flag-heading nil)))))))
  5931. ;; Show all siblings.
  5932. (when (eq detail 'lineage) (org-show-siblings))
  5933. ;; Show ancestors, possibly with their children.
  5934. (when (memq detail '(ancestors lineage tree canonical t))
  5935. (save-excursion
  5936. (while (org-up-heading-safe)
  5937. (org-flag-heading nil)
  5938. (when (memq detail '(canonical t)) (org-show-entry))
  5939. (when (memq detail '(tree canonical t)) (org-show-children))))))
  5940. (defvar org-reveal-start-hook nil
  5941. "Hook run before revealing a location.")
  5942. (defun org-reveal (&optional siblings)
  5943. "Show current entry, hierarchy above it, and the following headline.
  5944. This can be used to show a consistent set of context around
  5945. locations exposed with `org-show-context'.
  5946. With optional argument SIBLINGS, on each level of the hierarchy all
  5947. siblings are shown. This repairs the tree structure to what it would
  5948. look like when opened with hierarchical calls to `org-cycle'.
  5949. With a \\[universal-argument] \\[universal-argument] prefix, \
  5950. go to the parent and show the entire tree."
  5951. (interactive "P")
  5952. (run-hooks 'org-reveal-start-hook)
  5953. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  5954. ((equal siblings '(16))
  5955. (save-excursion
  5956. (when (org-up-heading-safe)
  5957. (org-show-subtree)
  5958. (run-hook-with-args 'org-cycle-hook 'subtree))))
  5959. (t (org-show-set-visibility 'lineage))))
  5960. ;;; Indirect buffer display of subtrees
  5961. (defvar org-indirect-dedicated-frame nil
  5962. "This is the frame being used for indirect tree display.")
  5963. (defvar org-last-indirect-buffer nil)
  5964. (defun org-tree-to-indirect-buffer (&optional arg)
  5965. "Create indirect buffer and narrow it to current subtree.
  5966. With a numerical prefix ARG, go up to this level and then take that tree.
  5967. If ARG is negative, go up that many levels.
  5968. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  5969. indirect buffer previously made with this command, to avoid proliferation of
  5970. indirect buffers. However, when you call the command with a \
  5971. `\\[universal-argument]' prefix, or
  5972. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  5973. so that you can work with several indirect buffers at the same time. If
  5974. `org-indirect-buffer-display' is `dedicated-frame', the \
  5975. `\\[universal-argument]' prefix also
  5976. requests that a new frame be made for the new buffer, so that the dedicated
  5977. frame is not changed."
  5978. (interactive "P")
  5979. (let ((cbuf (current-buffer))
  5980. (cwin (selected-window))
  5981. (pos (point))
  5982. beg end level heading ibuf)
  5983. (save-excursion
  5984. (org-back-to-heading t)
  5985. (when (numberp arg)
  5986. (setq level (org-outline-level))
  5987. (when (< arg 0) (setq arg (+ level arg)))
  5988. (while (> (setq level (org-outline-level)) arg)
  5989. (org-up-heading-safe)))
  5990. (setq beg (point)
  5991. heading (org-get-heading 'no-tags))
  5992. (org-end-of-subtree t t)
  5993. (when (org-at-heading-p) (backward-char 1))
  5994. (setq end (point)))
  5995. (when (and (buffer-live-p org-last-indirect-buffer)
  5996. (not (eq org-indirect-buffer-display 'new-frame))
  5997. (not arg))
  5998. (kill-buffer org-last-indirect-buffer))
  5999. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6000. org-last-indirect-buffer ibuf)
  6001. (cond
  6002. ((or (eq org-indirect-buffer-display 'new-frame)
  6003. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6004. (select-frame (make-frame))
  6005. (delete-other-windows)
  6006. (pop-to-buffer-same-window ibuf)
  6007. (org-set-frame-title heading))
  6008. ((eq org-indirect-buffer-display 'dedicated-frame)
  6009. (raise-frame
  6010. (select-frame (or (and org-indirect-dedicated-frame
  6011. (frame-live-p org-indirect-dedicated-frame)
  6012. org-indirect-dedicated-frame)
  6013. (setq org-indirect-dedicated-frame (make-frame)))))
  6014. (delete-other-windows)
  6015. (pop-to-buffer-same-window ibuf)
  6016. (org-set-frame-title (concat "Indirect: " heading)))
  6017. ((eq org-indirect-buffer-display 'current-window)
  6018. (pop-to-buffer-same-window ibuf))
  6019. ((eq org-indirect-buffer-display 'other-window)
  6020. (pop-to-buffer ibuf))
  6021. (t (error "Invalid value")))
  6022. (narrow-to-region beg end)
  6023. (org-show-all '(headings blocks))
  6024. (goto-char pos)
  6025. (run-hook-with-args 'org-cycle-hook 'all)
  6026. (and (window-live-p cwin) (select-window cwin))))
  6027. (defun org-get-indirect-buffer (&optional buffer heading)
  6028. (setq buffer (or buffer (current-buffer)))
  6029. (let ((n 1) (base (buffer-name buffer)) bname)
  6030. (while (buffer-live-p
  6031. (get-buffer
  6032. (setq bname
  6033. (concat base "-"
  6034. (if heading (concat heading "-" (number-to-string n))
  6035. (number-to-string n))))))
  6036. (setq n (1+ n)))
  6037. (condition-case nil
  6038. (make-indirect-buffer buffer bname 'clone)
  6039. (error (make-indirect-buffer buffer bname)))))
  6040. (defun org-set-frame-title (title)
  6041. "Set the title of the current frame to the string TITLE."
  6042. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6043. ;;;; Structure editing
  6044. ;;; Inserting headlines
  6045. (defun org--line-empty-p (n)
  6046. "Is the Nth next line empty?
  6047. Counts the current line as N = 1 and the previous line as N = 0;
  6048. see `beginning-of-line'."
  6049. (save-excursion
  6050. (and (not (bobp))
  6051. (or (beginning-of-line n) t)
  6052. (save-match-data
  6053. (looking-at "[ \t]*$")))))
  6054. (defun org-previous-line-empty-p ()
  6055. "Is the previous line a blank line?
  6056. When NEXT is non-nil, check the next line instead."
  6057. (org--line-empty-p 0))
  6058. (defun org-next-line-empty-p ()
  6059. "Is the previous line a blank line?
  6060. When NEXT is non-nil, check the next line instead."
  6061. (org--line-empty-p 2))
  6062. (defun org--blank-before-heading-p (&optional parent)
  6063. "Non-nil when an empty line should precede a new heading here.
  6064. When optional argument PARENT is non-nil, consider parent
  6065. headline instead of current one."
  6066. (pcase (assq 'heading org-blank-before-new-entry)
  6067. (`(heading . auto)
  6068. (save-excursion
  6069. (org-with-limited-levels
  6070. (unless (and (org-before-first-heading-p)
  6071. (not (outline-next-heading)))
  6072. (org-back-to-heading t)
  6073. (when parent (org-up-heading-safe))
  6074. (cond ((not (bobp))
  6075. (org-previous-line-empty-p))
  6076. ((outline-next-heading)
  6077. (org-previous-line-empty-p))
  6078. ;; Ignore trailing spaces on last buffer line.
  6079. ((progn (skip-chars-backward " \t") (bolp))
  6080. (org-previous-line-empty-p))
  6081. (t nil))))))
  6082. (`(heading . ,value) value)
  6083. (_ nil)))
  6084. (defun org-insert-heading (&optional arg invisible-ok top)
  6085. "Insert a new heading or an item with the same depth at point.
  6086. If point is at the beginning of a heading, insert a new heading
  6087. or a new headline above the current one. When at the beginning
  6088. of a regular line of text, turn it into a heading.
  6089. If point is in the middle of a line, split it and create a new
  6090. headline with the text in the current line after point (see
  6091. `org-M-RET-may-split-line' on how to modify this behavior). As
  6092. a special case, on a headline, splitting can only happen on the
  6093. title itself. E.g., this excludes breaking stars or tags.
  6094. With a `\\[universal-argument]' prefix, set \
  6095. `org-insert-heading-respect-content' to
  6096. a non-nil value for the duration of the command. This forces the
  6097. insertion of a heading after the current subtree, independently
  6098. on the location of point.
  6099. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6100. insert the heading at the end of the tree
  6101. above the current heading. For example, if point is within a
  6102. 2nd-level heading, then it will insert a 2nd-level heading at
  6103. the end of the 1st-level parent subtree.
  6104. When INVISIBLE-OK is set, stop at invisible headlines when going
  6105. back. This is important for non-interactive uses of the
  6106. command.
  6107. When optional argument TOP is non-nil, insert a level 1 heading,
  6108. unconditionally."
  6109. (interactive "P")
  6110. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6111. (level (org-current-level))
  6112. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6113. (cond
  6114. ((or org-insert-heading-respect-content
  6115. (member arg '((4) (16)))
  6116. (and (not invisible-ok)
  6117. (invisible-p (max (1- (point)) (point-min)))))
  6118. ;; Position point at the location of insertion. Make sure we
  6119. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6120. (org-with-limited-levels
  6121. (if (not level) (outline-next-heading) ;before first headline
  6122. (org-back-to-heading invisible-ok)
  6123. (when (equal arg '(16)) (org-up-heading-safe))
  6124. (org-end-of-subtree)))
  6125. (unless (bolp) (insert "\n"))
  6126. (unless (and blank? (org-previous-line-empty-p))
  6127. (org-N-empty-lines-before-current (if blank? 1 0)))
  6128. (insert stars " ")
  6129. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6130. ;; is visible.
  6131. (unless invisible-ok
  6132. (pcase (get-char-property-and-overlay (point) 'invisible)
  6133. (`(outline . ,o)
  6134. (move-overlay o (overlay-start o) (line-end-position 0)))
  6135. (_ nil))))
  6136. ;; At a headline...
  6137. ((org-at-heading-p)
  6138. (cond ((bolp)
  6139. (when blank? (save-excursion (insert "\n")))
  6140. (save-excursion (insert stars " \n"))
  6141. (unless (and blank? (org-previous-line-empty-p))
  6142. (org-N-empty-lines-before-current (if blank? 1 0)))
  6143. (end-of-line))
  6144. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6145. (org-match-line org-complex-heading-regexp)
  6146. (org-pos-in-match-range (point) 4))
  6147. ;; Grab the text that should moved to the new headline.
  6148. ;; Preserve tags.
  6149. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6150. (if (looking-at "[ \t]*$") (replace-match "")
  6151. (org-align-tags))
  6152. (end-of-line)
  6153. (when blank? (insert "\n"))
  6154. (insert "\n" stars " ")
  6155. (when (org-string-nw-p split) (insert split))))
  6156. (t
  6157. (end-of-line)
  6158. (when blank? (insert "\n"))
  6159. (insert "\n" stars " "))))
  6160. ;; On regular text, turn line into a headline or split, if
  6161. ;; appropriate.
  6162. ((bolp)
  6163. (insert stars " ")
  6164. (unless (and blank? (org-previous-line-empty-p))
  6165. (org-N-empty-lines-before-current (if blank? 1 0))))
  6166. (t
  6167. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6168. (end-of-line))
  6169. (insert "\n" stars " ")
  6170. (unless (and blank? (org-previous-line-empty-p))
  6171. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6172. (run-hooks 'org-insert-heading-hook))
  6173. (defun org-N-empty-lines-before-current (n)
  6174. "Make the number of empty lines before current exactly N.
  6175. So this will delete or add empty lines."
  6176. (let ((column (current-column)))
  6177. (beginning-of-line)
  6178. (unless (bobp)
  6179. (let ((start (save-excursion
  6180. (skip-chars-backward " \r\t\n")
  6181. (line-end-position))))
  6182. (delete-region start (line-end-position 0))))
  6183. (insert (make-string n ?\n))
  6184. (move-to-column column)))
  6185. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6186. "Return the heading of the current entry, without the stars.
  6187. When NO-TAGS is non-nil, don't include tags.
  6188. When NO-TODO is non-nil, don't include TODO keywords.
  6189. When NO-PRIORITY is non-nil, don't include priority cookie.
  6190. When NO-COMMENT is non-nil, don't include COMMENT string.
  6191. Return nil before first heading."
  6192. (unless (org-before-first-heading-p)
  6193. (save-excursion
  6194. (org-back-to-heading t)
  6195. (let ((case-fold-search nil))
  6196. (looking-at org-complex-heading-regexp)
  6197. (let ((todo (and (not no-todo) (match-string 2)))
  6198. (priority (and (not no-priority) (match-string 3)))
  6199. (headline (pcase (match-string 4)
  6200. (`nil "")
  6201. ((and (guard no-comment) h)
  6202. (replace-regexp-in-string
  6203. (eval-when-compile
  6204. (format "\\`%s[ \t]+" org-comment-string))
  6205. "" h))
  6206. (h h)))
  6207. (tags (and (not no-tags) (match-string 5))))
  6208. (mapconcat #'identity
  6209. (delq nil (list todo priority headline tags))
  6210. " "))))))
  6211. (defun org-heading-components ()
  6212. "Return the components of the current heading.
  6213. This is a list with the following elements:
  6214. - the level as an integer
  6215. - the reduced level, different if `org-odd-levels-only' is set.
  6216. - the TODO keyword, or nil
  6217. - the priority character, like ?A, or nil if no priority is given
  6218. - the headline text itself, or the tags string if no headline text
  6219. - the tags string, or nil."
  6220. (save-excursion
  6221. (org-back-to-heading t)
  6222. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6223. (list (length (match-string 1))
  6224. (org-reduced-level (length (match-string 1)))
  6225. (match-string-no-properties 2)
  6226. (and (match-end 3) (aref (match-string 3) 2))
  6227. (match-string-no-properties 4)
  6228. (match-string-no-properties 5)))))
  6229. (defun org-get-entry ()
  6230. "Get the entry text, after heading, entire subtree."
  6231. (save-excursion
  6232. (org-back-to-heading t)
  6233. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6234. (defun org-edit-headline (&optional heading)
  6235. "Edit the current headline.
  6236. Set it to HEADING when provided."
  6237. (interactive)
  6238. (org-with-wide-buffer
  6239. (org-back-to-heading t)
  6240. (let ((case-fold-search nil))
  6241. (when (looking-at org-complex-heading-regexp)
  6242. (let* ((old (match-string-no-properties 4))
  6243. (new (save-match-data
  6244. (org-trim (or heading (read-string "Edit: " old))))))
  6245. (unless (equal old new)
  6246. (if old (replace-match new t t nil 4)
  6247. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6248. (insert " " new))
  6249. (org-align-tags)
  6250. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6251. (defun org-insert-heading-after-current ()
  6252. "Insert a new heading with same level as current, after current subtree."
  6253. (interactive)
  6254. (org-back-to-heading)
  6255. (org-insert-heading)
  6256. (org-move-subtree-down)
  6257. (end-of-line 1))
  6258. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6259. "Insert heading with `org-insert-heading-respect-content' set to t."
  6260. (interactive)
  6261. (org-insert-heading '(4) invisible-ok))
  6262. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6263. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6264. (interactive)
  6265. (org-insert-todo-heading force-state '(4)))
  6266. (defun org-insert-todo-heading (arg &optional force-heading)
  6267. "Insert a new heading with the same level and TODO state as current heading.
  6268. If the heading has no TODO state, or if the state is DONE, use
  6269. the first state (TODO by default). Also with one prefix arg,
  6270. force first state. With two prefix args, force inserting at the
  6271. end of the parent subtree.
  6272. When called at a plain list item, insert a new item with an
  6273. unchecked check box."
  6274. (interactive "P")
  6275. (when (or force-heading (not (org-insert-item 'checkbox)))
  6276. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6277. force-heading))
  6278. (save-excursion
  6279. (org-forward-heading-same-level -1)
  6280. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6281. (let* ((new-mark-x
  6282. (if (or (equal arg '(4))
  6283. (not (match-beginning 2))
  6284. (member (match-string 2) org-done-keywords))
  6285. (car org-todo-keywords-1)
  6286. (match-string 2)))
  6287. (new-mark
  6288. (or
  6289. (run-hook-with-args-until-success
  6290. 'org-todo-get-default-hook new-mark-x nil)
  6291. new-mark-x)))
  6292. (beginning-of-line 1)
  6293. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6294. (if org-treat-insert-todo-heading-as-state-change
  6295. (org-todo new-mark)
  6296. (insert new-mark " "))))
  6297. (when org-provide-todo-statistics
  6298. (org-update-parent-todo-statistics))))
  6299. (defun org-insert-subheading (arg)
  6300. "Insert a new subheading and demote it.
  6301. Works for outline headings and for plain lists alike."
  6302. (interactive "P")
  6303. (org-insert-heading arg)
  6304. (cond
  6305. ((org-at-heading-p) (org-do-demote))
  6306. ((org-at-item-p) (org-indent-item))))
  6307. (defun org-insert-todo-subheading (arg)
  6308. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6309. Works for outline headings and for plain lists alike."
  6310. (interactive "P")
  6311. (org-insert-todo-heading arg)
  6312. (cond
  6313. ((org-at-heading-p) (org-do-demote))
  6314. ((org-at-item-p) (org-indent-item))))
  6315. ;;; Promotion and Demotion
  6316. (defvar org-after-demote-entry-hook nil
  6317. "Hook run after an entry has been demoted.
  6318. The cursor will be at the beginning of the entry.
  6319. When a subtree is being demoted, the hook will be called for each node.")
  6320. (defvar org-after-promote-entry-hook nil
  6321. "Hook run after an entry has been promoted.
  6322. The cursor will be at the beginning of the entry.
  6323. When a subtree is being promoted, the hook will be called for each node.")
  6324. (defun org-promote-subtree ()
  6325. "Promote the entire subtree.
  6326. See also `org-promote'."
  6327. (interactive)
  6328. (save-excursion
  6329. (org-with-limited-levels (org-map-tree 'org-promote)))
  6330. (org-fix-position-after-promote))
  6331. (defun org-demote-subtree ()
  6332. "Demote the entire subtree.
  6333. See `org-demote' and `org-promote'."
  6334. (interactive)
  6335. (save-excursion
  6336. (org-with-limited-levels (org-map-tree 'org-demote)))
  6337. (org-fix-position-after-promote))
  6338. (defun org-do-promote ()
  6339. "Promote the current heading higher up the tree.
  6340. If the region is active in `transient-mark-mode', promote all
  6341. headings in the region."
  6342. (interactive)
  6343. (save-excursion
  6344. (if (org-region-active-p)
  6345. (org-map-region 'org-promote (region-beginning) (region-end))
  6346. (org-promote)))
  6347. (org-fix-position-after-promote))
  6348. (defun org-do-demote ()
  6349. "Demote the current heading lower down the tree.
  6350. If the region is active in `transient-mark-mode', demote all
  6351. headings in the region."
  6352. (interactive)
  6353. (save-excursion
  6354. (if (org-region-active-p)
  6355. (org-map-region 'org-demote (region-beginning) (region-end))
  6356. (org-demote)))
  6357. (org-fix-position-after-promote))
  6358. (defun org-fix-position-after-promote ()
  6359. "Fix cursor position and indentation after demoting/promoting."
  6360. (let ((pos (point)))
  6361. (when (save-excursion
  6362. (beginning-of-line)
  6363. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6364. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6365. (cond ((eobp) (insert " "))
  6366. ((eolp) (insert " "))
  6367. ((equal (char-after) ?\s) (forward-char 1))))))
  6368. (defun org-current-level ()
  6369. "Return the level of the current entry, or nil if before the first headline.
  6370. The level is the number of stars at the beginning of the
  6371. headline. Use `org-reduced-level' to remove the effect of
  6372. `org-odd-levels'. Unlike to `org-outline-level', this function
  6373. ignores inlinetasks."
  6374. (let ((level (org-with-limited-levels (org-outline-level))))
  6375. (and (> level 0) level)))
  6376. (defun org-get-previous-line-level ()
  6377. "Return the outline depth of the last headline before the current line.
  6378. Returns 0 for the first headline in the buffer, and nil if before the
  6379. first headline."
  6380. (and (org-current-level)
  6381. (or (and (/= (line-beginning-position) (point-min))
  6382. (save-excursion (beginning-of-line 0) (org-current-level)))
  6383. 0)))
  6384. (defun org-reduced-level (l)
  6385. "Compute the effective level of a heading.
  6386. This takes into account the setting of `org-odd-levels-only'."
  6387. (cond
  6388. ((zerop l) 0)
  6389. (org-odd-levels-only (1+ (floor (/ l 2))))
  6390. (t l)))
  6391. (defun org-level-increment ()
  6392. "Return the number of stars that will be added or removed at a
  6393. time to headlines when structure editing, based on the value of
  6394. `org-odd-levels-only'."
  6395. (if org-odd-levels-only 2 1))
  6396. (defun org-get-valid-level (level &optional change)
  6397. "Rectify a level change under the influence of `org-odd-levels-only'.
  6398. LEVEL is a current level, CHANGE is by how much the level should
  6399. be modified. Even if CHANGE is nil, LEVEL may be returned
  6400. modified because even level numbers will become the next higher
  6401. odd number. Returns values greater than 0."
  6402. (if org-odd-levels-only
  6403. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6404. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6405. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6406. (max 1 (+ level (or change 0)))))
  6407. (defun org-promote ()
  6408. "Promote the current heading higher up the tree."
  6409. (org-with-wide-buffer
  6410. (org-back-to-heading t)
  6411. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6412. after-change-functions))
  6413. (level (save-match-data (funcall outline-level)))
  6414. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6415. (diff (abs (- level (length up-head) -1))))
  6416. (cond
  6417. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6418. (replace-match "# " nil t))
  6419. ((= level 1)
  6420. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6421. (t (replace-match up-head nil t)))
  6422. (unless (= level 1)
  6423. (when org-auto-align-tags (org-align-tags))
  6424. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6425. (run-hooks 'org-after-promote-entry-hook))))
  6426. (defun org-demote ()
  6427. "Demote the current heading lower down the tree."
  6428. (org-with-wide-buffer
  6429. (org-back-to-heading t)
  6430. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6431. after-change-functions))
  6432. (level (save-match-data (funcall outline-level)))
  6433. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6434. (diff (abs (- level (length down-head) -1))))
  6435. (replace-match down-head nil t)
  6436. (when org-auto-align-tags (org-align-tags))
  6437. (when org-adapt-indentation (org-fixup-indentation diff))
  6438. (run-hooks 'org-after-demote-entry-hook))))
  6439. (defun org-cycle-level ()
  6440. "Cycle the level of an empty headline through possible states.
  6441. This goes first to child, then to parent, level, then up the hierarchy.
  6442. After top level, it switches back to sibling level."
  6443. (interactive)
  6444. (let ((org-adapt-indentation nil))
  6445. (when (org-point-at-end-of-empty-headline)
  6446. (setq this-command 'org-cycle-level) ; Only needed for caching
  6447. (let ((cur-level (org-current-level))
  6448. (prev-level (org-get-previous-line-level)))
  6449. (cond
  6450. ;; If first headline in file, promote to top-level.
  6451. ((= prev-level 0)
  6452. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6453. do (org-do-promote)))
  6454. ;; If same level as prev, demote one.
  6455. ((= prev-level cur-level)
  6456. (org-do-demote))
  6457. ;; If parent is top-level, promote to top level if not already.
  6458. ((= prev-level 1)
  6459. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6460. do (org-do-promote)))
  6461. ;; If top-level, return to prev-level.
  6462. ((= cur-level 1)
  6463. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6464. do (org-do-demote)))
  6465. ;; If less than prev-level, promote one.
  6466. ((< cur-level prev-level)
  6467. (org-do-promote))
  6468. ;; If deeper than prev-level, promote until higher than
  6469. ;; prev-level.
  6470. ((> cur-level prev-level)
  6471. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6472. do (org-do-promote))))
  6473. t))))
  6474. (defun org-map-tree (fun)
  6475. "Call FUN for every heading underneath the current one."
  6476. (org-back-to-heading t)
  6477. (let ((level (funcall outline-level)))
  6478. (save-excursion
  6479. (funcall fun)
  6480. (while (and (progn
  6481. (outline-next-heading)
  6482. (> (funcall outline-level) level))
  6483. (not (eobp)))
  6484. (funcall fun)))))
  6485. (defun org-map-region (fun beg end)
  6486. "Call FUN for every heading between BEG and END."
  6487. (let ((org-ignore-region t))
  6488. (save-excursion
  6489. (setq end (copy-marker end))
  6490. (goto-char beg)
  6491. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6492. (< (point) end))
  6493. (funcall fun))
  6494. (while (and (progn
  6495. (outline-next-heading)
  6496. (< (point) end))
  6497. (not (eobp)))
  6498. (funcall fun)))))
  6499. (defun org-fixup-indentation (diff)
  6500. "Change the indentation in the current entry by DIFF.
  6501. DIFF is an integer. Indentation is done according to the
  6502. following rules:
  6503. - Planning information and property drawers are always indented
  6504. according to the new level of the headline;
  6505. - Footnote definitions and their contents are ignored;
  6506. - Inlinetasks' boundaries are not shifted;
  6507. - Empty lines are ignored;
  6508. - Other lines' indentation are shifted by DIFF columns, unless
  6509. it would introduce a structural change in the document, in
  6510. which case no shifting is done at all.
  6511. Assume point is at a heading or an inlinetask beginning."
  6512. (org-with-wide-buffer
  6513. (narrow-to-region (line-beginning-position)
  6514. (save-excursion
  6515. (if (org-with-limited-levels (org-at-heading-p))
  6516. (org-with-limited-levels (outline-next-heading))
  6517. (org-inlinetask-goto-end))
  6518. (point)))
  6519. (forward-line)
  6520. ;; Indent properly planning info and property drawer.
  6521. (when (looking-at-p org-planning-line-re)
  6522. (org-indent-line)
  6523. (forward-line))
  6524. (when (looking-at org-property-drawer-re)
  6525. (goto-char (match-end 0))
  6526. (forward-line)
  6527. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  6528. (catch 'no-shift
  6529. (when (zerop diff) (throw 'no-shift nil))
  6530. ;; If DIFF is negative, first check if a shift is possible at all
  6531. ;; (e.g., it doesn't break structure). This can only happen if
  6532. ;; some contents are not properly indented.
  6533. (let ((case-fold-search t))
  6534. (when (< diff 0)
  6535. (let ((diff (- diff))
  6536. (forbidden-re (concat org-outline-regexp
  6537. "\\|"
  6538. (substring org-footnote-definition-re 1))))
  6539. (save-excursion
  6540. (while (not (eobp))
  6541. (cond
  6542. ((looking-at-p "[ \t]*$") (forward-line))
  6543. ((and (looking-at-p org-footnote-definition-re)
  6544. (let ((e (org-element-at-point)))
  6545. (and (eq (org-element-type e) 'footnote-definition)
  6546. (goto-char (org-element-property :end e))))))
  6547. ((looking-at-p org-outline-regexp) (forward-line))
  6548. ;; Give up if shifting would move before column 0 or
  6549. ;; if it would introduce a headline or a footnote
  6550. ;; definition.
  6551. (t
  6552. (skip-chars-forward " \t")
  6553. (let ((ind (current-column)))
  6554. (when (or (< ind diff)
  6555. (and (= ind diff) (looking-at-p forbidden-re)))
  6556. (throw 'no-shift nil)))
  6557. ;; Ignore contents of example blocks and source
  6558. ;; blocks if their indentation is meant to be
  6559. ;; preserved. Jump to block's closing line.
  6560. (beginning-of-line)
  6561. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6562. (let ((e (org-element-at-point)))
  6563. (and (memq (org-element-type e)
  6564. '(example-block src-block))
  6565. (or org-src-preserve-indentation
  6566. (org-element-property :preserve-indent e))
  6567. (goto-char (org-element-property :end e))
  6568. (progn (skip-chars-backward " \r\t\n")
  6569. (beginning-of-line)
  6570. t))))
  6571. (forward-line))))))))
  6572. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6573. ;; by DIFF. Also skip contents of source or example blocks
  6574. ;; when indentation is meant to be preserved.
  6575. (while (not (eobp))
  6576. (cond
  6577. ((and (looking-at-p org-footnote-definition-re)
  6578. (let ((e (org-element-at-point)))
  6579. (and (eq (org-element-type e) 'footnote-definition)
  6580. (goto-char (org-element-property :end e))))))
  6581. ((looking-at-p org-outline-regexp) (forward-line))
  6582. ((looking-at-p "[ \t]*$") (forward-line))
  6583. (t
  6584. (indent-line-to (+ (current-indentation) diff))
  6585. (beginning-of-line)
  6586. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6587. (let ((e (org-element-at-point)))
  6588. (and (memq (org-element-type e)
  6589. '(example-block src-block))
  6590. (or org-src-preserve-indentation
  6591. (org-element-property :preserve-indent e))
  6592. (goto-char (org-element-property :end e))
  6593. (progn (skip-chars-backward " \r\t\n")
  6594. (beginning-of-line)
  6595. t))))
  6596. (forward-line)))))))))
  6597. (defun org-convert-to-odd-levels ()
  6598. "Convert an Org file with all levels allowed to one with odd levels.
  6599. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6600. level 5 etc."
  6601. (interactive)
  6602. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6603. (let ((outline-level 'org-outline-level)
  6604. (org-odd-levels-only nil) n)
  6605. (save-excursion
  6606. (goto-char (point-min))
  6607. (while (re-search-forward "^\\*\\*+ " nil t)
  6608. (setq n (- (length (match-string 0)) 2))
  6609. (while (>= (setq n (1- n)) 0)
  6610. (org-demote))
  6611. (end-of-line 1))))))
  6612. (defun org-convert-to-oddeven-levels ()
  6613. "Convert an Org file with only odd levels to one with odd/even levels.
  6614. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6615. file contains a section with an even level, conversion would
  6616. destroy the structure of the file. An error is signaled in this
  6617. case."
  6618. (interactive)
  6619. (goto-char (point-min))
  6620. ;; First check if there are no even levels
  6621. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6622. (org-show-set-visibility 'canonical)
  6623. (error "Not all levels are odd in this file. Conversion not possible"))
  6624. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6625. (let ((outline-regexp org-outline-regexp)
  6626. (outline-level 'org-outline-level)
  6627. (org-odd-levels-only nil) n)
  6628. (save-excursion
  6629. (goto-char (point-min))
  6630. (while (re-search-forward "^\\*\\*+ " nil t)
  6631. (setq n (/ (1- (length (match-string 0))) 2))
  6632. (while (>= (setq n (1- n)) 0)
  6633. (org-promote))
  6634. (end-of-line 1))))))
  6635. (defun org-tr-level (n)
  6636. "Make N odd if required."
  6637. (if org-odd-levels-only (1+ (/ n 2)) n))
  6638. ;;; Vertical tree motion, cutting and pasting of subtrees
  6639. (defun org-move-subtree-up (&optional arg)
  6640. "Move the current subtree up past ARG headlines of the same level."
  6641. (interactive "p")
  6642. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6643. (defun org-move-subtree-down (&optional arg)
  6644. "Move the current subtree down past ARG headlines of the same level."
  6645. (interactive "p")
  6646. (setq arg (prefix-numeric-value arg))
  6647. (org-preserve-local-variables
  6648. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6649. 'org-get-last-sibling))
  6650. (ins-point (make-marker))
  6651. (cnt (abs arg))
  6652. (col (current-column))
  6653. beg end txt folded)
  6654. ;; Select the tree
  6655. (org-back-to-heading)
  6656. (setq beg (point))
  6657. (save-match-data
  6658. (save-excursion (outline-end-of-heading)
  6659. (setq folded (org-invisible-p)))
  6660. (progn (org-end-of-subtree nil t)
  6661. (unless (eobp) (backward-char))))
  6662. (outline-next-heading)
  6663. (setq end (point))
  6664. (goto-char beg)
  6665. ;; Find insertion point, with error handling
  6666. (while (> cnt 0)
  6667. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6668. (goto-char beg)
  6669. (user-error "Cannot move past superior level or buffer limit"))
  6670. (setq cnt (1- cnt)))
  6671. (when (> arg 0)
  6672. ;; Moving forward - still need to move over subtree
  6673. (org-end-of-subtree t t)
  6674. (save-excursion
  6675. (org-back-over-empty-lines)
  6676. (or (bolp) (newline))))
  6677. (move-marker ins-point (point))
  6678. (setq txt (buffer-substring beg end))
  6679. (org-save-markers-in-region beg end)
  6680. (delete-region beg end)
  6681. (org-remove-empty-overlays-at beg)
  6682. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6683. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6684. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6685. (let ((bbb (point)))
  6686. (insert-before-markers txt)
  6687. (org-reinstall-markers-in-region bbb)
  6688. (move-marker ins-point bbb))
  6689. (or (bolp) (insert "\n"))
  6690. (goto-char ins-point)
  6691. (org-skip-whitespace)
  6692. (move-marker ins-point nil)
  6693. (if folded
  6694. (org-flag-subtree t)
  6695. (org-show-entry)
  6696. (org-show-children))
  6697. (org-clean-visibility-after-subtree-move)
  6698. ;; move back to the initial column we were at
  6699. (move-to-column col))))
  6700. (defvar org-subtree-clip ""
  6701. "Clipboard for cut and paste of subtrees.
  6702. This is actually only a copy of the kill, because we use the normal kill
  6703. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6704. (defvar org-subtree-clip-folded nil
  6705. "Was the last copied subtree folded?
  6706. This is used to fold the tree back after pasting.")
  6707. (defun org-cut-subtree (&optional n)
  6708. "Cut the current subtree into the clipboard.
  6709. With prefix arg N, cut this many sequential subtrees.
  6710. This is a short-hand for marking the subtree and then cutting it."
  6711. (interactive "p")
  6712. (org-copy-subtree n 'cut))
  6713. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6714. "Copy the current subtree into the clipboard.
  6715. With prefix arg N, copy this many sequential subtrees.
  6716. This is a short-hand for marking the subtree and then copying it.
  6717. If CUT is non-nil, actually cut the subtree.
  6718. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6719. of some markers in the region, even if CUT is non-nil. This is
  6720. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6721. (interactive "p")
  6722. (org-preserve-local-variables
  6723. (let (beg end folded (beg0 (point)))
  6724. (if (called-interactively-p 'any)
  6725. (org-back-to-heading nil) ; take what looks like a subtree
  6726. (org-back-to-heading t)) ; take what is really there
  6727. (setq beg (point))
  6728. (skip-chars-forward " \t\r\n")
  6729. (save-match-data
  6730. (if nosubtrees
  6731. (outline-next-heading)
  6732. (save-excursion (outline-end-of-heading)
  6733. (setq folded (org-invisible-p)))
  6734. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6735. (org-end-of-subtree t t)))
  6736. ;; Include the end of an inlinetask
  6737. (when (and (featurep 'org-inlinetask)
  6738. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6739. "END[ \t]*$")))
  6740. (end-of-line))
  6741. (setq end (point))
  6742. (goto-char beg0)
  6743. (when (> end beg)
  6744. (setq org-subtree-clip-folded folded)
  6745. (when (or cut force-store-markers)
  6746. (org-save-markers-in-region beg end))
  6747. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6748. (setq org-subtree-clip (current-kill 0))
  6749. (message "%s: Subtree(s) with %d characters"
  6750. (if cut "Cut" "Copied")
  6751. (length org-subtree-clip))))))
  6752. (defun org-paste-subtree (&optional level tree for-yank remove)
  6753. "Paste the clipboard as a subtree, with modification of headline level.
  6754. The entire subtree is promoted or demoted in order to match a new headline
  6755. level.
  6756. If the cursor is at the beginning of a headline, the same level as
  6757. that headline is used to paste the tree.
  6758. If not, the new level is derived from the *visible* headings
  6759. before and after the insertion point, and taken to be the inferior headline
  6760. level of the two. So if the previous visible heading is level 3 and the
  6761. next is level 4 (or vice versa), level 4 will be used for insertion.
  6762. This makes sure that the subtree remains an independent subtree and does
  6763. not swallow low level entries.
  6764. You can also force a different level, either by using a numeric prefix
  6765. argument, or by inserting the heading marker by hand. For example, if the
  6766. cursor is after \"*****\", then the tree will be shifted to level 5.
  6767. If optional TREE is given, use this text instead of the kill ring.
  6768. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6769. move back over whitespace before inserting, and move point to the end of
  6770. the inserted text when done.
  6771. When REMOVE is non-nil, remove the subtree from the clipboard."
  6772. (interactive "P")
  6773. (setq tree (or tree (and kill-ring (current-kill 0))))
  6774. (unless (org-kill-is-subtree-p tree)
  6775. (user-error
  6776. (substitute-command-keys
  6777. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6778. (org-with-limited-levels
  6779. (let* ((visp (not (org-invisible-p)))
  6780. (txt tree)
  6781. (old-level (if (string-match org-outline-regexp-bol txt)
  6782. (- (match-end 0) (match-beginning 0) 1)
  6783. -1))
  6784. (force-level
  6785. (cond
  6786. (level (prefix-numeric-value level))
  6787. ;; When point is after the stars in an otherwise empty
  6788. ;; headline, use the number of stars as the forced level.
  6789. ((and (org-match-line "^\\*+[ \t]*$")
  6790. (not (eq ?* (char-after))))
  6791. (org-outline-level))
  6792. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6793. (previous-level
  6794. (save-excursion
  6795. (org-previous-visible-heading 1)
  6796. (if (org-at-heading-p) (org-outline-level) 1)))
  6797. (next-level
  6798. (save-excursion
  6799. (if (org-at-heading-p) (org-outline-level)
  6800. (org-next-visible-heading 1)
  6801. (if (org-at-heading-p) (org-outline-level) 1))))
  6802. (new-level (or force-level (max previous-level next-level)))
  6803. (shift (if (or (= old-level -1)
  6804. (= new-level -1)
  6805. (= old-level new-level))
  6806. 0
  6807. (- new-level old-level)))
  6808. (delta (if (> shift 0) -1 1))
  6809. (func (if (> shift 0) #'org-demote #'org-promote))
  6810. (org-odd-levels-only nil)
  6811. beg end newend)
  6812. ;; Remove the forced level indicator.
  6813. (when (and force-level (not level))
  6814. (delete-region (line-beginning-position) (point)))
  6815. ;; Paste before the next visible heading or at end of buffer,
  6816. ;; unless point is at the beginning of a headline.
  6817. (unless (and (bolp) (org-at-heading-p))
  6818. (org-next-visible-heading 1)
  6819. (unless (bolp) (insert "\n")))
  6820. (setq beg (point))
  6821. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6822. (insert-before-markers txt)
  6823. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6824. (setq newend (point))
  6825. (org-reinstall-markers-in-region beg)
  6826. (setq end (point))
  6827. (goto-char beg)
  6828. (skip-chars-forward " \t\n\r")
  6829. (setq beg (point))
  6830. (when (and (org-invisible-p) visp)
  6831. (save-excursion (outline-show-heading)))
  6832. ;; Shift if necessary.
  6833. (unless (= shift 0)
  6834. (save-restriction
  6835. (narrow-to-region beg end)
  6836. (while (not (= shift 0))
  6837. (org-map-region func (point-min) (point-max))
  6838. (setq shift (+ delta shift)))
  6839. (goto-char (point-min))
  6840. (setq newend (point-max))))
  6841. (when (or for-yank (called-interactively-p 'interactive))
  6842. (message "Clipboard pasted as level %d subtree" new-level))
  6843. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6844. kill-ring
  6845. (equal org-subtree-clip (current-kill 0))
  6846. org-subtree-clip-folded)
  6847. ;; The tree was folded before it was killed/copied
  6848. (org-flag-subtree t))
  6849. (when for-yank (goto-char newend))
  6850. (when remove (pop kill-ring)))))
  6851. (defun org-kill-is-subtree-p (&optional txt)
  6852. "Check if the current kill is an outline subtree, or a set of trees.
  6853. Returns nil if kill does not start with a headline, or if the first
  6854. headline level is not the largest headline level in the tree.
  6855. So this will actually accept several entries of equal levels as well,
  6856. which is OK for `org-paste-subtree'.
  6857. If optional TXT is given, check this string instead of the current kill."
  6858. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6859. (re (org-get-limited-outline-regexp))
  6860. (^re (concat "^" re))
  6861. (start-level (and kill
  6862. (string-match
  6863. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6864. kill)
  6865. (- (match-end 2) (match-beginning 2) 1)))
  6866. (start (1+ (or (match-beginning 2) -1))))
  6867. (if (not start-level)
  6868. (progn
  6869. nil) ;; does not even start with a heading
  6870. (catch 'exit
  6871. (while (setq start (string-match ^re kill (1+ start)))
  6872. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6873. (throw 'exit nil)))
  6874. t))))
  6875. (defvar org-markers-to-move nil
  6876. "Markers that should be moved with a cut-and-paste operation.
  6877. Those markers are stored together with their positions relative to
  6878. the start of the region.")
  6879. (defun org-save-markers-in-region (beg end)
  6880. "Check markers in region.
  6881. If these markers are between BEG and END, record their position relative
  6882. to BEG, so that after moving the block of text, we can put the markers back
  6883. into place.
  6884. This function gets called just before an entry or tree gets cut from the
  6885. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6886. called immediately, to move the markers with the entries."
  6887. (setq org-markers-to-move nil)
  6888. (when (featurep 'org-clock)
  6889. (org-clock-save-markers-for-cut-and-paste beg end))
  6890. (when (featurep 'org-agenda)
  6891. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6892. (defun org-check-and-save-marker (marker beg end)
  6893. "Check if MARKER is between BEG and END.
  6894. If yes, remember the marker and the distance to BEG."
  6895. (when (and (marker-buffer marker)
  6896. (equal (marker-buffer marker) (current-buffer))
  6897. (>= marker beg) (< marker end))
  6898. (push (cons marker (- marker beg)) org-markers-to-move)))
  6899. (defun org-reinstall-markers-in-region (beg)
  6900. "Move all remembered markers to their position relative to BEG."
  6901. (dolist (x org-markers-to-move)
  6902. (move-marker (car x) (+ beg (cdr x))))
  6903. (setq org-markers-to-move nil))
  6904. (defun org-narrow-to-subtree ()
  6905. "Narrow buffer to the current subtree."
  6906. (interactive)
  6907. (save-excursion
  6908. (save-match-data
  6909. (org-with-limited-levels
  6910. (narrow-to-region
  6911. (progn (org-back-to-heading t) (point))
  6912. (progn (org-end-of-subtree t t)
  6913. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6914. (point)))))))
  6915. (defun org-toggle-narrow-to-subtree ()
  6916. "Narrow to the subtree at point or widen a narrowed buffer."
  6917. (interactive)
  6918. (if (buffer-narrowed-p)
  6919. (widen)
  6920. (org-narrow-to-subtree)))
  6921. (defun org-narrow-to-block ()
  6922. "Narrow buffer to the current block."
  6923. (interactive)
  6924. (let* ((case-fold-search t)
  6925. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6926. "^[ \t]*#\\+end_.*")))
  6927. (if blockp
  6928. (narrow-to-region (car blockp) (cdr blockp))
  6929. (user-error "Not in a block"))))
  6930. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6931. "Clone the task (subtree) at point N times.
  6932. The clones will be inserted as siblings.
  6933. In interactive use, the user will be prompted for the number of
  6934. clones to be produced. If the entry has a timestamp, the user
  6935. will also be prompted for a time shift, which may be a repeater
  6936. as used in time stamps, for example `+3d'. To disable this,
  6937. you can call the function with a universal prefix argument.
  6938. When a valid repeater is given and the entry contains any time
  6939. stamps, the clones will become a sequence in time, with time
  6940. stamps in the subtree shifted for each clone produced. If SHIFT
  6941. is nil or the empty string, time stamps will be left alone. The
  6942. ID property of the original subtree is removed.
  6943. In each clone, all the CLOCK entries will be removed. This
  6944. prevents Org from considering that the clocked times overlap.
  6945. If the original subtree did contain time stamps with a repeater,
  6946. the following will happen:
  6947. - the repeater will be removed in each clone
  6948. - an additional clone will be produced, with the current, unshifted
  6949. date(s) in the entry.
  6950. - the original entry will be placed *after* all the clones, with
  6951. repeater intact.
  6952. - the start days in the repeater in the original entry will be shifted
  6953. to past the last clone.
  6954. In this way you can spell out a number of instances of a repeating task,
  6955. and still retain the repeater to cover future instances of the task.
  6956. As described above, N+1 clones are produced when the original
  6957. subtree has a repeater. Setting N to 0, then, can be used to
  6958. remove the repeater from a subtree and create a shifted clone
  6959. with the original repeater."
  6960. (interactive "nNumber of clones to produce: ")
  6961. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  6962. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  6963. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  6964. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  6965. (shift
  6966. (or shift
  6967. (if (and (not (equal current-prefix-arg '(4)))
  6968. (save-excursion
  6969. (goto-char beg)
  6970. (re-search-forward org-ts-regexp-both end-of-tree t)))
  6971. (read-from-minibuffer
  6972. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  6973. ""))) ;No time shift
  6974. (doshift
  6975. (and (org-string-nw-p shift)
  6976. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  6977. shift)
  6978. (user-error "Invalid shift specification %s" shift)))))
  6979. (goto-char end-of-tree)
  6980. (unless (bolp) (insert "\n"))
  6981. (let* ((end (point))
  6982. (template (buffer-substring beg end))
  6983. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  6984. (shift-what (pcase (and doshift (match-string 2 shift))
  6985. (`nil nil)
  6986. ("d" 'day)
  6987. ("w" (setq shift-n (* 7 shift-n)) 'day)
  6988. ("m" 'month)
  6989. ("y" 'year)
  6990. (_ (error "Unsupported time unit"))))
  6991. (nmin 1)
  6992. (nmax n)
  6993. (n-no-remove -1)
  6994. (idprop (org-entry-get beg "ID")))
  6995. (when (and doshift
  6996. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  6997. template))
  6998. (delete-region beg end)
  6999. (setq end beg)
  7000. (setq nmin 0)
  7001. (setq nmax (1+ nmax))
  7002. (setq n-no-remove nmax))
  7003. (goto-char end)
  7004. (cl-loop for n from nmin to nmax do
  7005. (insert
  7006. ;; Prepare clone.
  7007. (with-temp-buffer
  7008. (insert template)
  7009. (org-mode)
  7010. (goto-char (point-min))
  7011. (org-show-subtree)
  7012. (and idprop (if org-clone-delete-id
  7013. (org-entry-delete nil "ID")
  7014. (org-id-get-create t)))
  7015. (unless (= n 0)
  7016. (while (re-search-forward org-clock-line-re nil t)
  7017. (delete-region (line-beginning-position)
  7018. (line-beginning-position 2)))
  7019. (goto-char (point-min))
  7020. (while (re-search-forward org-drawer-regexp nil t)
  7021. (org-remove-empty-drawer-at (point))))
  7022. (goto-char (point-min))
  7023. (when doshift
  7024. (while (re-search-forward org-ts-regexp-both nil t)
  7025. (org-timestamp-change (* n shift-n) shift-what))
  7026. (unless (= n n-no-remove)
  7027. (goto-char (point-min))
  7028. (while (re-search-forward org-ts-regexp nil t)
  7029. (save-excursion
  7030. (goto-char (match-beginning 0))
  7031. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7032. (delete-region (match-beginning 1) (match-end 1)))))))
  7033. (buffer-string)))))
  7034. (goto-char beg)))
  7035. ;;; Outline Sorting
  7036. (defun org-sort (&optional with-case)
  7037. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7038. Optional argument WITH-CASE means sort case-sensitively."
  7039. (interactive "P")
  7040. (org-call-with-arg
  7041. (cond ((org-at-table-p) #'org-table-sort-lines)
  7042. ((org-at-item-p) #'org-sort-list)
  7043. (t #'org-sort-entries))
  7044. with-case))
  7045. (defun org-sort-remove-invisible (s)
  7046. "Remove invisible part of links and emphasis markers from string S."
  7047. (remove-text-properties 0 (length s) org-rm-props s)
  7048. (replace-regexp-in-string
  7049. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7050. (replace-regexp-in-string
  7051. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7052. (org-link-display-format s)
  7053. t t) t t))
  7054. (defvar org-priority-regexp) ; defined later in the file
  7055. (defvar org-after-sorting-entries-or-items-hook nil
  7056. "Hook that is run after a bunch of entries or items have been sorted.
  7057. When children are sorted, the cursor is in the parent line when this
  7058. hook gets called. When a region or a plain list is sorted, the cursor
  7059. will be in the first entry of the sorted region/list.")
  7060. (defun org-sort-entries
  7061. (&optional with-case sorting-type getkey-func compare-func property
  7062. interactive?)
  7063. "Sort entries on a certain level of an outline tree.
  7064. If there is an active region, the entries in the region are sorted.
  7065. Else, if the cursor is before the first entry, sort the top-level items.
  7066. Else, the children of the entry at point are sorted.
  7067. Sorting can be alphabetically, numerically, by date/time as given by
  7068. a time stamp, by a property, by priority order, or by a custom function.
  7069. The command prompts for the sorting type unless it has been given to the
  7070. function through the SORTING-TYPE argument, which needs to be a character,
  7071. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7072. the precise meaning of each character:
  7073. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7074. c By creation time, which is assumed to be the first inactive time stamp
  7075. at the beginning of a line.
  7076. d By deadline date/time.
  7077. k By clocking time.
  7078. n Numerically, by converting the beginning of the entry/item to a number.
  7079. o By order of TODO keywords.
  7080. p By priority according to the cookie.
  7081. r By the value of a property.
  7082. s By scheduled date/time.
  7083. t By date/time, either the first active time stamp in the entry, or, if
  7084. none exist, by the first inactive one.
  7085. Capital letters will reverse the sort order.
  7086. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7087. called with point at the beginning of the record. It must return a
  7088. value that is compatible with COMPARE-FUNC, the function used to
  7089. compare entries.
  7090. Comparing entries ignores case by default. However, with an optional argument
  7091. WITH-CASE, the sorting considers case as well.
  7092. Sorting is done against the visible part of the headlines, it ignores hidden
  7093. links.
  7094. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7095. A non-nil value for INTERACTIVE? is used to signal that this
  7096. function is being called interactively."
  7097. (interactive (list current-prefix-arg nil nil nil nil t))
  7098. (let ((case-func (if with-case 'identity 'downcase))
  7099. start beg end stars re re2
  7100. txt what tmp)
  7101. ;; Find beginning and end of region to sort
  7102. (cond
  7103. ((org-region-active-p)
  7104. ;; we will sort the region
  7105. (setq end (region-end)
  7106. what "region")
  7107. (goto-char (region-beginning))
  7108. (unless (org-at-heading-p) (outline-next-heading))
  7109. (setq start (point)))
  7110. ((or (org-at-heading-p)
  7111. (ignore-errors (progn (org-back-to-heading) t)))
  7112. ;; we will sort the children of the current headline
  7113. (org-back-to-heading)
  7114. (setq start (point)
  7115. end (progn (org-end-of-subtree t t)
  7116. (or (bolp) (insert "\n"))
  7117. (when (>= (org-back-over-empty-lines) 1)
  7118. (forward-line 1))
  7119. (point))
  7120. what "children")
  7121. (goto-char start)
  7122. (outline-show-subtree)
  7123. (outline-next-heading))
  7124. (t
  7125. ;; we will sort the top-level entries in this file
  7126. (goto-char (point-min))
  7127. (or (org-at-heading-p) (outline-next-heading))
  7128. (setq start (point))
  7129. (goto-char (point-max))
  7130. (beginning-of-line 1)
  7131. (when (looking-at ".*?\\S-")
  7132. ;; File ends in a non-white line
  7133. (end-of-line 1)
  7134. (insert "\n"))
  7135. (setq end (point-max))
  7136. (setq what "top-level")
  7137. (goto-char start)
  7138. (org-show-all '(headings blocks))))
  7139. (setq beg (point))
  7140. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7141. (looking-at "\\(\\*+\\)")
  7142. (setq stars (match-string 1)
  7143. re (concat "^" (regexp-quote stars) " +")
  7144. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7145. txt (buffer-substring beg end))
  7146. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7147. (when (and (not (equal stars "*")) (string-match re2 txt))
  7148. (user-error "Region to sort contains a level above the first entry"))
  7149. (unless sorting-type
  7150. (message
  7151. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7152. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7153. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7154. what)
  7155. (setq sorting-type (read-char-exclusive)))
  7156. (unless getkey-func
  7157. (and (= (downcase sorting-type) ?f)
  7158. (setq getkey-func
  7159. (or (and interactive?
  7160. (org-read-function
  7161. "Function for extracting keys: "))
  7162. (error "Missing key extractor")))))
  7163. (and (= (downcase sorting-type) ?r)
  7164. (not property)
  7165. (setq property
  7166. (completing-read "Property: "
  7167. (mapcar #'list (org-buffer-property-keys t))
  7168. nil t)))
  7169. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7170. (message "Sorting entries...")
  7171. (save-restriction
  7172. (narrow-to-region start end)
  7173. (let ((restore-clock?
  7174. ;; The clock marker is lost when using `sort-subr'; mark
  7175. ;; the clock with temporary `:org-clock-marker-backup'
  7176. ;; text property.
  7177. (when (and (eq (org-clock-is-active) (current-buffer))
  7178. (<= start (marker-position org-clock-marker))
  7179. (>= end (marker-position org-clock-marker)))
  7180. (with-silent-modifications
  7181. (put-text-property (1- org-clock-marker) org-clock-marker
  7182. :org-clock-marker-backup t))
  7183. t))
  7184. (dcst (downcase sorting-type))
  7185. (case-fold-search nil)
  7186. (now (current-time)))
  7187. (org-preserve-local-variables
  7188. (sort-subr
  7189. (/= dcst sorting-type)
  7190. ;; This function moves to the beginning character of the
  7191. ;; "record" to be sorted.
  7192. (lambda nil
  7193. (if (re-search-forward re nil t)
  7194. (goto-char (match-beginning 0))
  7195. (goto-char (point-max))))
  7196. ;; This function moves to the last character of the "record" being
  7197. ;; sorted.
  7198. (lambda nil
  7199. (save-match-data
  7200. (condition-case nil
  7201. (outline-forward-same-level 1)
  7202. (error
  7203. (goto-char (point-max))))))
  7204. ;; This function returns the value that gets sorted against.
  7205. (lambda ()
  7206. (cond
  7207. ((= dcst ?n)
  7208. (string-to-number
  7209. (org-sort-remove-invisible (org-get-heading t t t t))))
  7210. ((= dcst ?a)
  7211. (funcall case-func
  7212. (org-sort-remove-invisible (org-get-heading t t t t))))
  7213. ((= dcst ?k)
  7214. (or (get-text-property (point) :org-clock-minutes) 0))
  7215. ((= dcst ?t)
  7216. (let ((end (save-excursion (outline-next-heading) (point))))
  7217. (if (or (re-search-forward org-ts-regexp end t)
  7218. (re-search-forward org-ts-regexp-both end t))
  7219. (org-time-string-to-seconds (match-string 0))
  7220. (float-time now))))
  7221. ((= dcst ?c)
  7222. (let ((end (save-excursion (outline-next-heading) (point))))
  7223. (if (re-search-forward
  7224. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7225. end t)
  7226. (org-time-string-to-seconds (match-string 0))
  7227. (float-time now))))
  7228. ((= dcst ?s)
  7229. (let ((end (save-excursion (outline-next-heading) (point))))
  7230. (if (re-search-forward org-scheduled-time-regexp end t)
  7231. (org-time-string-to-seconds (match-string 1))
  7232. (float-time now))))
  7233. ((= dcst ?d)
  7234. (let ((end (save-excursion (outline-next-heading) (point))))
  7235. (if (re-search-forward org-deadline-time-regexp end t)
  7236. (org-time-string-to-seconds (match-string 1))
  7237. (float-time now))))
  7238. ((= dcst ?p)
  7239. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7240. (string-to-char (match-string 2))
  7241. org-default-priority))
  7242. ((= dcst ?r)
  7243. (or (org-entry-get nil property) ""))
  7244. ((= dcst ?o)
  7245. (when (looking-at org-complex-heading-regexp)
  7246. (let* ((m (match-string 2))
  7247. (s (if (member m org-done-keywords) '- '+)))
  7248. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7249. ((= dcst ?f)
  7250. (if getkey-func
  7251. (progn
  7252. (setq tmp (funcall getkey-func))
  7253. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7254. tmp)
  7255. (error "Invalid key function `%s'" getkey-func)))
  7256. (t (error "Invalid sorting type `%c'" sorting-type))))
  7257. nil
  7258. (cond
  7259. ((= dcst ?a) 'org-string-collate-lessp)
  7260. ((= dcst ?f)
  7261. (or compare-func
  7262. (and interactive?
  7263. (org-read-function
  7264. (concat "Function for comparing keys "
  7265. "(empty for default `sort-subr' predicate): ")
  7266. 'allow-empty))))
  7267. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7268. (org-cycle-hide-drawers 'all)
  7269. (when restore-clock?
  7270. (move-marker org-clock-marker
  7271. (1+ (next-single-property-change
  7272. start :org-clock-marker-backup)))
  7273. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7274. '(:org-clock-marker-backup t)))))
  7275. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7276. (message "Sorting entries...done")))
  7277. (defun org-contextualize-keys (alist contexts)
  7278. "Return valid elements in ALIST depending on CONTEXTS.
  7279. `org-agenda-custom-commands' or `org-capture-templates' are the
  7280. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7281. or `org-capture-templates-contexts' are the associated contexts
  7282. definitions."
  7283. (let ((contexts
  7284. ;; normalize contexts
  7285. (mapcar
  7286. (lambda(c) (cond ((listp (cadr c))
  7287. (list (car c) (car c) (nth 1 c)))
  7288. ((string= "" (cadr c))
  7289. (list (car c) (car c) (nth 2 c)))
  7290. (t c)))
  7291. contexts))
  7292. (a alist) r s)
  7293. ;; loop over all commands or templates
  7294. (dolist (c a)
  7295. (let (vrules repl)
  7296. (cond
  7297. ((not (assoc (car c) contexts))
  7298. (push c r))
  7299. ((and (assoc (car c) contexts)
  7300. (setq vrules (org-contextualize-validate-key
  7301. (car c) contexts)))
  7302. (mapc (lambda (vr)
  7303. (unless (equal (car vr) (cadr vr))
  7304. (setq repl vr)))
  7305. vrules)
  7306. (if (not repl) (push c r)
  7307. (push (cadr repl) s)
  7308. (push
  7309. (cons (car c)
  7310. (cdr (or (assoc (cadr repl) alist)
  7311. (error "Undefined key `%s' as contextual replacement for `%s'"
  7312. (cadr repl) (car c)))))
  7313. r))))))
  7314. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7315. (delq
  7316. nil
  7317. (delete-dups
  7318. (mapcar (lambda (x)
  7319. (let ((tpl (car x)))
  7320. (unless (delq
  7321. nil
  7322. (mapcar (lambda (y)
  7323. (equal y tpl))
  7324. s))
  7325. x)))
  7326. (reverse r))))))
  7327. (defun org-contextualize-validate-key (key contexts)
  7328. "Check CONTEXTS for agenda or capture KEY."
  7329. (let (res)
  7330. (dolist (r contexts)
  7331. (dolist (rr (car (last r)))
  7332. (when
  7333. (and (equal key (car r))
  7334. (if (functionp rr) (funcall rr)
  7335. (or (and (eq (car rr) 'in-file)
  7336. (buffer-file-name)
  7337. (string-match (cdr rr) (buffer-file-name)))
  7338. (and (eq (car rr) 'in-mode)
  7339. (string-match (cdr rr) (symbol-name major-mode)))
  7340. (and (eq (car rr) 'in-buffer)
  7341. (string-match (cdr rr) (buffer-name)))
  7342. (when (and (eq (car rr) 'not-in-file)
  7343. (buffer-file-name))
  7344. (not (string-match (cdr rr) (buffer-file-name))))
  7345. (when (eq (car rr) 'not-in-mode)
  7346. (not (string-match (cdr rr) (symbol-name major-mode))))
  7347. (when (eq (car rr) 'not-in-buffer)
  7348. (not (string-match (cdr rr) (buffer-name)))))))
  7349. (push r res))))
  7350. (delete-dups (delq nil res))))
  7351. ;; Defined to provide a value for defcustom, since there is no
  7352. ;; string-collate-greaterp in Emacs.
  7353. (defun org-string-collate-greaterp (s1 s2)
  7354. "Return non-nil if S1 is greater than S2 in collation order."
  7355. (not (org-string-collate-lessp s1 s2)))
  7356. ;;;###autoload
  7357. (defun org-run-like-in-org-mode (cmd)
  7358. "Run a command, pretending that the current buffer is in Org mode.
  7359. This will temporarily bind local variables that are typically bound in
  7360. Org mode to the values they have in Org mode, and then interactively
  7361. call CMD."
  7362. (org-load-modules-maybe)
  7363. (let (binds)
  7364. (dolist (var (org-get-local-variables))
  7365. (when (or (not (boundp (car var)))
  7366. (eq (symbol-value (car var))
  7367. (default-value (car var))))
  7368. (push (list (car var) `(quote ,(cadr var))) binds)))
  7369. (eval `(let ,binds
  7370. (call-interactively (quote ,cmd))))))
  7371. (defun org-get-category (&optional pos force-refresh)
  7372. "Get the category applying to position POS."
  7373. (save-match-data
  7374. (when force-refresh (org-refresh-category-properties))
  7375. (let ((pos (or pos (point))))
  7376. (or (get-text-property pos 'org-category)
  7377. (progn (org-refresh-category-properties)
  7378. (get-text-property pos 'org-category))))))
  7379. ;;; Refresh properties
  7380. (defun org-refresh-properties (dprop tprop)
  7381. "Refresh buffer text properties.
  7382. DPROP is the drawer property and TPROP is either the
  7383. corresponding text property to set, or an alist with each element
  7384. being a text property (as a symbol) and a function to apply to
  7385. the value of the drawer property."
  7386. (let* ((case-fold-search t)
  7387. (inhibit-read-only t)
  7388. (inherit? (org-property-inherit-p dprop))
  7389. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7390. (global (and inherit? (org--property-global-value dprop nil))))
  7391. (with-silent-modifications
  7392. (org-with-point-at 1
  7393. ;; Set global values (e.g., values defined through
  7394. ;; "#+PROPERTY:" keywords) to the whole buffer.
  7395. (when global (put-text-property (point-min) (point-max) tprop global))
  7396. ;; Set local values.
  7397. (while (re-search-forward property-re nil t)
  7398. (when (org-at-property-p)
  7399. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7400. (outline-next-heading))))))
  7401. (defun org-refresh-property (tprop p &optional inherit)
  7402. "Refresh the buffer text property TPROP from the drawer property P.
  7403. The refresh happens only for the current headline, or the whole
  7404. subtree if optional argument INHERIT is non-nil."
  7405. (unless (org-before-first-heading-p)
  7406. (save-excursion
  7407. (org-back-to-heading t)
  7408. (let ((start (point))
  7409. (end (save-excursion
  7410. (if inherit (org-end-of-subtree t t)
  7411. (or (outline-next-heading) (point-max))))))
  7412. (if (symbolp tprop)
  7413. ;; TPROP is a text property symbol.
  7414. (put-text-property start end tprop p)
  7415. ;; TPROP is an alist with (property . function) elements.
  7416. (pcase-dolist (`(,prop . ,f) tprop)
  7417. (put-text-property start end prop (funcall f p))))))))
  7418. (defun org-refresh-category-properties ()
  7419. "Refresh category text properties in the buffer."
  7420. (let ((case-fold-search t)
  7421. (inhibit-read-only t)
  7422. (default-category
  7423. (cond ((null org-category)
  7424. (if buffer-file-name
  7425. (file-name-sans-extension
  7426. (file-name-nondirectory buffer-file-name))
  7427. "???"))
  7428. ((symbolp org-category) (symbol-name org-category))
  7429. (t org-category))))
  7430. (with-silent-modifications
  7431. (org-with-wide-buffer
  7432. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  7433. ;; This is the default category for the buffer. If none is
  7434. ;; found, fall-back to `org-category' or buffer file name.
  7435. (put-text-property
  7436. (point-min) (point-max)
  7437. 'org-category
  7438. (catch 'buffer-category
  7439. (goto-char (point-max))
  7440. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7441. (let ((element (org-element-at-point)))
  7442. (when (eq (org-element-type element) 'keyword)
  7443. (throw 'buffer-category
  7444. (org-element-property :value element)))))
  7445. default-category))
  7446. ;; Set subtree specific categories.
  7447. (goto-char (point-min))
  7448. (let ((regexp (org-re-property "CATEGORY")))
  7449. (while (re-search-forward regexp nil t)
  7450. (let ((value (match-string-no-properties 3)))
  7451. (when (org-at-property-p)
  7452. (put-text-property
  7453. (save-excursion (org-back-to-heading t) (point))
  7454. (save-excursion (org-end-of-subtree t t) (point))
  7455. 'org-category
  7456. value)))))))))
  7457. (defun org-refresh-stats-properties ()
  7458. "Refresh stats text properties in the buffer."
  7459. (with-silent-modifications
  7460. (org-with-point-at 1
  7461. (let ((regexp (concat org-outline-regexp-bol
  7462. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7463. (while (re-search-forward regexp nil t)
  7464. (let* ((numerator (string-to-number (match-string 1)))
  7465. (denominator (and (match-end 2)
  7466. (string-to-number (match-string 2))))
  7467. (stats (cond ((not denominator) numerator) ;percent
  7468. ((= denominator 0) 0)
  7469. (t (/ (* numerator 100) denominator)))))
  7470. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7471. 'org-stats stats)))))))
  7472. (defun org-refresh-effort-properties ()
  7473. "Refresh effort properties."
  7474. (org-refresh-properties
  7475. org-effort-property
  7476. '((effort . identity)
  7477. (effort-minutes . org-duration-to-minutes))))
  7478. (defun org-find-file-at-mouse (ev)
  7479. "Open file link or URL at mouse."
  7480. (interactive "e")
  7481. (mouse-set-point ev)
  7482. (org-open-at-point 'in-emacs))
  7483. (defun org-open-at-mouse (ev)
  7484. "Open file link or URL at mouse.
  7485. See the docstring of `org-open-file' for details."
  7486. (interactive "e")
  7487. (mouse-set-point ev)
  7488. (when (eq major-mode 'org-agenda-mode)
  7489. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7490. (org-open-at-point))
  7491. (defvar org-window-config-before-follow-link nil
  7492. "The window configuration before following a link.
  7493. This is saved in case the need arises to restore it.")
  7494. (defun org--file-default-apps ()
  7495. "Return the default applications for this operating system."
  7496. (pcase system-type
  7497. (`darwin org-file-apps-macos)
  7498. (`windows-nt org-file-apps-windowsnt)
  7499. (_ org-file-apps-gnu)))
  7500. (defun org--file-apps-entry-dlink-p (entry)
  7501. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7502. It assumes that is the case when the entry uses a regular
  7503. expression which has at least one grouping construct and the
  7504. action is either a Lisp form or a command string containing
  7505. \"%1\", i.e., using at least one subexpression match as
  7506. a parameter."
  7507. (pcase entry
  7508. (`(,selector . ,action)
  7509. (and (stringp selector)
  7510. (> (regexp-opt-depth selector) 0)
  7511. (or (and (stringp action)
  7512. (string-match "%[0-9]" action))
  7513. (consp action))))
  7514. (_ nil)))
  7515. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7516. "Convert extensions to regular expressions in the cars of LIST.
  7517. Also, weed out any non-string entries, because the return value
  7518. is used only for regexp matching.
  7519. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7520. point to the symbol `emacs', indicating that the file should be
  7521. opened in Emacs."
  7522. (append
  7523. (delq nil
  7524. (mapcar (lambda (x)
  7525. (unless (not (stringp (car x)))
  7526. (if (string-match "\\W" (car x))
  7527. x
  7528. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7529. list))
  7530. (when add-auto-mode
  7531. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7532. ;;;###autoload
  7533. (defun org-open-file (path &optional in-emacs line search)
  7534. "Open the file at PATH.
  7535. First, this expands any special file name abbreviations. Then the
  7536. configuration variable `org-file-apps' is checked if it contains an
  7537. entry for this file type, and if yes, the corresponding command is launched.
  7538. If no application is found, Emacs simply visits the file.
  7539. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7540. With a double \\[universal-argument] \\[universal-argument] \
  7541. prefix arg, Org tries to avoid opening in Emacs
  7542. and to use an external application to visit the file.
  7543. Optional LINE specifies a line to go to, optional SEARCH a string
  7544. to search for. If LINE or SEARCH is given, the file will be
  7545. opened in Emacs, unless an entry from `org-file-apps' that makes
  7546. use of groups in a regexp matches.
  7547. If you want to change the way frames are used when following a
  7548. link, please customize `org-link-frame-setup'.
  7549. If the file does not exist, throw an error."
  7550. (let* ((file (if (equal path "") buffer-file-name
  7551. (substitute-in-file-name (expand-file-name path))))
  7552. (file-apps (append org-file-apps (org--file-default-apps)))
  7553. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7554. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7555. file-apps))
  7556. (remp (and (assq 'remote apps) (file-remote-p file)))
  7557. (dirp (unless remp (file-directory-p file)))
  7558. (file (if (and dirp org-open-directory-means-index-dot-org)
  7559. (concat (file-name-as-directory file) "index.org")
  7560. file))
  7561. (a-m-a-p (assq 'auto-mode apps))
  7562. (dfile (downcase file))
  7563. ;; Reconstruct the original link from the PATH, LINE and
  7564. ;; SEARCH args.
  7565. (link (cond (line (concat file "::" (number-to-string line)))
  7566. (search (concat file "::" search))
  7567. (t file)))
  7568. (dlink (downcase link))
  7569. (ext
  7570. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7571. (match-string 1 dfile)))
  7572. (save-position-maybe
  7573. (let ((old-buffer (current-buffer))
  7574. (old-pos (point))
  7575. (old-mode major-mode))
  7576. (lambda ()
  7577. (and (derived-mode-p 'org-mode)
  7578. (eq old-mode 'org-mode)
  7579. (or (not (eq old-buffer (current-buffer)))
  7580. (not (eq old-pos (point))))
  7581. (org-mark-ring-push old-pos old-buffer)))))
  7582. cmd link-match-data)
  7583. (cond
  7584. ((member in-emacs '((16) system))
  7585. (setq cmd (cdr (assq 'system apps))))
  7586. (in-emacs (setq cmd 'emacs))
  7587. (t
  7588. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7589. (and dirp (cdr (assq 'directory apps)))
  7590. ;; First, try matching against apps-dlink if we
  7591. ;; get a match here, store the match data for
  7592. ;; later.
  7593. (let ((match (assoc-default dlink apps-dlink
  7594. 'string-match)))
  7595. (if match
  7596. (progn (setq link-match-data (match-data))
  7597. match)
  7598. (progn (setq in-emacs (or in-emacs line search))
  7599. nil))) ; if we have no match in apps-dlink,
  7600. ; always open the file in emacs if line or search
  7601. ; is given (for backwards compatibility)
  7602. (assoc-default dfile
  7603. (org--file-apps-regexp-alist apps a-m-a-p)
  7604. 'string-match)
  7605. (cdr (assoc ext apps))
  7606. (cdr (assq t apps))))))
  7607. (when (eq cmd 'system)
  7608. (setq cmd (cdr (assq 'system apps))))
  7609. (when (eq cmd 'default)
  7610. (setq cmd (cdr (assoc t apps))))
  7611. (when (eq cmd 'mailcap)
  7612. (require 'mailcap)
  7613. (mailcap-parse-mailcaps)
  7614. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7615. (command (mailcap-mime-info mime-type)))
  7616. (if (stringp command)
  7617. (setq cmd command)
  7618. (setq cmd 'emacs))))
  7619. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7620. (not (file-exists-p file))
  7621. (not org-open-non-existing-files))
  7622. (user-error "No such file: %s" file))
  7623. (cond
  7624. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7625. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7626. (while (string-match "['\"]%s['\"]" cmd)
  7627. (setq cmd (replace-match "%s" t t cmd)))
  7628. (setq cmd (replace-regexp-in-string
  7629. "%s"
  7630. (shell-quote-argument (convert-standard-filename file))
  7631. cmd
  7632. nil t))
  7633. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7634. (save-match-data
  7635. (let ((match-index 1)
  7636. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7637. (set-match-data link-match-data)
  7638. (while (<= match-index number-of-groups)
  7639. (let ((regex (concat "%" (number-to-string match-index)))
  7640. (replace-with (match-string match-index dlink)))
  7641. (while (string-match regex cmd)
  7642. (setq cmd (replace-match replace-with t t cmd))))
  7643. (setq match-index (+ match-index 1)))))
  7644. (save-window-excursion
  7645. (message "Running %s...done" cmd)
  7646. (start-process-shell-command cmd nil cmd)
  7647. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7648. ((or (stringp cmd)
  7649. (eq cmd 'emacs))
  7650. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7651. (widen)
  7652. (cond (line (org-goto-line line)
  7653. (when (derived-mode-p 'org-mode) (org-reveal)))
  7654. (search (condition-case err
  7655. (org-link-search search)
  7656. ;; Save position before error-ing out so user
  7657. ;; can easily move back to the original buffer.
  7658. (error (funcall save-position-maybe)
  7659. (error (nth 1 err)))))))
  7660. ((functionp cmd)
  7661. (save-match-data
  7662. (set-match-data link-match-data)
  7663. (condition-case nil
  7664. (funcall cmd file link)
  7665. ;; FIXME: Remove this check when most default installations
  7666. ;; of Emacs have at least Org 9.0.
  7667. ((debug wrong-number-of-arguments wrong-type-argument
  7668. invalid-function)
  7669. (user-error "Please see Org News for version 9.0 about \
  7670. `org-file-apps'--Lisp error: %S" cmd)))))
  7671. ((consp cmd)
  7672. ;; FIXME: Remove this check when most default installations of
  7673. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7674. ;; fall back to `org-link-frame-setup' for an old usage of
  7675. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7676. (user-error "Please see Org News for version 9.0 about \
  7677. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7678. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7679. (funcall save-position-maybe)))
  7680. ;;;###autoload
  7681. (defun org-open-at-point-global ()
  7682. "Follow a link or a time-stamp like Org mode does.
  7683. Also follow links and emails as seen by `thing-at-point'.
  7684. This command can be called in any mode to follow an external
  7685. link or a time-stamp that has Org mode syntax. Its behavior
  7686. is undefined when called on internal links like fuzzy links.
  7687. Raise a user error when there is nothing to follow."
  7688. (interactive)
  7689. (let ((tap-url (thing-at-point 'url))
  7690. (tap-email (thing-at-point 'email)))
  7691. (cond ((org-in-regexp org-link-any-re)
  7692. (org-link-open-from-string (match-string-no-properties 0)))
  7693. ((or (org-in-regexp org-ts-regexp-both nil t)
  7694. (org-in-regexp org-tsr-regexp-both nil t))
  7695. (org-follow-timestamp-link))
  7696. (tap-url (org-link-open-from-string tap-url))
  7697. (tap-email (org-link-open-from-string
  7698. (concat "mailto:" tap-email)))
  7699. (t (user-error "No link found")))))
  7700. (defvar org-open-at-point-functions nil
  7701. "Hook that is run when following a link at point.
  7702. Functions in this hook must return t if they identify and follow
  7703. a link at point. If they don't find anything interesting at point,
  7704. they must return nil.")
  7705. (defun org-open-at-point (&optional arg)
  7706. "Open link, timestamp, footnote or tags at point.
  7707. When point is on a link, follow it. Normally, files will be
  7708. opened by an appropriate application. If the optional prefix
  7709. argument ARG is non-nil, Emacs will visit the file. With
  7710. a double prefix argument, try to open outside of Emacs, in the
  7711. application the system uses for this file type.
  7712. When point is on a timestamp, open the agenda at the day
  7713. specified.
  7714. When point is a footnote definition, move to the first reference
  7715. found. If it is on a reference, move to the associated
  7716. definition.
  7717. When point is on a headline, display a list of every link in the
  7718. entry, so it is possible to pick one, or all, of them. If point
  7719. is on a tag, call `org-tags-view' instead.
  7720. On top of syntactically correct links, this function also tries
  7721. to open links and time-stamps in comments, node properties, and
  7722. keywords if point is on something looking like a timestamp or
  7723. a link."
  7724. (interactive "P")
  7725. (org-load-modules-maybe)
  7726. (setq org-window-config-before-follow-link (current-window-configuration))
  7727. (org-remove-occur-highlights nil nil t)
  7728. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7729. (let* ((context
  7730. ;; Only consider supported types, even if they are not the
  7731. ;; closest one.
  7732. (org-element-lineage
  7733. (org-element-context)
  7734. '(clock comment comment-block footnote-definition
  7735. footnote-reference headline inline-src-block inlinetask
  7736. keyword link node-property planning src-block timestamp)
  7737. t))
  7738. (type (org-element-type context))
  7739. (value (org-element-property :value context)))
  7740. (cond
  7741. ((not type) (user-error "No link found"))
  7742. ;; No valid link at point. For convenience, look if something
  7743. ;; looks like a link under point in some specific places.
  7744. ((memq type '(comment comment-block node-property keyword))
  7745. (call-interactively #'org-open-at-point-global))
  7746. ;; On a headline or an inlinetask, but not on a timestamp,
  7747. ;; a link, a footnote reference.
  7748. ((memq type '(headline inlinetask))
  7749. (org-match-line org-complex-heading-regexp)
  7750. (let ((tags-beg (match-beginning 5))
  7751. (tags-end (match-end 5)))
  7752. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7753. ;; On tags.
  7754. (org-tags-view
  7755. arg
  7756. (save-excursion
  7757. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7758. (end-tag (search-forward ":" tags-end nil 2)))
  7759. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7760. ;; Not on tags.
  7761. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7762. (`(nil . ,_)
  7763. (require 'org-attach)
  7764. (when (org-attach-dir)
  7765. (message "Opening attachment")
  7766. (if (equal arg '(4))
  7767. (org-attach-reveal-in-emacs)
  7768. (org-attach-reveal))))
  7769. (`(,links . ,links-end)
  7770. (dolist (link (if (stringp links) (list links) links))
  7771. (search-forward link nil links-end)
  7772. (goto-char (match-beginning 0))
  7773. (org-open-at-point arg)))))))
  7774. ;; On a footnote reference or at definition's label.
  7775. ((or (eq type 'footnote-reference)
  7776. (and (eq type 'footnote-definition)
  7777. (save-excursion
  7778. ;; Do not validate action when point is on the
  7779. ;; spaces right after the footnote label, in order
  7780. ;; to be on par with behavior on links.
  7781. (skip-chars-forward " \t")
  7782. (let ((begin
  7783. (org-element-property :contents-begin context)))
  7784. (if begin (< (point) begin)
  7785. (= (org-element-property :post-affiliated context)
  7786. (line-beginning-position)))))))
  7787. (org-footnote-action))
  7788. ;; On a planning line. Check if we are really on a timestamp.
  7789. ((and (eq type 'planning)
  7790. (org-in-regexp org-ts-regexp-both nil t))
  7791. (org-follow-timestamp-link))
  7792. ;; On a clock line, make sure point is on the timestamp
  7793. ;; before opening it.
  7794. ((and (eq type 'clock)
  7795. value
  7796. (>= (point) (org-element-property :begin value))
  7797. (<= (point) (org-element-property :end value)))
  7798. (org-follow-timestamp-link))
  7799. ((eq type 'src-block) (org-babel-open-src-block-result))
  7800. ;; Do nothing on white spaces after an object.
  7801. ((>= (point)
  7802. (save-excursion
  7803. (goto-char (org-element-property :end context))
  7804. (skip-chars-backward " \t")
  7805. (point)))
  7806. (user-error "No link found"))
  7807. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7808. ((eq type 'timestamp) (org-follow-timestamp-link))
  7809. ((eq type 'link) (org-link-open context arg))
  7810. (t (user-error "No link found")))))
  7811. (run-hook-with-args 'org-follow-link-hook))
  7812. ;;;###autoload
  7813. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7814. "Offer links in the current entry and return the selected link.
  7815. If there is only one link, return it.
  7816. If NTH is an integer, return the NTH link found.
  7817. If ZERO is a string, check also this string for a link, and if
  7818. there is one, return it."
  7819. (with-current-buffer buffer
  7820. (org-with-wide-buffer
  7821. (goto-char marker)
  7822. (let ((cnt ?0)
  7823. have-zero end links link c)
  7824. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7825. (push (match-string 0 zero) links)
  7826. (setq cnt (1- cnt) have-zero t))
  7827. (save-excursion
  7828. (org-back-to-heading t)
  7829. (setq end (save-excursion (outline-next-heading) (point)))
  7830. (while (re-search-forward org-link-any-re end t)
  7831. (push (match-string 0) links))
  7832. (setq links (org-uniquify (reverse links))))
  7833. (cond
  7834. ((null links)
  7835. (message "No links"))
  7836. ((equal (length links) 1)
  7837. (setq link (car links)))
  7838. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7839. (setq link (nth (if have-zero nth (1- nth)) links)))
  7840. (t ; we have to select a link
  7841. (save-excursion
  7842. (save-window-excursion
  7843. (delete-other-windows)
  7844. (with-output-to-temp-buffer "*Select Link*"
  7845. (dolist (l links)
  7846. (cond
  7847. ((not (string-match org-link-bracket-re l))
  7848. (princ (format "[%c] %s\n" (cl-incf cnt)
  7849. (org-unbracket-string "<" ">" l))))
  7850. ((match-end 2)
  7851. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7852. (match-string 2 l) (match-string 1 l))))
  7853. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7854. (match-string 1 l)))))))
  7855. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7856. (message "Select link to open, RET to open all:")
  7857. (setq c (read-char-exclusive))
  7858. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7859. (when (equal c ?q) (user-error "Abort"))
  7860. (if (equal c ?\C-m)
  7861. (setq link links)
  7862. (setq nth (- c ?0))
  7863. (when have-zero (setq nth (1+ nth)))
  7864. (unless (and (integerp nth) (>= (length links) nth))
  7865. (user-error "Invalid link selection"))
  7866. (setq link (nth (1- nth) links)))))
  7867. (cons link end)))))
  7868. ;;; File search
  7869. (defun org-do-occur (regexp &optional cleanup)
  7870. "Call the Emacs command `occur'.
  7871. If CLEANUP is non-nil, remove the printout of the regular expression
  7872. in the *Occur* buffer. This is useful if the regex is long and not useful
  7873. to read."
  7874. (occur regexp)
  7875. (when cleanup
  7876. (let ((cwin (selected-window)) win beg end)
  7877. (when (setq win (get-buffer-window "*Occur*"))
  7878. (select-window win))
  7879. (goto-char (point-min))
  7880. (when (re-search-forward "match[a-z]+" nil t)
  7881. (setq beg (match-end 0))
  7882. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7883. (setq end (1- (match-beginning 0)))))
  7884. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7885. (goto-char (point-min))
  7886. (select-window cwin))))
  7887. ;;; The Mark Ring
  7888. (defvar org-mark-ring nil
  7889. "Mark ring for positions before jumps in Org mode.")
  7890. (defvar org-mark-ring-last-goto nil
  7891. "Last position in the mark ring used to go back.")
  7892. ;; Fill and close the ring
  7893. (setq org-mark-ring nil)
  7894. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7895. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7896. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7897. org-mark-ring)
  7898. (defun org-mark-ring-push (&optional pos buffer)
  7899. "Put the current position into the mark ring and rotate it.
  7900. Also push position into the Emacs mark ring. If optional
  7901. argument POS and BUFFER are not nil, mark this location instead."
  7902. (interactive)
  7903. (let ((pos (or pos (point)))
  7904. (buffer (or buffer (current-buffer))))
  7905. (with-current-buffer buffer
  7906. (org-with-point-at pos (push-mark nil t)))
  7907. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  7908. (move-marker (car org-mark-ring) pos buffer))
  7909. (message
  7910. (substitute-command-keys
  7911. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  7912. (defun org-mark-ring-goto (&optional n)
  7913. "Jump to the previous position in the mark ring.
  7914. With prefix arg N, jump back that many stored positions. When
  7915. called several times in succession, walk through the entire ring.
  7916. Org mode commands jumping to a different position in the current file,
  7917. or to another Org file, automatically push the old position onto the ring."
  7918. (interactive "p")
  7919. (let (p m)
  7920. (if (eq last-command this-command)
  7921. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  7922. (setq p org-mark-ring))
  7923. (setq org-mark-ring-last-goto p)
  7924. (setq m (car p))
  7925. (pop-to-buffer-same-window (marker-buffer m))
  7926. (goto-char m)
  7927. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  7928. ;;; Following specific links
  7929. (defvar org-agenda-buffer-tmp-name)
  7930. (defvar org-agenda-start-on-weekday)
  7931. (defun org-follow-timestamp-link ()
  7932. "Open an agenda view for the time-stamp date/range at point."
  7933. (cond
  7934. ((org-at-date-range-p t)
  7935. (let ((org-agenda-start-on-weekday)
  7936. (t1 (match-string 1))
  7937. (t2 (match-string 2)) tt1 tt2)
  7938. (setq tt1 (time-to-days (org-time-string-to-time t1))
  7939. tt2 (time-to-days (org-time-string-to-time t2)))
  7940. (let ((org-agenda-buffer-tmp-name
  7941. (format "*Org Agenda(a:%s)"
  7942. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  7943. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  7944. ((org-at-timestamp-p 'lax)
  7945. (let ((org-agenda-buffer-tmp-name
  7946. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  7947. (org-agenda-list nil (time-to-days (org-time-string-to-time
  7948. (substring (match-string 1) 0 10)))
  7949. 1)))
  7950. (t (error "This should not happen"))))
  7951. ;;; Following file links
  7952. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  7953. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  7954. (declare-function mailcap-mime-info
  7955. "mailcap" (string &optional request no-decode))
  7956. (defvar org-wait nil)
  7957. ;;;; Refiling
  7958. (defun org-get-org-file ()
  7959. "Read a filename, with default directory `org-directory'."
  7960. (let ((default (or org-default-notes-file remember-data-file)))
  7961. (read-file-name (format "File name [%s]: " default)
  7962. (file-name-as-directory org-directory)
  7963. default)))
  7964. (defun org-notes-order-reversed-p ()
  7965. "Check if the current file should receive notes in reversed order."
  7966. (cond
  7967. ((not org-reverse-note-order) nil)
  7968. ((eq t org-reverse-note-order) t)
  7969. ((not (listp org-reverse-note-order)) nil)
  7970. (t (catch 'exit
  7971. (dolist (entry org-reverse-note-order)
  7972. (when (string-match (car entry) buffer-file-name)
  7973. (throw 'exit (cdr entry))))))))
  7974. (defvar org-refile-target-table nil
  7975. "The list of refile targets, created by `org-refile'.")
  7976. (defvar org-agenda-new-buffers nil
  7977. "Buffers created to visit agenda files.")
  7978. (defvar org-refile-cache nil
  7979. "Cache for refile targets.")
  7980. (defvar org-refile-markers nil
  7981. "All the markers used for caching refile locations.")
  7982. (defun org-refile-marker (pos)
  7983. "Get a new refile marker, but only if caching is in use."
  7984. (if (not org-refile-use-cache)
  7985. pos
  7986. (let ((m (make-marker)))
  7987. (move-marker m pos)
  7988. (push m org-refile-markers)
  7989. m)))
  7990. (defun org-refile-cache-clear ()
  7991. "Clear the refile cache and disable all the markers."
  7992. (dolist (m org-refile-markers) (move-marker m nil))
  7993. (setq org-refile-markers nil)
  7994. (setq org-refile-cache nil)
  7995. (message "Refile cache has been cleared"))
  7996. (defun org-refile-cache-check-set (set)
  7997. "Check if all the markers in the cache still have live buffers."
  7998. (let (marker)
  7999. (catch 'exit
  8000. (while (and set (setq marker (nth 3 (pop set))))
  8001. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  8002. (when (and marker (null (marker-buffer marker)))
  8003. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  8004. (sit-for 3)
  8005. (throw 'exit nil)))
  8006. t)))
  8007. (defun org-refile-cache-put (set &rest identifiers)
  8008. "Push the refile targets SET into the cache, under IDENTIFIERS."
  8009. (let* ((key (sha1 (prin1-to-string identifiers)))
  8010. (entry (assoc key org-refile-cache)))
  8011. (if entry
  8012. (setcdr entry set)
  8013. (push (cons key set) org-refile-cache))))
  8014. (defun org-refile-cache-get (&rest identifiers)
  8015. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  8016. (cond
  8017. ((not org-refile-cache) nil)
  8018. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  8019. (t
  8020. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  8021. org-refile-cache))))
  8022. (and set (org-refile-cache-check-set set) set)))))
  8023. (defvar org-outline-path-cache nil
  8024. "Alist between buffer positions and outline paths.
  8025. It value is an alist (POSITION . PATH) where POSITION is the
  8026. buffer position at the beginning of an entry and PATH is a list
  8027. of strings describing the outline path for that entry, in reverse
  8028. order.")
  8029. (defun org-refile-get-targets (&optional default-buffer)
  8030. "Produce a table with refile targets."
  8031. (let ((case-fold-search nil)
  8032. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  8033. (entries (or org-refile-targets '((nil . (:level . 1)))))
  8034. targets tgs files desc descre)
  8035. (message "Getting targets...")
  8036. (with-current-buffer (or default-buffer (current-buffer))
  8037. (dolist (entry entries)
  8038. (setq files (car entry) desc (cdr entry))
  8039. (cond
  8040. ((null files) (setq files (list (current-buffer))))
  8041. ((eq files 'org-agenda-files)
  8042. (setq files (org-agenda-files 'unrestricted)))
  8043. ((and (symbolp files) (fboundp files))
  8044. (setq files (funcall files)))
  8045. ((and (symbolp files) (boundp files))
  8046. (setq files (symbol-value files))))
  8047. (when (stringp files) (setq files (list files)))
  8048. (cond
  8049. ((eq (car desc) :tag)
  8050. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  8051. ((eq (car desc) :todo)
  8052. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  8053. ((eq (car desc) :regexp)
  8054. (setq descre (cdr desc)))
  8055. ((eq (car desc) :level)
  8056. (setq descre (concat "^\\*\\{" (number-to-string
  8057. (if org-odd-levels-only
  8058. (1- (* 2 (cdr desc)))
  8059. (cdr desc)))
  8060. "\\}[ \t]")))
  8061. ((eq (car desc) :maxlevel)
  8062. (setq descre (concat "^\\*\\{1," (number-to-string
  8063. (if org-odd-levels-only
  8064. (1- (* 2 (cdr desc)))
  8065. (cdr desc)))
  8066. "\\}[ \t]")))
  8067. (t (error "Bad refiling target description %s" desc)))
  8068. (dolist (f files)
  8069. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  8070. (or
  8071. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  8072. (progn
  8073. (when (bufferp f)
  8074. (setq f (buffer-file-name (buffer-base-buffer f))))
  8075. (setq f (and f (expand-file-name f)))
  8076. (when (eq org-refile-use-outline-path 'file)
  8077. (push (list (file-name-nondirectory f) f nil nil) tgs))
  8078. (when (eq org-refile-use-outline-path 'buffer-name)
  8079. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  8080. (when (eq org-refile-use-outline-path 'full-file-path)
  8081. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  8082. (org-with-wide-buffer
  8083. (goto-char (point-min))
  8084. (setq org-outline-path-cache nil)
  8085. (while (re-search-forward descre nil t)
  8086. (beginning-of-line)
  8087. (let ((case-fold-search nil))
  8088. (looking-at org-complex-heading-regexp))
  8089. (let ((begin (point))
  8090. (heading (match-string-no-properties 4)))
  8091. (unless (or (and
  8092. org-refile-target-verify-function
  8093. (not
  8094. (funcall org-refile-target-verify-function)))
  8095. (not heading))
  8096. (let ((re (format org-complex-heading-regexp-format
  8097. (regexp-quote heading)))
  8098. (target
  8099. (if (not org-refile-use-outline-path) heading
  8100. (mapconcat
  8101. #'identity
  8102. (append
  8103. (pcase org-refile-use-outline-path
  8104. (`file (list (file-name-nondirectory
  8105. (buffer-file-name
  8106. (buffer-base-buffer)))))
  8107. (`full-file-path
  8108. (list (buffer-file-name
  8109. (buffer-base-buffer))))
  8110. (`buffer-name
  8111. (list (buffer-name
  8112. (buffer-base-buffer))))
  8113. (_ nil))
  8114. (mapcar (lambda (s) (replace-regexp-in-string
  8115. "/" "\\/" s nil t))
  8116. (org-get-outline-path t t)))
  8117. "/"))))
  8118. (push (list target f re (org-refile-marker (point)))
  8119. tgs)))
  8120. (when (= (point) begin)
  8121. ;; Verification function has not moved point.
  8122. (end-of-line)))))))
  8123. (when org-refile-use-cache
  8124. (org-refile-cache-put tgs (buffer-file-name) descre))
  8125. (setq targets (append tgs targets))))))
  8126. (message "Getting targets...done")
  8127. (delete-dups (nreverse targets))))
  8128. (defun org--get-outline-path-1 (&optional use-cache)
  8129. "Return outline path to current headline.
  8130. Outline path is a list of strings, in reverse order. When
  8131. optional argument USE-CACHE is non-nil, make use of a cache. See
  8132. `org-get-outline-path' for details.
  8133. Assume buffer is widened and point is on a headline."
  8134. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  8135. (let ((p (point))
  8136. (heading (let ((case-fold-search nil))
  8137. (looking-at org-complex-heading-regexp)
  8138. (if (not (match-end 4)) ""
  8139. ;; Remove statistics cookies.
  8140. (org-trim
  8141. (org-link-display-format
  8142. (replace-regexp-in-string
  8143. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  8144. (match-string-no-properties 4))))))))
  8145. (if (org-up-heading-safe)
  8146. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  8147. (when use-cache
  8148. (push (cons p path) org-outline-path-cache))
  8149. path)
  8150. ;; This is a new root node. Since we assume we are moving
  8151. ;; forward, we can drop previous cache so as to limit number
  8152. ;; of associations there.
  8153. (let ((path (list heading)))
  8154. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  8155. path)))))
  8156. (defun org-get-outline-path (&optional with-self use-cache)
  8157. "Return the outline path to the current entry.
  8158. An outline path is a list of ancestors for current headline, as
  8159. a list of strings. Statistics cookies are removed and links are
  8160. replaced with their description, if any, or their path otherwise.
  8161. When optional argument WITH-SELF is non-nil, the path also
  8162. includes the current headline.
  8163. When optional argument USE-CACHE is non-nil, cache outline paths
  8164. between calls to this function so as to avoid backtracking. This
  8165. argument is useful when planning to find more than one outline
  8166. path in the same document. In that case, there are two
  8167. conditions to satisfy:
  8168. - `org-outline-path-cache' is set to nil before starting the
  8169. process;
  8170. - outline paths are computed by increasing buffer positions."
  8171. (org-with-wide-buffer
  8172. (and (or (and with-self (org-back-to-heading t))
  8173. (org-up-heading-safe))
  8174. (reverse (org--get-outline-path-1 use-cache)))))
  8175. (defun org-format-outline-path (path &optional width prefix separator)
  8176. "Format the outline path PATH for display.
  8177. WIDTH is the maximum number of characters that is available.
  8178. PREFIX is a prefix to be included in the returned string,
  8179. such as the file name.
  8180. SEPARATOR is inserted between the different parts of the path,
  8181. the default is \"/\"."
  8182. (setq width (or width 79))
  8183. (setq path (delq nil path))
  8184. (unless (> width 0)
  8185. (user-error "Argument `width' must be positive"))
  8186. (setq separator (or separator "/"))
  8187. (let* ((org-odd-levels-only nil)
  8188. (fpath (concat
  8189. prefix (and prefix path separator)
  8190. (mapconcat
  8191. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  8192. (cl-loop for head in path
  8193. for n from 0
  8194. collect (org-add-props
  8195. head nil 'face
  8196. (nth (% n org-n-level-faces) org-level-faces)))
  8197. separator))))
  8198. (when (> (length fpath) width)
  8199. (if (< width 7)
  8200. ;; It's unlikely that `width' will be this small, but don't
  8201. ;; waste characters by adding ".." if it is.
  8202. (setq fpath (substring fpath 0 width))
  8203. (setf (substring fpath (- width 2)) "..")))
  8204. fpath))
  8205. (defun org-display-outline-path (&optional file current separator just-return-string)
  8206. "Display the current outline path in the echo area.
  8207. If FILE is non-nil, prepend the output with the file name.
  8208. If CURRENT is non-nil, append the current heading to the output.
  8209. SEPARATOR is passed through to `org-format-outline-path'. It separates
  8210. the different parts of the path and defaults to \"/\".
  8211. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  8212. (interactive "P")
  8213. (let* (case-fold-search
  8214. (bfn (buffer-file-name (buffer-base-buffer)))
  8215. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  8216. res)
  8217. (when current (setq path (append path
  8218. (save-excursion
  8219. (org-back-to-heading t)
  8220. (when (looking-at org-complex-heading-regexp)
  8221. (list (match-string 4)))))))
  8222. (setq res
  8223. (org-format-outline-path
  8224. path
  8225. (1- (frame-width))
  8226. (and file bfn (concat (file-name-nondirectory bfn) separator))
  8227. separator))
  8228. (if just-return-string
  8229. (org-no-properties res)
  8230. (org-unlogged-message "%s" res))))
  8231. (defvar org-refile-history nil
  8232. "History for refiling operations.")
  8233. (defvar org-after-refile-insert-hook nil
  8234. "Hook run after `org-refile' has inserted its stuff at the new location.
  8235. Note that this is still *before* the stuff will be removed from
  8236. the *old* location.")
  8237. (defvar org-capture-last-stored-marker)
  8238. (defvar org-refile-keep nil
  8239. "Non-nil means `org-refile' will copy instead of refile.")
  8240. (defun org-copy ()
  8241. "Like `org-refile', but copy."
  8242. (interactive)
  8243. (let ((org-refile-keep t))
  8244. (org-refile nil nil nil "Copy")))
  8245. (defun org-refile (&optional arg default-buffer rfloc msg)
  8246. "Move the entry or entries at point to another heading.
  8247. The list of target headings is compiled using the information in
  8248. `org-refile-targets', which see.
  8249. At the target location, the entry is filed as a subitem of the
  8250. target heading. Depending on `org-reverse-note-order', the new
  8251. subitem will either be the first or the last subitem.
  8252. If there is an active region, all entries in that region will be
  8253. refiled. However, the region must fulfill the requirement that
  8254. the first heading sets the top-level of the moved text.
  8255. With a `\\[universal-argument]' ARG, the command will only visit the target \
  8256. location
  8257. and not actually move anything.
  8258. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  8259. location where the last
  8260. refiling operation has put the subtree.
  8261. With a numeric prefix argument of `2', refile to the running clock.
  8262. With a numeric prefix argument of `3', emulate `org-refile-keep'
  8263. being set to t and copy to the target location, don't move it.
  8264. Beware that keeping refiled entries may result in duplicated ID
  8265. properties.
  8266. RFLOC can be a refile location obtained in a different way.
  8267. MSG is a string to replace \"Refile\" in the default prompt with
  8268. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  8269. See also `org-refile-use-outline-path'.
  8270. If you are using target caching (see `org-refile-use-cache'), you
  8271. have to clear the target cache in order to find new targets.
  8272. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  8273. prefix argument (`C-u C-u C-u C-c C-w')."
  8274. (interactive "P")
  8275. (if (member arg '(0 (64)))
  8276. (org-refile-cache-clear)
  8277. (let* ((actionmsg (cond (msg msg)
  8278. ((equal arg 3) "Refile (and keep)")
  8279. (t "Refile")))
  8280. (regionp (org-region-active-p))
  8281. (region-start (and regionp (region-beginning)))
  8282. (region-end (and regionp (region-end)))
  8283. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  8284. pos it nbuf file level reversed)
  8285. (setq last-command nil)
  8286. (when regionp
  8287. (goto-char region-start)
  8288. (beginning-of-line)
  8289. (setq region-start (point))
  8290. (unless (or (org-kill-is-subtree-p
  8291. (buffer-substring region-start region-end))
  8292. (prog1 org-refile-active-region-within-subtree
  8293. (let ((s (point-at-eol)))
  8294. (org-toggle-heading)
  8295. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  8296. (user-error "The region is not a (sequence of) subtree(s)")))
  8297. (if (equal arg '(16))
  8298. (org-refile-goto-last-stored)
  8299. (when (or
  8300. (and (equal arg 2)
  8301. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  8302. (prog1
  8303. (setq it (list (or org-clock-heading "running clock")
  8304. (buffer-file-name
  8305. (marker-buffer org-clock-hd-marker))
  8306. ""
  8307. (marker-position org-clock-hd-marker)))
  8308. (setq arg nil)))
  8309. (setq it
  8310. (or rfloc
  8311. (let (heading-text)
  8312. (save-excursion
  8313. (unless (and arg (listp arg))
  8314. (org-back-to-heading t)
  8315. (setq heading-text
  8316. (replace-regexp-in-string
  8317. org-link-bracket-re
  8318. "\\2"
  8319. (or (nth 4 (org-heading-components))
  8320. ""))))
  8321. (org-refile-get-location
  8322. (cond ((and arg (listp arg)) "Goto")
  8323. (regionp (concat actionmsg " region to"))
  8324. (t (concat actionmsg " subtree \""
  8325. heading-text "\" to")))
  8326. default-buffer
  8327. (and (not (equal '(4) arg))
  8328. org-refile-allow-creating-parent-nodes)))))))
  8329. (setq file (nth 1 it)
  8330. pos (nth 3 it))
  8331. (when (and (not arg)
  8332. pos
  8333. (equal (buffer-file-name) file)
  8334. (if regionp
  8335. (and (>= pos region-start)
  8336. (<= pos region-end))
  8337. (and (>= pos (point))
  8338. (< pos (save-excursion
  8339. (org-end-of-subtree t t))))))
  8340. (error "Cannot refile to position inside the tree or region"))
  8341. (setq nbuf (or (find-buffer-visiting file)
  8342. (find-file-noselect file)))
  8343. (if (and arg (not (equal arg 3)))
  8344. (progn
  8345. (pop-to-buffer-same-window nbuf)
  8346. (goto-char (cond (pos)
  8347. ((org-notes-order-reversed-p) (point-min))
  8348. (t (point-max))))
  8349. (org-show-context 'org-goto))
  8350. (if regionp
  8351. (progn
  8352. (org-kill-new (buffer-substring region-start region-end))
  8353. (org-save-markers-in-region region-start region-end))
  8354. (org-copy-subtree 1 nil t))
  8355. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  8356. (find-file-noselect file)))
  8357. (setq reversed (org-notes-order-reversed-p))
  8358. (org-with-wide-buffer
  8359. (if pos
  8360. (progn
  8361. (goto-char pos)
  8362. (setq level (org-get-valid-level (funcall outline-level) 1))
  8363. (goto-char
  8364. (if reversed
  8365. (or (outline-next-heading) (point-max))
  8366. (or (save-excursion (org-get-next-sibling))
  8367. (org-end-of-subtree t t)
  8368. (point-max)))))
  8369. (setq level 1)
  8370. (if (not reversed)
  8371. (goto-char (point-max))
  8372. (goto-char (point-min))
  8373. (or (outline-next-heading) (goto-char (point-max)))))
  8374. (unless (bolp) (newline))
  8375. (org-paste-subtree level nil nil t)
  8376. ;; Record information, according to `org-log-refile'.
  8377. ;; Do not prompt for a note when refiling multiple
  8378. ;; headlines, however. Simply add a time stamp.
  8379. (cond
  8380. ((not org-log-refile))
  8381. (regionp
  8382. (org-map-region
  8383. (lambda () (org-add-log-setup 'refile nil nil 'time))
  8384. (point)
  8385. (+ (point) (- region-end region-start))))
  8386. (t
  8387. (org-add-log-setup 'refile nil nil org-log-refile)))
  8388. (and org-auto-align-tags
  8389. (let ((org-loop-over-headlines-in-active-region nil))
  8390. (org-align-tags)))
  8391. (let ((bookmark-name (plist-get org-bookmark-names-plist
  8392. :last-refile)))
  8393. (when bookmark-name
  8394. (with-demoted-errors
  8395. (bookmark-set bookmark-name))))
  8396. ;; If we are refiling for capture, make sure that the
  8397. ;; last-capture pointers point here
  8398. (when (bound-and-true-p org-capture-is-refiling)
  8399. (let ((bookmark-name (plist-get org-bookmark-names-plist
  8400. :last-capture-marker)))
  8401. (when bookmark-name
  8402. (with-demoted-errors
  8403. (bookmark-set bookmark-name))))
  8404. (move-marker org-capture-last-stored-marker (point)))
  8405. (when (fboundp 'deactivate-mark) (deactivate-mark))
  8406. (run-hooks 'org-after-refile-insert-hook)))
  8407. (unless org-refile-keep
  8408. (if regionp
  8409. (delete-region (point) (+ (point) (- region-end region-start)))
  8410. (org-preserve-local-variables
  8411. (delete-region
  8412. (and (org-back-to-heading t) (point))
  8413. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  8414. (when (featurep 'org-inlinetask)
  8415. (org-inlinetask-remove-END-maybe))
  8416. (setq org-markers-to-move nil)
  8417. (message "%s to \"%s\" in file %s: done" actionmsg
  8418. (car it) file)))))))
  8419. (defun org-refile-goto-last-stored ()
  8420. "Go to the location where the last refile was stored."
  8421. (interactive)
  8422. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  8423. (message "This is the location of the last refile"))
  8424. (defun org-refile--get-location (refloc tbl)
  8425. "When user refile to REFLOC, find the associated target in TBL.
  8426. Also check `org-refile-target-table'."
  8427. (car (delq
  8428. nil
  8429. (mapcar
  8430. (lambda (r) (or (assoc r tbl)
  8431. (assoc r org-refile-target-table)))
  8432. (list (replace-regexp-in-string "/$" "" refloc)
  8433. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  8434. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  8435. "Prompt the user for a refile location, using PROMPT.
  8436. PROMPT should not be suffixed with a colon and a space, because
  8437. this function appends the default value from
  8438. `org-refile-history' automatically, if that is not empty."
  8439. (let ((org-refile-targets org-refile-targets)
  8440. (org-refile-use-outline-path org-refile-use-outline-path))
  8441. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  8442. (unless org-refile-target-table
  8443. (user-error "No refile targets"))
  8444. (let* ((cbuf (current-buffer))
  8445. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  8446. (cfunc (if (and org-refile-use-outline-path
  8447. org-outline-path-complete-in-steps)
  8448. #'org-olpath-completing-read
  8449. #'completing-read))
  8450. (extra (if org-refile-use-outline-path "/" ""))
  8451. (cbnex (concat (buffer-name) extra))
  8452. (filename (and cfn (expand-file-name cfn)))
  8453. (tbl (mapcar
  8454. (lambda (x)
  8455. (if (and (not (member org-refile-use-outline-path
  8456. '(file full-file-path)))
  8457. (not (equal filename (nth 1 x))))
  8458. (cons (concat (car x) extra " ("
  8459. (file-name-nondirectory (nth 1 x)) ")")
  8460. (cdr x))
  8461. (cons (concat (car x) extra) (cdr x))))
  8462. org-refile-target-table))
  8463. (completion-ignore-case t)
  8464. cdef
  8465. (prompt (concat prompt
  8466. (or (and (car org-refile-history)
  8467. (concat " (default " (car org-refile-history) ")"))
  8468. (and (assoc cbnex tbl) (setq cdef cbnex)
  8469. (concat " (default " cbnex ")"))) ": "))
  8470. pa answ parent-target child parent old-hist)
  8471. (setq old-hist org-refile-history)
  8472. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  8473. nil 'org-refile-history (or cdef (car org-refile-history))))
  8474. (if (setq pa (org-refile--get-location answ tbl))
  8475. (progn
  8476. (org-refile-check-position pa)
  8477. (when (or (not org-refile-history)
  8478. (not (eq old-hist org-refile-history))
  8479. (not (equal (car pa) (car org-refile-history))))
  8480. (setq org-refile-history
  8481. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  8482. org-refile-history
  8483. (cdr org-refile-history))))
  8484. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  8485. (pop org-refile-history)))
  8486. pa)
  8487. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  8488. (progn
  8489. (setq parent (match-string 1 answ)
  8490. child (match-string 2 answ))
  8491. (setq parent-target (org-refile--get-location parent tbl))
  8492. (when (and parent-target
  8493. (or (eq new-nodes t)
  8494. (and (eq new-nodes 'confirm)
  8495. (y-or-n-p (format "Create new node \"%s\"? "
  8496. child)))))
  8497. (org-refile-new-child parent-target child)))
  8498. (user-error "Invalid target location")))))
  8499. (declare-function org-string-nw-p "org-macs" (s))
  8500. (defun org-refile-check-position (refile-pointer)
  8501. "Check if the refile pointer matches the headline to which it points."
  8502. (let* ((file (nth 1 refile-pointer))
  8503. (re (nth 2 refile-pointer))
  8504. (pos (nth 3 refile-pointer))
  8505. buffer)
  8506. (if (and (not (markerp pos)) (not file))
  8507. (user-error "Please indicate a target file in the refile path")
  8508. (when (org-string-nw-p re)
  8509. (setq buffer (if (markerp pos)
  8510. (marker-buffer pos)
  8511. (or (find-buffer-visiting file)
  8512. (find-file-noselect file))))
  8513. (with-current-buffer buffer
  8514. (org-with-wide-buffer
  8515. (goto-char pos)
  8516. (beginning-of-line 1)
  8517. (unless (looking-at-p re)
  8518. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  8519. (defun org-refile-new-child (parent-target child)
  8520. "Use refile target PARENT-TARGET to add new CHILD below it."
  8521. (unless parent-target
  8522. (error "Cannot find parent for new node"))
  8523. (let ((file (nth 1 parent-target))
  8524. (pos (nth 3 parent-target))
  8525. level)
  8526. (with-current-buffer (or (find-buffer-visiting file)
  8527. (find-file-noselect file))
  8528. (org-with-wide-buffer
  8529. (if pos
  8530. (goto-char pos)
  8531. (goto-char (point-max))
  8532. (unless (bolp) (newline)))
  8533. (when (looking-at org-outline-regexp)
  8534. (setq level (funcall outline-level))
  8535. (org-end-of-subtree t t))
  8536. (org-back-over-empty-lines)
  8537. (insert "\n" (make-string
  8538. (if pos (org-get-valid-level level 1) 1) ?*)
  8539. " " child "\n")
  8540. (beginning-of-line 0)
  8541. (list (concat (car parent-target) "/" child) file "" (point))))))
  8542. (defun org-olpath-completing-read (prompt collection &rest args)
  8543. "Read an outline path like a file name."
  8544. (let ((thetable collection))
  8545. (apply #'completing-read
  8546. prompt
  8547. (lambda (string predicate &optional flag)
  8548. (cond
  8549. ((eq flag nil) (try-completion string thetable))
  8550. ((eq flag t)
  8551. (let ((l (length string)))
  8552. (mapcar (lambda (x)
  8553. (let ((r (substring x l))
  8554. (f (if (string-match " ([^)]*)$" x)
  8555. (match-string 0 x)
  8556. "")))
  8557. (if (string-match "/" r)
  8558. (concat string (substring r 0 (match-end 0)) f)
  8559. x)))
  8560. (all-completions string thetable predicate))))
  8561. ;; Exact match?
  8562. ((eq flag 'lambda) (assoc string thetable))))
  8563. args)))
  8564. ;;;; Dynamic blocks
  8565. (defun org-find-dblock (name)
  8566. "Find the first dynamic block with name NAME in the buffer.
  8567. If not found, stay at current position and return nil."
  8568. (let ((case-fold-search t) pos)
  8569. (save-excursion
  8570. (goto-char (point-min))
  8571. (setq pos (and (re-search-forward
  8572. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8573. (match-beginning 0))))
  8574. (when pos (goto-char pos))
  8575. pos))
  8576. (defun org-create-dblock (plist)
  8577. "Create a dynamic block section, with parameters taken from PLIST.
  8578. PLIST must contain a :name entry which is used as the name of the block."
  8579. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8580. (end-of-line 1)
  8581. (newline))
  8582. (let ((col (current-column))
  8583. (name (plist-get plist :name)))
  8584. (insert "#+BEGIN: " name)
  8585. (while plist
  8586. (if (eq (car plist) :name)
  8587. (setq plist (cddr plist))
  8588. (insert " " (prin1-to-string (pop plist)))))
  8589. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8590. (beginning-of-line -2)))
  8591. (defun org-prepare-dblock ()
  8592. "Prepare dynamic block for refresh.
  8593. This empties the block, puts the cursor at the insert position and returns
  8594. the property list including an extra property :name with the block name."
  8595. (unless (looking-at org-dblock-start-re)
  8596. (user-error "Not at a dynamic block"))
  8597. (let* ((begdel (1+ (match-end 0)))
  8598. (name (org-no-properties (match-string 1)))
  8599. (params (append (list :name name)
  8600. (read (concat "(" (match-string 3) ")")))))
  8601. (save-excursion
  8602. (beginning-of-line 1)
  8603. (skip-chars-forward " \t")
  8604. (setq params (plist-put params :indentation-column (current-column))))
  8605. (unless (re-search-forward org-dblock-end-re nil t)
  8606. (error "Dynamic block not terminated"))
  8607. (setq params
  8608. (append params
  8609. (list :content (buffer-substring
  8610. begdel (match-beginning 0)))))
  8611. (delete-region begdel (match-beginning 0))
  8612. (goto-char begdel)
  8613. (open-line 1)
  8614. params))
  8615. (defun org-map-dblocks (&optional command)
  8616. "Apply COMMAND to all dynamic blocks in the current buffer.
  8617. If COMMAND is not given, use `org-update-dblock'."
  8618. (let ((cmd (or command 'org-update-dblock)))
  8619. (save-excursion
  8620. (goto-char (point-min))
  8621. (while (re-search-forward org-dblock-start-re nil t)
  8622. (goto-char (match-beginning 0))
  8623. (save-excursion
  8624. (condition-case nil
  8625. (funcall cmd)
  8626. (error (message "Error during update of dynamic block"))))
  8627. (unless (re-search-forward org-dblock-end-re nil t)
  8628. (error "Dynamic block not terminated"))))))
  8629. (defvar org-dynamic-block-alist nil
  8630. "Alist defining all the Org dynamic blocks.
  8631. The key is the dynamic block type name, as a string. The value
  8632. is the function used to insert the dynamic block.
  8633. Use `org-dynamic-block-define' to populate it.")
  8634. (defun org-dynamic-block-function (type)
  8635. "Return function associated to a given dynamic block type.
  8636. TYPE is the dynamic block type, as a string."
  8637. (cdr (assoc type org-dynamic-block-alist)))
  8638. (defun org-dynamic-block-types ()
  8639. "List all defined dynamic block types."
  8640. (mapcar #'car org-dynamic-block-alist))
  8641. (defun org-dynamic-block-define (type func)
  8642. "Define dynamic block TYPE with FUNC.
  8643. TYPE is a string. FUNC is the function creating the dynamic
  8644. block of such type."
  8645. (pcase (assoc type org-dynamic-block-alist)
  8646. (`nil (push (cons type func) org-dynamic-block-alist))
  8647. (def (setcdr def func))))
  8648. (defun org-dynamic-block-insert-dblock (type)
  8649. "Insert a dynamic block of type TYPE.
  8650. When used interactively, select the dynamic block types among
  8651. defined types, per `org-dynamic-block-define'."
  8652. (interactive (list (completing-read "Dynamic block: "
  8653. (org-dynamic-block-types))))
  8654. (pcase (org-dynamic-block-function type)
  8655. (`nil (error "No such dynamic block: %S" type))
  8656. ((and f (pred functionp)) (funcall f))
  8657. (_ (error "Invalid function for dynamic block %S" type))))
  8658. (defun org-dblock-update (&optional arg)
  8659. "User command for updating dynamic blocks.
  8660. Update the dynamic block at point. With prefix ARG, update all dynamic
  8661. blocks in the buffer."
  8662. (interactive "P")
  8663. (if arg
  8664. (org-update-all-dblocks)
  8665. (or (looking-at org-dblock-start-re)
  8666. (org-beginning-of-dblock))
  8667. (org-update-dblock)))
  8668. (defun org-update-dblock ()
  8669. "Update the dynamic block at point.
  8670. This means to empty the block, parse for parameters and then call
  8671. the correct writing function."
  8672. (interactive)
  8673. (save-excursion
  8674. (let* ((win (selected-window))
  8675. (pos (point))
  8676. (line (org-current-line))
  8677. (params (org-prepare-dblock))
  8678. (name (plist-get params :name))
  8679. (indent (plist-get params :indentation-column))
  8680. (cmd (intern (concat "org-dblock-write:" name))))
  8681. (message "Updating dynamic block `%s' at line %d..." name line)
  8682. (funcall cmd params)
  8683. (message "Updating dynamic block `%s' at line %d...done" name line)
  8684. (goto-char pos)
  8685. (when (and indent (> indent 0))
  8686. (setq indent (make-string indent ?\ ))
  8687. (save-excursion
  8688. (select-window win)
  8689. (org-beginning-of-dblock)
  8690. (forward-line 1)
  8691. (while (not (looking-at org-dblock-end-re))
  8692. (insert indent)
  8693. (beginning-of-line 2))
  8694. (when (looking-at org-dblock-end-re)
  8695. (and (looking-at "[ \t]+")
  8696. (replace-match ""))
  8697. (insert indent)))))))
  8698. (defun org-beginning-of-dblock ()
  8699. "Find the beginning of the dynamic block at point.
  8700. Error if there is no such block at point."
  8701. (let ((pos (point))
  8702. beg)
  8703. (end-of-line 1)
  8704. (if (and (re-search-backward org-dblock-start-re nil t)
  8705. (setq beg (match-beginning 0))
  8706. (re-search-forward org-dblock-end-re nil t)
  8707. (> (match-end 0) pos))
  8708. (goto-char beg)
  8709. (goto-char pos)
  8710. (error "Not in a dynamic block"))))
  8711. (defun org-update-all-dblocks ()
  8712. "Update all dynamic blocks in the buffer.
  8713. This function can be used in a hook."
  8714. (interactive)
  8715. (when (derived-mode-p 'org-mode)
  8716. (org-map-dblocks 'org-update-dblock)))
  8717. ;;;; Completion
  8718. (declare-function org-export-backend-options "ox" (cl-x) t)
  8719. (defun org-get-export-keywords ()
  8720. "Return a list of all currently understood export keywords.
  8721. Export keywords include options, block names, attributes and
  8722. keywords relative to each registered export back-end."
  8723. (let (keywords)
  8724. (dolist (backend
  8725. (bound-and-true-p org-export-registered-backends)
  8726. (delq nil keywords))
  8727. ;; Back-end name (for keywords, like #+LATEX:)
  8728. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8729. (dolist (option-entry (org-export-backend-options backend))
  8730. ;; Back-end options.
  8731. (push (nth 1 option-entry) keywords)))))
  8732. (defconst org-options-keywords
  8733. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8734. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8735. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8736. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8737. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8738. (defcustom org-structure-template-alist
  8739. '(("a" . "export ascii")
  8740. ("c" . "center")
  8741. ("C" . "comment")
  8742. ("e" . "example")
  8743. ("E" . "export")
  8744. ("h" . "export html")
  8745. ("l" . "export latex")
  8746. ("q" . "quote")
  8747. ("s" . "src")
  8748. ("v" . "verse"))
  8749. "An alist of keys and block types.
  8750. `org-insert-structure-template' will display a menu with this
  8751. list of templates to choose from. The block type is inserted,
  8752. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8753. The menu keys are defined by the car of each entry in this alist.
  8754. If two entries have the keys \"a\" and \"aa\" respectively, the
  8755. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8756. latter will be inserted by typing \"aa\". If an entry with the
  8757. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8758. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8759. block can be inserted by pressing TAB after the string \"<KEY\"."
  8760. :group 'org-edit-structure
  8761. :type '(repeat
  8762. (cons (string :tag "Key")
  8763. (string :tag "Template")))
  8764. :package-version '(Org . "9.2"))
  8765. (defun org--check-org-structure-template-alist (&optional checklist)
  8766. "Check whether `org-structure-template-alist' is set up correctly.
  8767. In particular, check if the Org 9.2 format is used as opposed to
  8768. previous format.
  8769. "
  8770. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8771. (or (eval checklist)
  8772. org-structure-template-alist))))
  8773. (when elm
  8774. (org-display-warning
  8775. (format "
  8776. Please update the entries of `%s'.
  8777. In Org 9.2 the format was changed from something like
  8778. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8779. to something like
  8780. (\"s\" . \"src\")
  8781. Please refer to the documentation of `org-structure-template-alist'.
  8782. The following entries must be updated:
  8783. %s"
  8784. (or checklist 'org-structure-template-alist)
  8785. (pp-to-string elm))))))
  8786. (defun org--insert-structure-template-mks ()
  8787. "Present `org-structure-template-alist' with `org-mks'.
  8788. Menus are added if keys require more than one keystroke. Tabs
  8789. are added to single key entries when more than one stroke is
  8790. needed. Keys longer than two characters are reduced to two
  8791. characters."
  8792. (org--check-org-structure-template-alist)
  8793. (let* (case-fold-search
  8794. (templates (append org-structure-template-alist
  8795. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8796. (keys (mapcar #'car templates))
  8797. (start-letters
  8798. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8799. ;; Sort each element of `org-structure-template-alist' into
  8800. ;; sublists according to the first letter.
  8801. (superlist
  8802. (mapcar (lambda (letter)
  8803. (list letter
  8804. (cl-remove-if-not
  8805. (apply-partially #'string-match-p (concat "^" letter))
  8806. templates :key #'car)))
  8807. start-letters)))
  8808. (org-mks
  8809. (apply #'append
  8810. ;; Make an `org-mks' table. If only one element is
  8811. ;; present in a sublist, make it part of the top-menu,
  8812. ;; otherwise make a submenu according to the starting
  8813. ;; letter and populate it.
  8814. (mapcar (lambda (sublist)
  8815. (if (eq 1 (length (cadr sublist)))
  8816. (mapcar (lambda (elm)
  8817. (list (substring (car elm) 0 1)
  8818. (cdr elm) ""))
  8819. (cadr sublist))
  8820. ;; Create submenu.
  8821. (let* ((topkey (car sublist))
  8822. (elms (cadr sublist))
  8823. (keys (mapcar #'car elms))
  8824. (long (> (length elms) 3)))
  8825. (append
  8826. (list
  8827. ;; Make a description of the submenu.
  8828. (list topkey
  8829. (concat
  8830. (mapconcat #'cdr
  8831. (cl-subseq elms 0 (if long 3 (length elms)))
  8832. ", ")
  8833. (when long ", ..."))))
  8834. ;; List of entries in submenu.
  8835. (cl-mapcar #'list
  8836. (org--insert-structure-template-unique-keys keys)
  8837. (mapcar #'cdr elms)
  8838. (make-list (length elms) ""))))))
  8839. superlist))
  8840. "Select a key\n============"
  8841. "Key: ")))
  8842. (defun org--insert-structure-template-unique-keys (keys)
  8843. "Make a list of unique, two characters long elements from KEYS.
  8844. Elements of length one have a tab appended. Elements of length
  8845. two are kept as is. Longer elements are truncated to length two.
  8846. If an element cannot be made unique, an error is raised."
  8847. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8848. menu-keys)
  8849. (dolist (key ordered-keys)
  8850. (let ((potential-key
  8851. (cl-case (length key)
  8852. (1 (concat key "\t"))
  8853. (2 key)
  8854. (otherwise
  8855. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8856. (mapcar (apply-partially #'concat (substring key 0 1))
  8857. (split-string (substring key 1) "" t)))))))
  8858. (if (or (not potential-key) (assoc potential-key menu-keys))
  8859. (user-error "Could not make unique key for %s." key)
  8860. (push (cons potential-key key) menu-keys))))
  8861. (mapcar #'car
  8862. (cl-sort menu-keys #'<
  8863. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8864. (defun org-insert-structure-template (type)
  8865. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8866. Select a block from `org-structure-template-alist' then type
  8867. either RET, TAB or SPC to write the block type. With an active
  8868. region, wrap the region in the block. Otherwise, insert an empty
  8869. block."
  8870. (interactive
  8871. (list (pcase (org--insert-structure-template-mks)
  8872. (`("\t" . ,_) (read-string "Structure type: "))
  8873. (`(,_ ,choice . ,_) choice))))
  8874. (let* ((region? (use-region-p))
  8875. (region-start (and region? (region-beginning)))
  8876. (region-end (and region? (copy-marker (region-end))))
  8877. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8878. (verbatim? (string-match-p
  8879. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8880. type)))
  8881. (when region? (goto-char region-start))
  8882. (let ((column (current-indentation)))
  8883. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8884. (beginning-of-line)
  8885. (insert "\n"))
  8886. (save-excursion
  8887. (indent-to column)
  8888. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8889. (when region?
  8890. (when verbatim? (org-escape-code-in-region (point) region-end))
  8891. (goto-char region-end)
  8892. ;; Ignore empty lines at the end of the region.
  8893. (skip-chars-backward " \r\t\n")
  8894. (end-of-line))
  8895. (unless (bolp) (insert "\n"))
  8896. (indent-to column)
  8897. (insert (format "#+end_%s" (car (split-string type))))
  8898. (if (looking-at "[ \t]*$") (replace-match "")
  8899. (insert "\n"))
  8900. (when (and (eobp) (not (bolp))) (insert "\n")))
  8901. (if extended? (end-of-line)
  8902. (forward-line)
  8903. (skip-chars-forward " \t")))))
  8904. ;;;; TODO, DEADLINE, Comments
  8905. (defun org-toggle-comment ()
  8906. "Change the COMMENT state of an entry."
  8907. (interactive)
  8908. (save-excursion
  8909. (org-back-to-heading)
  8910. (let ((case-fold-search nil))
  8911. (looking-at org-complex-heading-regexp))
  8912. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8913. (skip-chars-forward " \t")
  8914. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8915. (if (org-in-commented-heading-p t)
  8916. (delete-region (point)
  8917. (progn (search-forward " " (line-end-position) 'move)
  8918. (skip-chars-forward " \t")
  8919. (point)))
  8920. (insert org-comment-string)
  8921. (unless (eolp) (insert " ")))))
  8922. (defvar org-last-todo-state-is-todo nil
  8923. "This is non-nil when the last TODO state change led to a TODO state.
  8924. If the last change removed the TODO tag or switched to DONE, then
  8925. this is nil.")
  8926. (defvar org-todo-setup-filter-hook nil
  8927. "Hook for functions that pre-filter todo specs.
  8928. Each function takes a todo spec and returns either nil or the spec
  8929. transformed into canonical form." )
  8930. (defvar org-todo-get-default-hook nil
  8931. "Hook for functions that get a default item for todo.
  8932. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8933. nil or a string to be used for the todo mark." )
  8934. (defvar org-agenda-headline-snapshot-before-repeat)
  8935. (defun org-current-effective-time ()
  8936. "Return current time adjusted for `org-extend-today-until' variable."
  8937. (let* ((ct (org-current-time))
  8938. (dct (decode-time ct))
  8939. (ct1
  8940. (cond
  8941. (org-use-last-clock-out-time-as-effective-time
  8942. (or (org-clock-get-last-clock-out-time) ct))
  8943. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8944. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8945. (t ct))))
  8946. ct1))
  8947. (defun org-todo-yesterday (&optional arg)
  8948. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8949. (interactive "P")
  8950. (if (eq major-mode 'org-agenda-mode)
  8951. (apply 'org-agenda-todo-yesterday arg)
  8952. (let* ((org-use-effective-time t)
  8953. (hour (nth 2 (decode-time (org-current-time))))
  8954. (org-extend-today-until (1+ hour)))
  8955. (org-todo arg))))
  8956. (defvar org-block-entry-blocking ""
  8957. "First entry preventing the TODO state change.")
  8958. (defun org-cancel-repeater ()
  8959. "Cancel a repeater by setting its numeric value to zero."
  8960. (interactive)
  8961. (save-excursion
  8962. (org-back-to-heading t)
  8963. (let ((bound1 (point))
  8964. (bound0 (save-excursion (outline-next-heading) (point))))
  8965. (when (and (re-search-forward
  8966. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8967. org-deadline-time-regexp "\\)\\|\\("
  8968. org-ts-regexp "\\)")
  8969. bound0 t)
  8970. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8971. bound1 t))
  8972. (replace-match "0" t nil nil 1)))))
  8973. (defvar org-state)
  8974. (defvar org-blocked-by-checkboxes)
  8975. (defun org-todo (&optional arg)
  8976. "Change the TODO state of an item.
  8977. The state of an item is given by a keyword at the start of the heading,
  8978. like
  8979. *** TODO Write paper
  8980. *** DONE Call mom
  8981. The different keywords are specified in the variable `org-todo-keywords'.
  8982. By default the available states are \"TODO\" and \"DONE\". So, for this
  8983. example: when the item starts with TODO, it is changed to DONE.
  8984. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8985. DONE are present, add TODO at the beginning of the heading.
  8986. You can set up single-character keys to fast-select the new state. See the
  8987. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8988. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8989. and take a
  8990. logging note.
  8991. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8992. next set of TODO \
  8993. keywords (nextset).
  8994. Another way to achieve this is `S-C-<right>'.
  8995. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8996. prefix, circumvent any state blocking.
  8997. With numeric prefix arg, switch to the Nth state.
  8998. With a numeric prefix arg of 0, inhibit note taking for the change.
  8999. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  9000. When called through ELisp, arg is also interpreted in the following way:
  9001. `none' -> empty state
  9002. \"\" -> switch to empty state
  9003. `done' -> switch to DONE
  9004. `nextset' -> switch to the next set of keywords
  9005. `previousset' -> switch to the previous set of keywords
  9006. \"WAITING\" -> switch to the specified keyword, but only if it
  9007. really is a member of `org-todo-keywords'."
  9008. (interactive "P")
  9009. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9010. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9011. 'region-start-level 'region))
  9012. org-loop-over-headlines-in-active-region)
  9013. (org-map-entries
  9014. `(org-todo ,arg)
  9015. org-loop-over-headlines-in-active-region
  9016. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  9017. (when (equal arg '(16)) (setq arg 'nextset))
  9018. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  9019. (let ((org-blocker-hook org-blocker-hook)
  9020. commentp
  9021. case-fold-search)
  9022. (when (equal arg '(64))
  9023. (setq arg nil org-blocker-hook nil))
  9024. (when (and org-blocker-hook
  9025. (or org-inhibit-blocking
  9026. (org-entry-get nil "NOBLOCKING")))
  9027. (setq org-blocker-hook nil))
  9028. (save-excursion
  9029. (catch 'exit
  9030. (org-back-to-heading t)
  9031. (when (org-in-commented-heading-p t)
  9032. (org-toggle-comment)
  9033. (setq commentp t))
  9034. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  9035. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  9036. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  9037. (let* ((match-data (match-data))
  9038. (startpos (copy-marker (line-beginning-position)))
  9039. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  9040. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  9041. (org-log-done org-log-done)
  9042. (org-log-repeat org-log-repeat)
  9043. (org-todo-log-states org-todo-log-states)
  9044. (org-inhibit-logging
  9045. (if (equal arg 0)
  9046. (progn (setq arg nil) 'note) org-inhibit-logging))
  9047. (this (match-string 1))
  9048. (hl-pos (match-beginning 0))
  9049. (head (org-get-todo-sequence-head this))
  9050. (ass (assoc head org-todo-kwd-alist))
  9051. (interpret (nth 1 ass))
  9052. (done-word (nth 3 ass))
  9053. (final-done-word (nth 4 ass))
  9054. (org-last-state (or this ""))
  9055. (completion-ignore-case t)
  9056. (member (member this org-todo-keywords-1))
  9057. (tail (cdr member))
  9058. (org-state (cond
  9059. ((eq arg 'right)
  9060. ;; Next state
  9061. (if this
  9062. (if tail (car tail) nil)
  9063. (car org-todo-keywords-1)))
  9064. ((eq arg 'left)
  9065. ;; Previous state
  9066. (unless (equal member org-todo-keywords-1)
  9067. (if this
  9068. (nth (- (length org-todo-keywords-1)
  9069. (length tail) 2)
  9070. org-todo-keywords-1)
  9071. (org-last org-todo-keywords-1))))
  9072. (arg
  9073. ;; User or caller requests a specific state.
  9074. (cond
  9075. ((equal arg "") nil)
  9076. ((eq arg 'none) nil)
  9077. ((eq arg 'done) (or done-word (car org-done-keywords)))
  9078. ((eq arg 'nextset)
  9079. (or (car (cdr (member head org-todo-heads)))
  9080. (car org-todo-heads)))
  9081. ((eq arg 'previousset)
  9082. (let ((org-todo-heads (reverse org-todo-heads)))
  9083. (or (car (cdr (member head org-todo-heads)))
  9084. (car org-todo-heads))))
  9085. ((car (member arg org-todo-keywords-1)))
  9086. ((stringp arg)
  9087. (user-error "State `%s' not valid in this file" arg))
  9088. ((nth (1- (prefix-numeric-value arg))
  9089. org-todo-keywords-1))))
  9090. ((and org-todo-key-trigger org-use-fast-todo-selection)
  9091. ;; Use fast selection.
  9092. (org-fast-todo-selection this))
  9093. ((null member) (or head (car org-todo-keywords-1)))
  9094. ((equal this final-done-word) nil) ;-> make empty
  9095. ((null tail) nil) ;-> first entry
  9096. ((memq interpret '(type priority))
  9097. (if (eq this-command last-command)
  9098. (car tail)
  9099. (if (> (length tail) 0)
  9100. (or done-word (car org-done-keywords))
  9101. nil)))
  9102. (t
  9103. (car tail))))
  9104. (org-state (or
  9105. (run-hook-with-args-until-success
  9106. 'org-todo-get-default-hook org-state org-last-state)
  9107. org-state))
  9108. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  9109. (change-plist (list :type 'todo-state-change :from this :to org-state
  9110. :position startpos))
  9111. dolog now-done-p)
  9112. (when org-blocker-hook
  9113. (let (org-blocked-by-checkboxes block-reason)
  9114. (setq org-last-todo-state-is-todo
  9115. (not (member this org-done-keywords)))
  9116. (unless (save-excursion
  9117. (save-match-data
  9118. (org-with-wide-buffer
  9119. (run-hook-with-args-until-failure
  9120. 'org-blocker-hook change-plist))))
  9121. (setq block-reason (if org-blocked-by-checkboxes
  9122. "contained checkboxes"
  9123. (format "\"%s\"" org-block-entry-blocking)))
  9124. (if (called-interactively-p 'interactive)
  9125. (user-error "TODO state change from %s to %s blocked (by %s)"
  9126. this org-state block-reason)
  9127. ;; Fail silently.
  9128. (message "TODO state change from %s to %s blocked (by %s)"
  9129. this org-state block-reason)
  9130. (throw 'exit nil)))))
  9131. (store-match-data match-data)
  9132. (replace-match next t t)
  9133. (cond ((equal this org-state)
  9134. (message "TODO state was already %s" (org-trim next)))
  9135. ((not (pos-visible-in-window-p hl-pos))
  9136. (message "TODO state changed to %s" (org-trim next))))
  9137. (unless head
  9138. (setq head (org-get-todo-sequence-head org-state)
  9139. ass (assoc head org-todo-kwd-alist)
  9140. interpret (nth 1 ass)
  9141. done-word (nth 3 ass)
  9142. final-done-word (nth 4 ass)))
  9143. (when (memq arg '(nextset previousset))
  9144. (message "Keyword-Set %d/%d: %s"
  9145. (- (length org-todo-sets) -1
  9146. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  9147. (length org-todo-sets)
  9148. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  9149. (setq org-last-todo-state-is-todo
  9150. (not (member org-state org-done-keywords)))
  9151. (setq now-done-p (and (member org-state org-done-keywords)
  9152. (not (member this org-done-keywords))))
  9153. (and logging (org-local-logging logging))
  9154. (when (or (and (or org-todo-log-states org-log-done)
  9155. (not (eq org-inhibit-logging t))
  9156. (not (memq arg '(nextset previousset))))
  9157. force-log)
  9158. ;; We need to look at recording a time and note.
  9159. (setq dolog (or (if force-log 'note)
  9160. (nth 1 (assoc org-state org-todo-log-states))
  9161. (nth 2 (assoc this org-todo-log-states))))
  9162. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  9163. (setq dolog 'time))
  9164. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  9165. (and org-state
  9166. (member org-state org-not-done-keywords)
  9167. (not (member this org-not-done-keywords))))
  9168. ;; This is now a todo state and was not one before
  9169. ;; If there was a CLOSED time stamp, get rid of it.
  9170. (org-add-planning-info nil nil 'closed))
  9171. (when (and now-done-p org-log-done)
  9172. ;; It is now done, and it was not done before.
  9173. (org-add-planning-info 'closed (org-current-effective-time))
  9174. (when (and (not dolog) (eq 'note org-log-done))
  9175. (org-add-log-setup 'done org-state this 'note)))
  9176. (when (and org-state dolog)
  9177. ;; This is a non-nil state, and we need to log it.
  9178. (org-add-log-setup 'state org-state this dolog)))
  9179. ;; Fixup tag positioning.
  9180. (org-todo-trigger-tag-changes org-state)
  9181. (when org-auto-align-tags (org-align-tags))
  9182. (when org-provide-todo-statistics
  9183. (org-update-parent-todo-statistics))
  9184. (when (bound-and-true-p org-clock-out-when-done)
  9185. (org-clock-out-if-current))
  9186. (run-hooks 'org-after-todo-state-change-hook)
  9187. (when (and arg (not (member org-state org-done-keywords)))
  9188. (setq head (org-get-todo-sequence-head org-state)))
  9189. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  9190. ;; Do we need to trigger a repeat?
  9191. (when now-done-p
  9192. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  9193. ;; This is for the agenda, take a snapshot of the headline.
  9194. (save-match-data
  9195. (setq org-agenda-headline-snapshot-before-repeat
  9196. (org-get-heading))))
  9197. (org-auto-repeat-maybe org-state))
  9198. ;; Fixup cursor location if close to the keyword.
  9199. (when (and (outline-on-heading-p)
  9200. (not (bolp))
  9201. (save-excursion (beginning-of-line 1)
  9202. (looking-at org-todo-line-regexp))
  9203. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  9204. (goto-char (or (match-end 2) (match-end 1)))
  9205. (and (looking-at " ")
  9206. (not (looking-at " *:"))
  9207. (just-one-space)))
  9208. (when org-trigger-hook
  9209. (save-excursion
  9210. (run-hook-with-args 'org-trigger-hook change-plist)))
  9211. (when commentp (org-toggle-comment))))))))
  9212. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  9213. "Block turning an entry into a TODO, using the hierarchy.
  9214. This checks whether the current task should be blocked from state
  9215. changes. Such blocking occurs when:
  9216. 1. The task has children which are not all in a completed state.
  9217. 2. A task has a parent with the property :ORDERED:, and there
  9218. are siblings prior to the current task with incomplete
  9219. status.
  9220. 3. The parent of the task is blocked because it has siblings that should
  9221. be done first, or is child of a block grandparent TODO entry."
  9222. (if (not org-enforce-todo-dependencies)
  9223. t ; if locally turned off don't block
  9224. (catch 'dont-block
  9225. ;; If this is not a todo state change, or if this entry is already DONE,
  9226. ;; do not block
  9227. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9228. (member (plist-get change-plist :from)
  9229. (cons 'done org-done-keywords))
  9230. (member (plist-get change-plist :to)
  9231. (cons 'todo org-not-done-keywords))
  9232. (not (plist-get change-plist :to)))
  9233. (throw 'dont-block t))
  9234. ;; If this task has children, and any are undone, it's blocked
  9235. (save-excursion
  9236. (org-back-to-heading t)
  9237. (let ((this-level (funcall outline-level)))
  9238. (outline-next-heading)
  9239. (let ((child-level (funcall outline-level)))
  9240. (while (and (not (eobp))
  9241. (> child-level this-level))
  9242. ;; this todo has children, check whether they are all
  9243. ;; completed
  9244. (when (and (not (org-entry-is-done-p))
  9245. (org-entry-is-todo-p))
  9246. (setq org-block-entry-blocking (org-get-heading))
  9247. (throw 'dont-block nil))
  9248. (outline-next-heading)
  9249. (setq child-level (funcall outline-level))))))
  9250. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  9251. ;; any previous siblings are undone, it's blocked
  9252. (save-excursion
  9253. (org-back-to-heading t)
  9254. (let* ((pos (point))
  9255. (parent-pos (and (org-up-heading-safe) (point)))
  9256. (case-fold-search nil))
  9257. (unless parent-pos (throw 'dont-block t)) ; no parent
  9258. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9259. (forward-line 1)
  9260. (re-search-forward org-not-done-heading-regexp pos t))
  9261. (setq org-block-entry-blocking (match-string 0))
  9262. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  9263. ;; Search further up the hierarchy, to see if an ancestor is blocked
  9264. (while t
  9265. (goto-char parent-pos)
  9266. (unless (looking-at org-not-done-heading-regexp)
  9267. (throw 'dont-block t)) ; do not block, parent is not a TODO
  9268. (setq pos (point))
  9269. (setq parent-pos (and (org-up-heading-safe) (point)))
  9270. (unless parent-pos (throw 'dont-block t)) ; no parent
  9271. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9272. (forward-line 1)
  9273. (re-search-forward org-not-done-heading-regexp pos t)
  9274. (setq org-block-entry-blocking (org-get-heading)))
  9275. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  9276. (defcustom org-track-ordered-property-with-tag nil
  9277. "Should the ORDERED property also be shown as a tag?
  9278. The ORDERED property decides if an entry should require subtasks to be
  9279. completed in sequence. Since a property is not very visible, setting
  9280. this option means that toggling the ORDERED property with the command
  9281. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  9282. not relevant for the behavior, but it makes things more visible.
  9283. Note that toggling the tag with tags commands will not change the property
  9284. and therefore not influence behavior!
  9285. This can be t, meaning the tag ORDERED should be used. It can also be a
  9286. string to select a different tag for this task."
  9287. :group 'org-todo
  9288. :type '(choice
  9289. (const :tag "No tracking" nil)
  9290. (const :tag "Track with ORDERED tag" t)
  9291. (string :tag "Use other tag")))
  9292. (defun org-toggle-ordered-property ()
  9293. "Toggle the ORDERED property of the current entry.
  9294. For better visibility, you can track the value of this property with a tag.
  9295. See variable `org-track-ordered-property-with-tag'."
  9296. (interactive)
  9297. (let* ((t1 org-track-ordered-property-with-tag)
  9298. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  9299. (save-excursion
  9300. (org-back-to-heading)
  9301. (if (org-entry-get nil "ORDERED")
  9302. (progn
  9303. (org-delete-property "ORDERED")
  9304. (and tag (org-toggle-tag tag 'off))
  9305. (message "Subtasks can be completed in arbitrary order"))
  9306. (org-entry-put nil "ORDERED" "t")
  9307. (and tag (org-toggle-tag tag 'on))
  9308. (message "Subtasks must be completed in sequence")))))
  9309. (defun org-block-todo-from-checkboxes (change-plist)
  9310. "Block turning an entry into a TODO, using checkboxes.
  9311. This checks whether the current task should be blocked from state
  9312. changes because there are unchecked boxes in this entry."
  9313. (if (not org-enforce-todo-checkbox-dependencies)
  9314. t ; if locally turned off don't block
  9315. (catch 'dont-block
  9316. ;; If this is not a todo state change, or if this entry is already DONE,
  9317. ;; do not block
  9318. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9319. (member (plist-get change-plist :from)
  9320. (cons 'done org-done-keywords))
  9321. (member (plist-get change-plist :to)
  9322. (cons 'todo org-not-done-keywords))
  9323. (not (plist-get change-plist :to)))
  9324. (throw 'dont-block t))
  9325. ;; If this task has checkboxes that are not checked, it's blocked
  9326. (save-excursion
  9327. (org-back-to-heading t)
  9328. (let ((beg (point)) end)
  9329. (outline-next-heading)
  9330. (setq end (point))
  9331. (goto-char beg)
  9332. (when (org-list-search-forward
  9333. (concat (org-item-beginning-re)
  9334. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  9335. "\\[[- ]\\]")
  9336. end t)
  9337. (when (boundp 'org-blocked-by-checkboxes)
  9338. (setq org-blocked-by-checkboxes t))
  9339. (throw 'dont-block nil))))
  9340. t))) ; do not block
  9341. (defun org-entry-blocked-p ()
  9342. "Non-nil if entry at point is blocked."
  9343. (and (not (org-entry-get nil "NOBLOCKING"))
  9344. (member (org-entry-get nil "TODO") org-not-done-keywords)
  9345. (not (run-hook-with-args-until-failure
  9346. 'org-blocker-hook
  9347. (list :type 'todo-state-change
  9348. :position (point)
  9349. :from 'todo
  9350. :to 'done)))))
  9351. (defun org-update-statistics-cookies (all)
  9352. "Update the statistics cookie, either from TODO or from checkboxes.
  9353. This should be called with the cursor in a line with a statistics
  9354. cookie. When called with a \\[universal-argument] prefix, update
  9355. all statistics cookies in the buffer."
  9356. (interactive "P")
  9357. (if all
  9358. (progn
  9359. (org-update-checkbox-count 'all)
  9360. (org-map-entries 'org-update-parent-todo-statistics))
  9361. (if (not (org-at-heading-p))
  9362. (org-update-checkbox-count)
  9363. (let ((pos (point-marker))
  9364. end l1 l2)
  9365. (ignore-errors (org-back-to-heading t))
  9366. (if (not (org-at-heading-p))
  9367. (org-update-checkbox-count)
  9368. (setq l1 (org-outline-level))
  9369. (setq end (save-excursion
  9370. (outline-next-heading)
  9371. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  9372. (point)))
  9373. (if (and (save-excursion
  9374. (re-search-forward
  9375. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  9376. (not (save-excursion (re-search-forward
  9377. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  9378. (org-update-checkbox-count)
  9379. (if (and l2 (> l2 l1))
  9380. (progn
  9381. (goto-char end)
  9382. (org-update-parent-todo-statistics))
  9383. (goto-char pos)
  9384. (beginning-of-line 1)
  9385. (while (re-search-forward
  9386. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  9387. (point-at-eol) t)
  9388. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  9389. (goto-char pos)
  9390. (move-marker pos nil)))))
  9391. (defvar org-entry-property-inherited-from) ;; defined below
  9392. (defun org-update-parent-todo-statistics ()
  9393. "Update any statistics cookie in the parent of the current headline.
  9394. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  9395. the entire subtree and this will travel up the hierarchy and update
  9396. statistics everywhere."
  9397. (let* ((prop (save-excursion (org-up-heading-safe)
  9398. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  9399. (recursive (or (not org-hierarchical-todo-statistics)
  9400. (and prop (string-match "\\<recursive\\>" prop))))
  9401. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  9402. 0))
  9403. (first t)
  9404. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  9405. level ltoggle l1 new ndel
  9406. (cnt-all 0) (cnt-done 0) is-percent kwd
  9407. checkbox-beg cookie-present)
  9408. (catch 'exit
  9409. (save-excursion
  9410. (beginning-of-line 1)
  9411. (setq ltoggle (funcall outline-level))
  9412. ;; Three situations are to consider:
  9413. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  9414. ;; to the top-level ancestor on the headline;
  9415. ;; 2. If parent has "recursive" property, repeat up to the
  9416. ;; headline setting that property, taking inheritance into
  9417. ;; account;
  9418. ;; 3. Else, move up to direct parent and proceed only once.
  9419. (while (and (setq level (org-up-heading-safe))
  9420. (or recursive first)
  9421. (>= (point) lim))
  9422. (setq first nil cookie-present nil)
  9423. (unless (and level
  9424. (not (string-match
  9425. "\\<checkbox\\>"
  9426. (downcase (or (org-entry-get nil "COOKIE_DATA")
  9427. "")))))
  9428. (throw 'exit nil))
  9429. (while (re-search-forward box-re (point-at-eol) t)
  9430. (setq cnt-all 0 cnt-done 0 cookie-present t)
  9431. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  9432. (save-match-data
  9433. (unless (outline-next-heading) (throw 'exit nil))
  9434. (while (and (looking-at org-complex-heading-regexp)
  9435. (> (setq l1 (length (match-string 1))) level))
  9436. (setq kwd (and (or recursive (= l1 ltoggle))
  9437. (match-string 2)))
  9438. (if (or (eq org-provide-todo-statistics 'all-headlines)
  9439. (and (eq org-provide-todo-statistics t)
  9440. (or (member kwd org-done-keywords)))
  9441. (and (listp org-provide-todo-statistics)
  9442. (stringp (car org-provide-todo-statistics))
  9443. (or (member kwd org-provide-todo-statistics)
  9444. (member kwd org-done-keywords)))
  9445. (and (listp org-provide-todo-statistics)
  9446. (listp (car org-provide-todo-statistics))
  9447. (or (member kwd (car org-provide-todo-statistics))
  9448. (and (member kwd org-done-keywords)
  9449. (member kwd (cadr org-provide-todo-statistics))))))
  9450. (setq cnt-all (1+ cnt-all))
  9451. (and (eq org-provide-todo-statistics t)
  9452. kwd
  9453. (setq cnt-all (1+ cnt-all))))
  9454. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  9455. (member kwd org-done-keywords))
  9456. (and (listp org-provide-todo-statistics)
  9457. (listp (car org-provide-todo-statistics))
  9458. (member kwd org-done-keywords)
  9459. (member kwd (cadr org-provide-todo-statistics)))
  9460. (and (listp org-provide-todo-statistics)
  9461. (stringp (car org-provide-todo-statistics))
  9462. (member kwd org-done-keywords)))
  9463. (setq cnt-done (1+ cnt-done)))
  9464. (outline-next-heading)))
  9465. (setq new
  9466. (if is-percent
  9467. (format "[%d%%]" (floor (* 100.0 cnt-done)
  9468. (max 1 cnt-all)))
  9469. (format "[%d/%d]" cnt-done cnt-all))
  9470. ndel (- (match-end 0) checkbox-beg))
  9471. (goto-char checkbox-beg)
  9472. (insert new)
  9473. (delete-region (point) (+ (point) ndel))
  9474. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  9475. (when cookie-present
  9476. (run-hook-with-args 'org-after-todo-statistics-hook
  9477. cnt-done (- cnt-all cnt-done))))))
  9478. (run-hooks 'org-todo-statistics-hook)))
  9479. (defvar org-after-todo-statistics-hook nil
  9480. "Hook that is called after a TODO statistics cookie has been updated.
  9481. Each function is called with two arguments: the number of not-done entries
  9482. and the number of done entries.
  9483. For example, the following function, when added to this hook, will switch
  9484. an entry to DONE when all children are done, and back to TODO when new
  9485. entries are set to a TODO status. Note that this hook is only called
  9486. when there is a statistics cookie in the headline!
  9487. (defun org-summary-todo (n-done n-not-done)
  9488. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9489. (let (org-log-done org-log-states) ; turn off logging
  9490. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  9491. ")
  9492. (defvar org-todo-statistics-hook nil
  9493. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9494. This hook runs even if there is no statistics cookie present, in which case
  9495. `org-after-todo-statistics-hook' would not run.")
  9496. (defun org-todo-trigger-tag-changes (state)
  9497. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9498. (let ((l org-todo-state-tags-triggers)
  9499. changes)
  9500. (when (or (not state) (equal state ""))
  9501. (setq changes (append changes (cdr (assoc "" l)))))
  9502. (when (and (stringp state) (> (length state) 0))
  9503. (setq changes (append changes (cdr (assoc state l)))))
  9504. (when (member state org-not-done-keywords)
  9505. (setq changes (append changes (cdr (assq 'todo l)))))
  9506. (when (member state org-done-keywords)
  9507. (setq changes (append changes (cdr (assq 'done l)))))
  9508. (dolist (c changes)
  9509. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9510. (defun org-local-logging (value)
  9511. "Get logging settings from a property VALUE."
  9512. ;; Directly set the variables, they are already local.
  9513. (setq org-log-done nil
  9514. org-log-repeat nil
  9515. org-todo-log-states nil)
  9516. (dolist (w (split-string value))
  9517. (let (a)
  9518. (cond
  9519. ((setq a (assoc w org-startup-options))
  9520. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9521. (set (nth 1 a) (nth 2 a))))
  9522. ((setq a (org-extract-log-state-settings w))
  9523. (and (member (car a) org-todo-keywords-1)
  9524. (push a org-todo-log-states)))))))
  9525. (defun org-get-todo-sequence-head (kwd)
  9526. "Return the head of the TODO sequence to which KWD belongs.
  9527. If KWD is not set, check if there is a text property remembering the
  9528. right sequence."
  9529. (let (p)
  9530. (cond
  9531. ((not kwd)
  9532. (or (get-text-property (point-at-bol) 'org-todo-head)
  9533. (progn
  9534. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9535. nil (point-at-eol)))
  9536. (get-text-property p 'org-todo-head))))
  9537. ((not (member kwd org-todo-keywords-1))
  9538. (car org-todo-keywords-1))
  9539. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9540. (defun org-fast-todo-selection (&optional current-state)
  9541. "Fast TODO keyword selection with single keys.
  9542. Returns the new TODO keyword, or nil if no state change should occur.
  9543. When CURRENT-STATE is given and selection letters are not unique globally,
  9544. prefer a state in the current sequence over on in another sequence."
  9545. (let* ((fulltable org-todo-key-alist)
  9546. (head (org-get-todo-sequence-head current-state))
  9547. (done-keywords org-done-keywords) ;; needed for the faces.
  9548. (maxlen (apply 'max (mapcar
  9549. (lambda (x)
  9550. (if (stringp (car x)) (string-width (car x)) 0))
  9551. fulltable)))
  9552. (expert (equal org-use-fast-todo-selection 'expert))
  9553. (prompt "")
  9554. (fwidth (+ maxlen 3 1 3))
  9555. (ncol (/ (- (window-width) 4) fwidth))
  9556. tg cnt e c tbl subtable
  9557. groups ingroup in-current-sequence)
  9558. (save-excursion
  9559. (save-window-excursion
  9560. (if expert
  9561. (set-buffer (get-buffer-create " *Org todo*"))
  9562. (delete-other-windows)
  9563. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9564. (org-switch-to-buffer-other-window " *Org todo*"))
  9565. (erase-buffer)
  9566. (setq-local org-done-keywords done-keywords)
  9567. (setq tbl fulltable cnt 0)
  9568. (while (setq e (pop tbl))
  9569. (cond
  9570. ((equal e '(:startgroup))
  9571. (push '() groups) (setq ingroup t)
  9572. (unless (= cnt 0)
  9573. (setq cnt 0)
  9574. (insert "\n"))
  9575. (setq prompt (concat prompt "{"))
  9576. (insert "{ "))
  9577. ((equal e '(:endgroup))
  9578. (setq ingroup nil cnt 0 in-current-sequence nil)
  9579. (setq prompt (concat prompt "}"))
  9580. (insert "}\n"))
  9581. ((equal e '(:newline))
  9582. (unless (= cnt 0)
  9583. (setq cnt 0)
  9584. (insert "\n")
  9585. (setq e (car tbl))
  9586. (while (equal (car tbl) '(:newline))
  9587. (insert "\n")
  9588. (setq tbl (cdr tbl)))))
  9589. (t
  9590. (setq tg (car e) c (cdr e))
  9591. (if (equal tg head) (setq in-current-sequence t))
  9592. (when ingroup (push tg (car groups)))
  9593. (when in-current-sequence (push e subtable))
  9594. (setq tg (org-add-props tg nil 'face
  9595. (org-get-todo-face tg)))
  9596. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9597. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9598. (insert "[" c "] " tg (make-string
  9599. (- fwidth 4 (length tg)) ?\ ))
  9600. (when (and (= (setq cnt (1+ cnt)) ncol)
  9601. ;; Avoid lines with just a closing delimiter.
  9602. (not (equal (car tbl) '(:endgroup))))
  9603. (insert "\n")
  9604. (when ingroup (insert " "))
  9605. (setq cnt 0)))))
  9606. (insert "\n")
  9607. (goto-char (point-min))
  9608. (unless expert (org-fit-window-to-buffer))
  9609. (message (concat "[a-z..]:Set [SPC]:clear"
  9610. (if expert (concat "\n" prompt) "")))
  9611. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9612. (setq subtable (nreverse subtable))
  9613. (cond
  9614. ((or (= c ?\C-g)
  9615. (and (= c ?q) (not (rassoc c fulltable))))
  9616. (setq quit-flag t))
  9617. ((= c ?\ ) nil)
  9618. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9619. tg (car e))
  9620. tg)
  9621. (t (setq quit-flag t)))))))
  9622. (defun org-entry-is-todo-p ()
  9623. (member (org-get-todo-state) org-not-done-keywords))
  9624. (defun org-entry-is-done-p ()
  9625. (member (org-get-todo-state) org-done-keywords))
  9626. (defun org-get-todo-state ()
  9627. "Return the TODO keyword of the current subtree."
  9628. (save-excursion
  9629. (org-back-to-heading t)
  9630. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9631. (match-end 2)
  9632. (match-string 2))))
  9633. (defun org-at-date-range-p (&optional inactive-ok)
  9634. "Non-nil if point is inside a date range.
  9635. When optional argument INACTIVE-OK is non-nil, also consider
  9636. inactive time ranges.
  9637. When this function returns a non-nil value, match data is set
  9638. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9639. on INACTIVE-OK."
  9640. (interactive)
  9641. (save-excursion
  9642. (catch 'exit
  9643. (let ((pos (point)))
  9644. (skip-chars-backward "^[<\r\n")
  9645. (skip-chars-backward "<[")
  9646. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9647. (>= (match-end 0) pos)
  9648. (throw 'exit t))
  9649. (skip-chars-backward "^<[\r\n")
  9650. (skip-chars-backward "<[")
  9651. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9652. (>= (match-end 0) pos)
  9653. (throw 'exit t)))
  9654. nil)))
  9655. (defun org-get-repeat (&optional timestamp)
  9656. "Check if there is a time-stamp with repeater in this entry.
  9657. Return the repeater, as a string, or nil. Also return nil when
  9658. this function is called before first heading.
  9659. When optional argument TIMESTAMP is a string, extract the
  9660. repeater from there instead."
  9661. (save-match-data
  9662. (cond (timestamp
  9663. (and (string-match org-repeat-re timestamp)
  9664. (match-string-no-properties 1 timestamp)))
  9665. ((org-before-first-heading-p) nil)
  9666. (t
  9667. (save-excursion
  9668. (org-back-to-heading t)
  9669. (let ((end (org-entry-end-position)))
  9670. (catch :repeat
  9671. (while (re-search-forward org-repeat-re end t)
  9672. (when (save-match-data (org-at-timestamp-p 'agenda))
  9673. (throw :repeat (match-string-no-properties 1)))))))))))
  9674. (defvar org-last-changed-timestamp)
  9675. (defvar org-last-inserted-timestamp)
  9676. (defvar org-log-post-message)
  9677. (defvar org-log-note-purpose)
  9678. (defvar org-log-note-how nil)
  9679. (defvar org-log-note-extra)
  9680. (defun org-auto-repeat-maybe (done-word)
  9681. "Check if the current headline contains a repeated time-stamp.
  9682. If yes, set TODO state back to what it was and change the base date
  9683. of repeating deadline/scheduled time stamps to new date.
  9684. This function is run automatically after each state change to a DONE state."
  9685. (let* ((repeat (org-get-repeat))
  9686. (aa (assoc org-last-state org-todo-kwd-alist))
  9687. (interpret (nth 1 aa))
  9688. (head (nth 2 aa))
  9689. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9690. (msg "Entry repeats: ")
  9691. (org-log-done nil)
  9692. (org-todo-log-states nil)
  9693. (end (copy-marker (org-entry-end-position))))
  9694. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9695. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9696. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9697. (and (stringp org-todo-repeat-to-state)
  9698. org-todo-repeat-to-state)
  9699. (and org-todo-repeat-to-state org-last-state))))
  9700. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9701. to-state)
  9702. ((eq interpret 'type) org-last-state)
  9703. (head)
  9704. (t 'none))))
  9705. (org-back-to-heading t)
  9706. (org-add-planning-info nil nil 'closed)
  9707. ;; When `org-log-repeat' is non-nil or entry contains
  9708. ;; a clock, set LAST_REPEAT property.
  9709. (when (or org-log-repeat
  9710. (catch :clock
  9711. (save-excursion
  9712. (while (re-search-forward org-clock-line-re end t)
  9713. (when (org-at-clock-log-p) (throw :clock t))))))
  9714. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9715. (org-time-stamp-format t t))))
  9716. (when org-log-repeat
  9717. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  9718. (memq 'org-add-log-note post-command-hook))
  9719. ;; We are already setup for some record.
  9720. (when (eq org-log-repeat 'note)
  9721. ;; Make sure we take a note, not only a time stamp.
  9722. (setq org-log-note-how 'note))
  9723. ;; Set up for taking a record.
  9724. (org-add-log-setup 'state
  9725. (or done-word (car org-done-keywords))
  9726. org-last-state
  9727. org-log-repeat)))
  9728. ;; Time-stamps without a repeater are usually skipped. However,
  9729. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9730. ;; longer relevant.
  9731. (save-excursion
  9732. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9733. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9734. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9735. ;; Update every time-stamp with a repeater in the entry.
  9736. (let ((planning-re (regexp-opt
  9737. (list org-scheduled-string org-deadline-string))))
  9738. (while (re-search-forward org-repeat-re end t)
  9739. (let* ((ts (match-string 0))
  9740. (type (if (not (org-at-planning-p)) "Plain:"
  9741. (save-excursion
  9742. (re-search-backward
  9743. planning-re (line-beginning-position) t)
  9744. (match-string 0)))))
  9745. (when (and (org-at-timestamp-p 'agenda)
  9746. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9747. (let ((n (string-to-number (match-string 2 ts)))
  9748. (what (match-string 3 ts)))
  9749. (when (equal what "w") (setq n (* n 7) what "d"))
  9750. (when (and (equal what "h")
  9751. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9752. ts)))
  9753. (user-error
  9754. "Cannot repeat in %d hour(s) because no hour has been set"
  9755. n))
  9756. ;; Preparation, see if we need to modify the start
  9757. ;; date for the change.
  9758. (when (match-end 1)
  9759. (let ((time (save-match-data (org-time-string-to-time ts)))
  9760. (repeater-type (match-string 1 ts)))
  9761. (cond
  9762. ((equal "." repeater-type)
  9763. ;; Shift starting date to today.
  9764. (org-timestamp-change (- (org-today) (time-to-days time))
  9765. 'day))
  9766. ((equal "+" repeater-type)
  9767. (let ((nshiftmax 10)
  9768. (nshift 0))
  9769. (while (or (= nshift 0)
  9770. (not (org-time-less-p nil time)))
  9771. (when (= nshiftmax (cl-incf nshift))
  9772. (or (y-or-n-p
  9773. (format "%d repeater intervals were not \
  9774. enough to shift date past today. Continue? "
  9775. nshift))
  9776. (user-error "Abort")))
  9777. (org-timestamp-change n (cdr (assoc what whata)))
  9778. (org-in-regexp org-ts-regexp3)
  9779. (setq ts (match-string 1))
  9780. (setq time
  9781. (save-match-data
  9782. (org-time-string-to-time ts)))))
  9783. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9784. ;; Rematch, so that we have everything in place
  9785. ;; for the real shift.
  9786. (org-in-regexp org-ts-regexp3)
  9787. (setq ts (match-string 1))
  9788. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9789. ts)))))
  9790. (save-excursion
  9791. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9792. (setq msg
  9793. (concat msg type " " org-last-changed-timestamp " ")))))))
  9794. (run-hooks 'org-todo-repeat-hook)
  9795. (setq org-log-post-message msg)
  9796. (message msg))))
  9797. (defun org-show-todo-tree (arg)
  9798. "Make a compact tree which shows all headlines marked with TODO.
  9799. The tree will show the lines where the regexp matches, and all higher
  9800. headlines above the match.
  9801. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9802. With a numeric prefix N, construct a sparse tree for the Nth element
  9803. of `org-todo-keywords-1'."
  9804. (interactive "P")
  9805. (let ((case-fold-search nil)
  9806. (kwd-re
  9807. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9808. ((equal arg '(4))
  9809. (let ((kwd
  9810. (completing-read "Keyword (or KWD1|KWD2|...): "
  9811. (mapcar #'list org-todo-keywords-1))))
  9812. (concat "\\("
  9813. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9814. "\\)\\>")))
  9815. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9816. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9817. org-todo-keywords-1)))
  9818. (t (user-error "Invalid prefix argument: %s" arg)))))
  9819. (message "%d TODO entries found"
  9820. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9821. (defun org--deadline-or-schedule (arg type time)
  9822. "Insert DEADLINE or SCHEDULE information in current entry.
  9823. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9824. `org-schedule' for information about ARG and TIME arguments."
  9825. (let* ((deadline? (eq type 'deadline))
  9826. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9827. (log (if deadline? org-log-redeadline org-log-reschedule))
  9828. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9829. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9830. ;; Save repeater cookie from either TIME or current scheduled
  9831. ;; time stamp. We are going to insert it back at the end of
  9832. ;; the process.
  9833. (repeater (or (and (org-string-nw-p time)
  9834. ;; We use `org-repeat-re' because we need
  9835. ;; to tell the difference between a real
  9836. ;; repeater and a time delta, e.g. "+2d".
  9837. (string-match org-repeat-re time)
  9838. (match-string 1 time))
  9839. (and (org-string-nw-p old-date)
  9840. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9841. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9842. old-date)
  9843. (match-string 1 old-date)))))
  9844. (pcase arg
  9845. (`(4)
  9846. (if (not old-date)
  9847. (message (if deadline? "Entry had no deadline to remove"
  9848. "Entry was not scheduled"))
  9849. (when (and old-date log)
  9850. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9851. nil old-date log))
  9852. (org-remove-timestamp-with-keyword keyword)
  9853. (message (if deadline? "Entry no longer has a deadline."
  9854. "Entry is no longer scheduled."))))
  9855. (`(16)
  9856. (save-excursion
  9857. (org-back-to-heading t)
  9858. (let ((regexp (if deadline? org-deadline-time-regexp
  9859. org-scheduled-time-regexp)))
  9860. (if (not (re-search-forward regexp (line-end-position 2) t))
  9861. (user-error (if deadline? "No deadline information to update"
  9862. "No scheduled information to update"))
  9863. (let* ((rpl0 (match-string 1))
  9864. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9865. (msg (if deadline? "Warn starting from" "Delay until")))
  9866. (replace-match
  9867. (concat keyword
  9868. " <" rpl
  9869. (format " -%dd"
  9870. (abs (- (time-to-days
  9871. (save-match-data
  9872. (org-read-date
  9873. nil t nil msg old-date-time)))
  9874. (time-to-days old-date-time))))
  9875. ">") t t))))))
  9876. (_
  9877. (org-add-planning-info type time 'closed)
  9878. (when (and old-date
  9879. log
  9880. (not (equal old-date org-last-inserted-timestamp)))
  9881. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9882. org-last-inserted-timestamp
  9883. old-date
  9884. log))
  9885. (when repeater
  9886. (save-excursion
  9887. (org-back-to-heading t)
  9888. (when (re-search-forward
  9889. (concat keyword " " org-last-inserted-timestamp)
  9890. (line-end-position 2)
  9891. t)
  9892. (goto-char (1- (match-end 0)))
  9893. (insert " " repeater)
  9894. (setq org-last-inserted-timestamp
  9895. (concat (substring org-last-inserted-timestamp 0 -1)
  9896. " " repeater
  9897. (substring org-last-inserted-timestamp -1))))))
  9898. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9899. org-last-inserted-timestamp)))))
  9900. (defun org-deadline (arg &optional time)
  9901. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  9902. With one universal prefix argument, remove any deadline from the item.
  9903. With two universal prefix arguments, prompt for a warning delay.
  9904. With argument TIME, set the deadline at the corresponding date. TIME
  9905. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9906. (interactive "P")
  9907. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9908. (org-map-entries
  9909. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9910. nil
  9911. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9912. 'region-start-level
  9913. 'region)
  9914. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9915. (org--deadline-or-schedule arg 'deadline time)))
  9916. (defun org-schedule (arg &optional time)
  9917. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  9918. With one universal prefix argument, remove any scheduling date from the item.
  9919. With two universal prefix arguments, prompt for a delay cookie.
  9920. With argument TIME, scheduled at the corresponding date. TIME can
  9921. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9922. (interactive "P")
  9923. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9924. (org-map-entries
  9925. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9926. nil
  9927. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9928. 'region-start-level
  9929. 'region)
  9930. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9931. (org--deadline-or-schedule arg 'scheduled time)))
  9932. (defun org-get-scheduled-time (pom &optional inherit)
  9933. "Get the scheduled time as a time tuple, of a format suitable
  9934. for calling org-schedule with, or if there is no scheduling,
  9935. returns nil."
  9936. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9937. (when time
  9938. (org-time-string-to-time time))))
  9939. (defun org-get-deadline-time (pom &optional inherit)
  9940. "Get the deadline as a time tuple, of a format suitable for
  9941. calling org-deadline with, or if there is no scheduling, returns
  9942. nil."
  9943. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9944. (when time
  9945. (org-time-string-to-time time))))
  9946. (defun org-remove-timestamp-with-keyword (keyword)
  9947. "Remove all time stamps with KEYWORD in the current entry."
  9948. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9949. beg)
  9950. (save-excursion
  9951. (org-back-to-heading t)
  9952. (setq beg (point))
  9953. (outline-next-heading)
  9954. (while (re-search-backward re beg t)
  9955. (replace-match "")
  9956. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9957. (equal (char-before) ?\ ))
  9958. (backward-delete-char 1)
  9959. (when (string-match "^[ \t]*$" (buffer-substring
  9960. (point-at-bol) (point-at-eol)))
  9961. (delete-region (point-at-bol)
  9962. (min (point-max) (1+ (point-at-eol))))))))))
  9963. (defvar org-time-was-given) ; dynamically scoped parameter
  9964. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9965. (defun org-at-planning-p ()
  9966. "Non-nil when point is on a planning info line."
  9967. ;; This is as accurate and faster than `org-element-at-point' since
  9968. ;; planning info location is fixed in the section.
  9969. (org-with-wide-buffer
  9970. (beginning-of-line)
  9971. (and (looking-at-p org-planning-line-re)
  9972. (eq (point)
  9973. (ignore-errors
  9974. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9975. (org-back-to-heading t)
  9976. (org-with-limited-levels (org-back-to-heading t)))
  9977. (line-beginning-position 2))))))
  9978. (defun org-add-planning-info (what &optional time &rest remove)
  9979. "Insert new timestamp with keyword in the planning line.
  9980. WHAT indicates what kind of time stamp to add. It is a symbol
  9981. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9982. the time to use. If none is given, the user is prompted for
  9983. a date. REMOVE indicates what kind of entries to remove. An old
  9984. WHAT entry will also be removed."
  9985. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9986. (catch 'exit
  9987. (when (and (memq what '(scheduled deadline))
  9988. (or (not time)
  9989. (and (stringp time)
  9990. (string-match "^[-+]+[0-9]" time))))
  9991. ;; Try to get a default date/time from existing timestamp
  9992. (save-excursion
  9993. (org-back-to-heading t)
  9994. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9995. (when (re-search-forward (if (eq what 'scheduled)
  9996. org-scheduled-time-regexp
  9997. org-deadline-time-regexp)
  9998. end t)
  9999. (setq ts (match-string 1)
  10000. default-time (org-time-string-to-time ts)
  10001. default-input (and ts (org-get-compact-tod ts)))))))
  10002. (when what
  10003. (setq time
  10004. (if (stringp time)
  10005. ;; This is a string (relative or absolute), set
  10006. ;; proper date.
  10007. (apply #'encode-time
  10008. (org-read-date-analyze
  10009. time default-time (decode-time default-time)))
  10010. ;; If necessary, get the time from the user
  10011. (or time (org-read-date nil 'to-time nil
  10012. (cl-case what
  10013. (deadline "DEADLINE")
  10014. (scheduled "SCHEDULED")
  10015. (otherwise nil))
  10016. default-time default-input)))))
  10017. (org-with-wide-buffer
  10018. (org-back-to-heading t)
  10019. (forward-line)
  10020. (unless (bolp) (insert "\n"))
  10021. (cond ((looking-at-p org-planning-line-re)
  10022. ;; Move to current indentation.
  10023. (skip-chars-forward " \t")
  10024. ;; Check if we have to remove something.
  10025. (dolist (type (if what (cons what remove) remove))
  10026. (save-excursion
  10027. (when (re-search-forward
  10028. (cl-case type
  10029. (closed org-closed-time-regexp)
  10030. (deadline org-deadline-time-regexp)
  10031. (scheduled org-scheduled-time-regexp)
  10032. (otherwise
  10033. (error "Invalid planning type: %s" type)))
  10034. (line-end-position) t)
  10035. ;; Delete until next keyword or end of line.
  10036. (delete-region
  10037. (match-beginning 0)
  10038. (if (re-search-forward org-keyword-time-not-clock-regexp
  10039. (line-end-position)
  10040. t)
  10041. (match-beginning 0)
  10042. (line-end-position))))))
  10043. ;; If there is nothing more to add and no more keyword
  10044. ;; is left, remove the line completely.
  10045. (if (and (looking-at-p "[ \t]*$") (not what))
  10046. (delete-region (line-beginning-position)
  10047. (line-beginning-position 2))
  10048. ;; If we removed last keyword, do not leave trailing
  10049. ;; white space at the end of line.
  10050. (let ((p (point)))
  10051. (save-excursion
  10052. (end-of-line)
  10053. (unless (= (skip-chars-backward " \t" p) 0)
  10054. (delete-region (point) (line-end-position)))))))
  10055. ((not what) (throw 'exit nil)) ; Nothing to do.
  10056. (t (insert-before-markers "\n")
  10057. (backward-char 1)
  10058. (when org-adapt-indentation
  10059. (indent-to-column (1+ (org-outline-level))))))
  10060. (when what
  10061. ;; Insert planning keyword.
  10062. (insert (cl-case what
  10063. (closed org-closed-string)
  10064. (deadline org-deadline-string)
  10065. (scheduled org-scheduled-string)
  10066. (otherwise (error "Invalid planning type: %s" what)))
  10067. " ")
  10068. ;; Insert associated timestamp.
  10069. (let ((ts (org-insert-time-stamp
  10070. time
  10071. (or org-time-was-given
  10072. (and (eq what 'closed) org-log-done-with-time))
  10073. (eq what 'closed)
  10074. nil nil (list org-end-time-was-given))))
  10075. (unless (eolp) (insert " "))
  10076. ts))))))
  10077. (defvar org-log-note-marker (make-marker)
  10078. "Marker pointing at the entry where the note is to be inserted.")
  10079. (defvar org-log-note-purpose nil)
  10080. (defvar org-log-note-state nil)
  10081. (defvar org-log-note-previous-state nil)
  10082. (defvar org-log-note-extra nil)
  10083. (defvar org-log-note-window-configuration nil)
  10084. (defvar org-log-note-return-to (make-marker))
  10085. (defvar org-log-note-effective-time nil
  10086. "Remembered current time so that dynamically scoped
  10087. `org-extend-today-until' affects timestamps in state change log")
  10088. (defvar org-log-post-message nil
  10089. "Message to be displayed after a log note has been stored.
  10090. The auto-repeater uses this.")
  10091. (defun org-add-note ()
  10092. "Add a note to the current entry.
  10093. This is done in the same way as adding a state change note."
  10094. (interactive)
  10095. (org-add-log-setup 'note))
  10096. (defun org-log-beginning (&optional create)
  10097. "Return expected start of log notes in current entry.
  10098. When optional argument CREATE is non-nil, the function creates
  10099. a drawer to store notes, if necessary. Returned position ignores
  10100. narrowing."
  10101. (org-with-wide-buffer
  10102. (let ((drawer (org-log-into-drawer)))
  10103. (cond
  10104. (drawer
  10105. (org-end-of-meta-data)
  10106. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  10107. (end (if (org-at-heading-p) (point)
  10108. (save-excursion (outline-next-heading) (point))))
  10109. (case-fold-search t))
  10110. (catch 'exit
  10111. ;; Try to find existing drawer.
  10112. (while (re-search-forward regexp end t)
  10113. (let ((element (org-element-at-point)))
  10114. (when (eq (org-element-type element) 'drawer)
  10115. (let ((cend (org-element-property :contents-end element)))
  10116. (when (and (not org-log-states-order-reversed) cend)
  10117. (goto-char cend)))
  10118. (throw 'exit nil))))
  10119. ;; No drawer found. Create one, if permitted.
  10120. (when create
  10121. (unless (bolp) (insert "\n"))
  10122. (let ((beg (point)))
  10123. (insert ":" drawer ":\n:END:\n")
  10124. (org-indent-region beg (point))
  10125. (org-flag-region
  10126. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  10127. (end-of-line -1)))))
  10128. (t
  10129. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  10130. (skip-chars-forward " \t\n")
  10131. (beginning-of-line)
  10132. (unless org-log-states-order-reversed
  10133. (org-skip-over-state-notes)
  10134. (skip-chars-backward " \t\n")
  10135. (forward-line)))))
  10136. (if (bolp) (point) (line-beginning-position 2))))
  10137. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  10138. "Set up the post command hook to take a note.
  10139. If this is about to TODO state change, the new state is expected in STATE.
  10140. HOW is an indicator what kind of note should be created.
  10141. EXTRA is additional text that will be inserted into the notes buffer."
  10142. (move-marker org-log-note-marker (point))
  10143. (setq org-log-note-purpose purpose
  10144. org-log-note-state state
  10145. org-log-note-previous-state prev-state
  10146. org-log-note-how how
  10147. org-log-note-extra extra
  10148. org-log-note-effective-time (org-current-effective-time))
  10149. (add-hook 'post-command-hook 'org-add-log-note 'append))
  10150. (defun org-skip-over-state-notes ()
  10151. "Skip past the list of State notes in an entry."
  10152. (when (ignore-errors (goto-char (org-in-item-p)))
  10153. (let* ((struct (org-list-struct))
  10154. (prevs (org-list-prevs-alist struct))
  10155. (regexp
  10156. (concat "[ \t]*- +"
  10157. (replace-regexp-in-string
  10158. " +" " +"
  10159. (org-replace-escapes
  10160. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  10161. `(("%d" . ,org-ts-regexp-inactive)
  10162. ("%D" . ,org-ts-regexp)
  10163. ("%s" . "\\(?:\"\\S-+\"\\)?")
  10164. ("%S" . "\\(?:\"\\S-+\"\\)?")
  10165. ("%t" . ,org-ts-regexp-inactive)
  10166. ("%T" . ,org-ts-regexp)
  10167. ("%u" . ".*?")
  10168. ("%U" . ".*?")))))))
  10169. (while (looking-at-p regexp)
  10170. (goto-char (or (org-list-get-next-item (point) struct prevs)
  10171. (org-list-get-item-end (point) struct)))))))
  10172. (defun org-add-log-note (&optional _purpose)
  10173. "Pop up a window for taking a note, and add this note later."
  10174. (remove-hook 'post-command-hook 'org-add-log-note)
  10175. (setq org-log-note-window-configuration (current-window-configuration))
  10176. (delete-other-windows)
  10177. (move-marker org-log-note-return-to (point))
  10178. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  10179. (goto-char org-log-note-marker)
  10180. (org-switch-to-buffer-other-window "*Org Note*")
  10181. (erase-buffer)
  10182. (if (memq org-log-note-how '(time state))
  10183. (org-store-log-note)
  10184. (let ((org-inhibit-startup t)) (org-mode))
  10185. (insert (format "# Insert note for %s.
  10186. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  10187. (cl-case org-log-note-purpose
  10188. (clock-out "stopped clock")
  10189. (done "closed todo item")
  10190. (reschedule "rescheduling")
  10191. (delschedule "no longer scheduled")
  10192. (redeadline "changing deadline")
  10193. (deldeadline "removing deadline")
  10194. (refile "refiling")
  10195. (note "this entry")
  10196. (state
  10197. (format "state change from \"%s\" to \"%s\""
  10198. (or org-log-note-previous-state "")
  10199. (or org-log-note-state "")))
  10200. (t (error "This should not happen")))))
  10201. (when org-log-note-extra (insert org-log-note-extra))
  10202. (setq-local org-finish-function 'org-store-log-note)
  10203. (run-hooks 'org-log-buffer-setup-hook)))
  10204. (defvar org-note-abort nil) ; dynamically scoped
  10205. (defun org-store-log-note ()
  10206. "Finish taking a log note, and insert it to where it belongs."
  10207. (let ((txt (prog1 (buffer-string)
  10208. (kill-buffer)))
  10209. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  10210. lines)
  10211. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  10212. (setq txt (replace-match "" t t txt)))
  10213. (when (string-match "\\s-+\\'" txt)
  10214. (setq txt (replace-match "" t t txt)))
  10215. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  10216. (when (org-string-nw-p note)
  10217. (setq note
  10218. (org-replace-escapes
  10219. note
  10220. (list (cons "%u" (user-login-name))
  10221. (cons "%U" user-full-name)
  10222. (cons "%t" (format-time-string
  10223. (org-time-stamp-format 'long 'inactive)
  10224. org-log-note-effective-time))
  10225. (cons "%T" (format-time-string
  10226. (org-time-stamp-format 'long nil)
  10227. org-log-note-effective-time))
  10228. (cons "%d" (format-time-string
  10229. (org-time-stamp-format nil 'inactive)
  10230. org-log-note-effective-time))
  10231. (cons "%D" (format-time-string
  10232. (org-time-stamp-format nil nil)
  10233. org-log-note-effective-time))
  10234. (cons "%s" (cond
  10235. ((not org-log-note-state) "")
  10236. ((string-match-p org-ts-regexp
  10237. org-log-note-state)
  10238. (format "\"[%s]\""
  10239. (substring org-log-note-state 1 -1)))
  10240. (t (format "\"%s\"" org-log-note-state))))
  10241. (cons "%S"
  10242. (cond
  10243. ((not org-log-note-previous-state) "")
  10244. ((string-match-p org-ts-regexp
  10245. org-log-note-previous-state)
  10246. (format "\"[%s]\""
  10247. (substring
  10248. org-log-note-previous-state 1 -1)))
  10249. (t (format "\"%s\""
  10250. org-log-note-previous-state)))))))
  10251. (when lines (setq note (concat note " \\\\")))
  10252. (push note lines))
  10253. (when (and lines (not org-note-abort))
  10254. (with-current-buffer (marker-buffer org-log-note-marker)
  10255. (org-with-wide-buffer
  10256. ;; Find location for the new note.
  10257. (goto-char org-log-note-marker)
  10258. (set-marker org-log-note-marker nil)
  10259. ;; Note associated to a clock is to be located right after
  10260. ;; the clock. Do not move point.
  10261. (unless (eq org-log-note-purpose 'clock-out)
  10262. (goto-char (org-log-beginning t)))
  10263. ;; Make sure point is at the beginning of an empty line.
  10264. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  10265. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  10266. ;; In an existing list, add a new item at the top level.
  10267. ;; Otherwise, indent line like a regular one.
  10268. (let ((itemp (org-in-item-p)))
  10269. (if itemp
  10270. (indent-line-to
  10271. (let ((struct (save-excursion
  10272. (goto-char itemp) (org-list-struct))))
  10273. (org-list-get-ind (org-list-get-top-point struct) struct)))
  10274. (org-indent-line)))
  10275. (insert (org-list-bullet-string "-") (pop lines))
  10276. (let ((ind (org-list-item-body-column (line-beginning-position))))
  10277. (dolist (line lines)
  10278. (insert "\n")
  10279. (indent-line-to ind)
  10280. (insert line)))
  10281. (message "Note stored")
  10282. (org-back-to-heading t))
  10283. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  10284. ;; from within `org-add-log-note' because `buffer-undo-list'
  10285. ;; is then modified outside of `org-with-remote-undo'.
  10286. (when (eq this-command 'org-agenda-todo)
  10287. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  10288. ;; Don't add undo information when called from `org-agenda-todo'.
  10289. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  10290. (set-window-configuration org-log-note-window-configuration)
  10291. (with-current-buffer (marker-buffer org-log-note-return-to)
  10292. (goto-char org-log-note-return-to))
  10293. (move-marker org-log-note-return-to nil)
  10294. (when org-log-post-message (message "%s" org-log-post-message))))
  10295. (defun org-remove-empty-drawer-at (pos)
  10296. "Remove an empty drawer at position POS.
  10297. POS may also be a marker."
  10298. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  10299. (org-with-wide-buffer
  10300. (goto-char pos)
  10301. (let ((drawer (org-element-at-point)))
  10302. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  10303. (not (org-element-property :contents-begin drawer)))
  10304. (delete-region (org-element-property :begin drawer)
  10305. (progn (goto-char (org-element-property :end drawer))
  10306. (skip-chars-backward " \r\t\n")
  10307. (forward-line)
  10308. (point))))))))
  10309. (defvar org-ts-type nil)
  10310. (defun org-sparse-tree (&optional arg type)
  10311. "Create a sparse tree, prompt for the details.
  10312. This command can create sparse trees. You first need to select the type
  10313. of match used to create the tree:
  10314. t Show all TODO entries.
  10315. T Show entries with a specific TODO keyword.
  10316. m Show entries selected by a tags/property match.
  10317. p Enter a property name and its value (both with completion on existing
  10318. names/values) and show entries with that property.
  10319. r Show entries matching a regular expression (`/' can be used as well).
  10320. b Show deadlines and scheduled items before a date.
  10321. a Show deadlines and scheduled items after a date.
  10322. d Show deadlines due within `org-deadline-warning-days'.
  10323. D Show deadlines and scheduled items between a date range."
  10324. (interactive "P")
  10325. (setq type (or type org-sparse-tree-default-date-type))
  10326. (setq org-ts-type type)
  10327. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  10328. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  10329. \[c]ycle through date types: %s"
  10330. (cl-case type
  10331. (all "all timestamps")
  10332. (scheduled "only scheduled")
  10333. (deadline "only deadline")
  10334. (active "only active timestamps")
  10335. (inactive "only inactive timestamps")
  10336. (closed "with a closed time-stamp")
  10337. (otherwise "scheduled/deadline")))
  10338. (let ((answer (read-char-exclusive)))
  10339. (cl-case answer
  10340. (?c
  10341. (org-sparse-tree
  10342. arg
  10343. (cadr
  10344. (memq type '(nil all scheduled deadline active inactive closed)))))
  10345. (?d (call-interactively 'org-check-deadlines))
  10346. (?b (call-interactively 'org-check-before-date))
  10347. (?a (call-interactively 'org-check-after-date))
  10348. (?D (call-interactively 'org-check-dates-range))
  10349. (?t (call-interactively 'org-show-todo-tree))
  10350. (?T (org-show-todo-tree '(4)))
  10351. (?m (call-interactively 'org-match-sparse-tree))
  10352. ((?p ?P)
  10353. (let* ((kwd (completing-read
  10354. "Property: " (mapcar #'list (org-buffer-property-keys))))
  10355. (value (completing-read
  10356. "Value: " (mapcar #'list (org-property-values kwd)))))
  10357. (unless (string-match "\\`{.*}\\'" value)
  10358. (setq value (concat "\"" value "\"")))
  10359. (org-match-sparse-tree arg (concat kwd "=" value))))
  10360. ((?r ?R ?/) (call-interactively 'org-occur))
  10361. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  10362. (defvar-local org-occur-highlights nil
  10363. "List of overlays used for occur matches.")
  10364. (defvar-local org-occur-parameters nil
  10365. "Parameters of the active org-occur calls.
  10366. This is a list, each call to org-occur pushes as cons cell,
  10367. containing the regular expression and the callback, onto the list.
  10368. The list can contain several entries if `org-occur' has been called
  10369. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  10370. will only contain one set of parameters. When the highlights are
  10371. removed (for example with `C-c C-c', or with the next edit (depending
  10372. on `org-remove-highlights-with-change'), this variable is emptied
  10373. as well.")
  10374. (defun org-occur (regexp &optional keep-previous callback)
  10375. "Make a compact tree which shows all matches of REGEXP.
  10376. The tree will show the lines where the regexp matches, and any other context
  10377. defined in `org-show-context-detail', which see.
  10378. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  10379. done by a previous call to `org-occur' will be kept, to allow stacking of
  10380. calls to this command.
  10381. Optional argument CALLBACK can be a function of no argument. In this case,
  10382. it is called with point at the end of the match, match data being set
  10383. accordingly. Current match is shown only if the return value is non-nil.
  10384. The function must neither move point nor alter narrowing."
  10385. (interactive "sRegexp: \nP")
  10386. (when (equal regexp "")
  10387. (user-error "Regexp cannot be empty"))
  10388. (unless keep-previous
  10389. (org-remove-occur-highlights nil nil t))
  10390. (push (cons regexp callback) org-occur-parameters)
  10391. (let ((cnt 0))
  10392. (save-excursion
  10393. (goto-char (point-min))
  10394. (when (or (not keep-previous) ; do not want to keep
  10395. (not org-occur-highlights)) ; no previous matches
  10396. ;; hide everything
  10397. (org-overview))
  10398. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  10399. (isearch-no-upper-case-p regexp t)
  10400. org-occur-case-fold-search)))
  10401. (while (re-search-forward regexp nil t)
  10402. (when (or (not callback)
  10403. (save-match-data (funcall callback)))
  10404. (setq cnt (1+ cnt))
  10405. (when org-highlight-sparse-tree-matches
  10406. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  10407. (org-show-context 'occur-tree)))))
  10408. (when org-remove-highlights-with-change
  10409. (add-hook 'before-change-functions 'org-remove-occur-highlights
  10410. nil 'local))
  10411. (unless org-sparse-tree-open-archived-trees
  10412. (org-hide-archived-subtrees (point-min) (point-max)))
  10413. (run-hooks 'org-occur-hook)
  10414. (when (called-interactively-p 'interactive)
  10415. (message "%d match(es) for regexp %s" cnt regexp))
  10416. cnt))
  10417. (defun org-occur-next-match (&optional n _reset)
  10418. "Function for `next-error-function' to find sparse tree matches.
  10419. N is the number of matches to move, when negative move backwards.
  10420. This function always goes back to the starting point when no
  10421. match is found."
  10422. (let* ((limit (if (< n 0) (point-min) (point-max)))
  10423. (search-func (if (< n 0)
  10424. 'previous-single-char-property-change
  10425. 'next-single-char-property-change))
  10426. (n (abs n))
  10427. (pos (point))
  10428. p1)
  10429. (catch 'exit
  10430. (while (setq p1 (funcall search-func (point) 'org-type))
  10431. (when (equal p1 limit)
  10432. (goto-char pos)
  10433. (user-error "No more matches"))
  10434. (when (equal (get-char-property p1 'org-type) 'org-occur)
  10435. (setq n (1- n))
  10436. (when (= n 0)
  10437. (goto-char p1)
  10438. (throw 'exit (point))))
  10439. (goto-char p1))
  10440. (goto-char p1)
  10441. (user-error "No more matches"))))
  10442. (defun org-highlight-new-match (beg end)
  10443. "Highlight from BEG to END and mark the highlight is an occur headline."
  10444. (let ((ov (make-overlay beg end)))
  10445. (overlay-put ov 'face 'secondary-selection)
  10446. (overlay-put ov 'org-type 'org-occur)
  10447. (push ov org-occur-highlights)))
  10448. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10449. "Remove the occur highlights from the buffer.
  10450. BEG and END are ignored. If NOREMOVE is nil, remove this function
  10451. from the `before-change-functions' in the current buffer."
  10452. (interactive)
  10453. (unless org-inhibit-highlight-removal
  10454. (mapc #'delete-overlay org-occur-highlights)
  10455. (setq org-occur-highlights nil)
  10456. (setq org-occur-parameters nil)
  10457. (unless noremove
  10458. (remove-hook 'before-change-functions
  10459. 'org-remove-occur-highlights 'local))))
  10460. ;;;; Priorities
  10461. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  10462. "Regular expression matching the priority indicator.")
  10463. (defun org-priority-up ()
  10464. "Increase the priority of the current item."
  10465. (interactive)
  10466. (org-priority 'up))
  10467. (defun org-priority-down ()
  10468. "Decrease the priority of the current item."
  10469. (interactive)
  10470. (org-priority 'down))
  10471. (defun org-priority (&optional action show)
  10472. "Change the priority of an item.
  10473. When called interactively with a `\\[universal-argument]' prefix,
  10474. show the priority in the minibuffer instead of changing it.
  10475. When called programmatically, ACTION can be `set', `up', `down',
  10476. or a character."
  10477. (interactive "P")
  10478. (when show
  10479. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10480. ;; passed the SHOW argument should be removed.
  10481. (warn "`org-priority' called with deprecated SHOW argument"))
  10482. (if (equal action '(4))
  10483. (org-show-priority)
  10484. (unless org-enable-priority-commands
  10485. (user-error "Priority commands are disabled"))
  10486. (setq action (or action 'set))
  10487. (let (current new news have remove)
  10488. (save-excursion
  10489. (org-back-to-heading t)
  10490. (when (looking-at org-priority-regexp)
  10491. (setq current (string-to-char (match-string 2))
  10492. have t))
  10493. (cond
  10494. ((eq action 'remove)
  10495. (setq remove t new ?\ ))
  10496. ((or (eq action 'set)
  10497. (integerp action))
  10498. (if (not (eq action 'set))
  10499. (setq new action)
  10500. (message "Priority %c-%c, SPC to remove: "
  10501. org-highest-priority org-lowest-priority)
  10502. (save-match-data
  10503. (setq new (read-char-exclusive))))
  10504. (when (and (= (upcase org-highest-priority) org-highest-priority)
  10505. (= (upcase org-lowest-priority) org-lowest-priority))
  10506. (setq new (upcase new)))
  10507. (cond ((equal new ?\s) (setq remove t))
  10508. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  10509. (user-error "Priority must be between `%c' and `%c'"
  10510. org-highest-priority org-lowest-priority))))
  10511. ((eq action 'up)
  10512. (setq new (if have
  10513. (1- current) ; normal cycling
  10514. ;; last priority was empty
  10515. (if (eq last-command this-command)
  10516. org-lowest-priority ; wrap around empty to lowest
  10517. ;; default
  10518. (if org-priority-start-cycle-with-default
  10519. org-default-priority
  10520. (1- org-default-priority))))))
  10521. ((eq action 'down)
  10522. (setq new (if have
  10523. (1+ current) ; normal cycling
  10524. ;; last priority was empty
  10525. (if (eq last-command this-command)
  10526. org-highest-priority ; wrap around empty to highest
  10527. ;; default
  10528. (if org-priority-start-cycle-with-default
  10529. org-default-priority
  10530. (1+ org-default-priority))))))
  10531. (t (user-error "Invalid action")))
  10532. (when (or (< (upcase new) org-highest-priority)
  10533. (> (upcase new) org-lowest-priority))
  10534. (if (and (memq action '(up down))
  10535. (not have) (not (eq last-command this-command)))
  10536. ;; `new' is from default priority
  10537. (error
  10538. "The default can not be set, see `org-default-priority' why")
  10539. ;; normal cycling: `new' is beyond highest/lowest priority
  10540. ;; and is wrapped around to the empty priority
  10541. (setq remove t)))
  10542. (setq news (format "%c" new))
  10543. (if have
  10544. (if remove
  10545. (replace-match "" t t nil 1)
  10546. (replace-match news t t nil 2))
  10547. (if remove
  10548. (user-error "No priority cookie found in line")
  10549. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10550. (if (match-end 2)
  10551. (progn
  10552. (goto-char (match-end 2))
  10553. (insert " [#" news "]"))
  10554. (goto-char (match-beginning 3))
  10555. (insert "[#" news "] "))))
  10556. (org-align-tags))
  10557. (if remove
  10558. (message "Priority removed")
  10559. (message "Priority of current item set to %s" news)))))
  10560. (defun org-show-priority ()
  10561. "Show the priority of the current item.
  10562. This priority is composed of the main priority given with the [#A] cookies,
  10563. and by additional input from the age of a schedules or deadline entry."
  10564. (interactive)
  10565. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10566. (org-get-at-bol 'priority)
  10567. (save-excursion
  10568. (save-match-data
  10569. (beginning-of-line)
  10570. (and (looking-at org-heading-regexp)
  10571. (org-get-priority (match-string 0))))))))
  10572. (message "Priority is %d" (if pri pri -1000))))
  10573. (defun org-get-priority (s)
  10574. "Find priority cookie and return priority."
  10575. (save-match-data
  10576. (if (functionp org-get-priority-function)
  10577. (funcall org-get-priority-function s)
  10578. (if (not (string-match org-priority-regexp s))
  10579. (* 1000 (- org-lowest-priority org-default-priority))
  10580. (* 1000 (- org-lowest-priority
  10581. (string-to-char (match-string 2 s))))))))
  10582. ;;;; Tags
  10583. (defvar org-agenda-archives-mode)
  10584. (defvar org-map-continue-from nil
  10585. "Position from where mapping should continue.
  10586. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10587. (defvar org-scanner-tags nil
  10588. "The current tag list while the tags scanner is running.")
  10589. (defvar org-trust-scanner-tags nil
  10590. "Should `org-get-tags' use the tags for the scanner.
  10591. This is for internal dynamical scoping only.
  10592. When this is non-nil, the function `org-get-tags' will return the value
  10593. of `org-scanner-tags' instead of building the list by itself. This
  10594. can lead to large speed-ups when the tags scanner is used in a file with
  10595. many entries, and when the list of tags is retrieved, for example to
  10596. obtain a list of properties. Building the tags list for each entry in such
  10597. a file becomes an N^2 operation - but with this variable set, it scales
  10598. as N.")
  10599. (defvar org--matcher-tags-todo-only nil)
  10600. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10601. "Scan headline tags with inheritance and produce output ACTION.
  10602. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10603. or `agenda' to produce an entry list for an agenda view. It can also be
  10604. a Lisp form or a function that should be called at each matched headline, in
  10605. this case the return value is a list of all return values from these calls.
  10606. MATCHER is a function accepting three arguments, returning
  10607. a non-nil value whenever a given set of tags qualifies a headline
  10608. for inclusion. See `org-make-tags-matcher' for more information.
  10609. As a special case, it can also be set to t (respectively nil) in
  10610. order to match all (respectively none) headline.
  10611. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10612. included in the output.
  10613. START-LEVEL can be a string with asterisks, reducing the scope to
  10614. headlines matching this string."
  10615. (require 'org-agenda)
  10616. (let* ((re (concat "^"
  10617. (if start-level
  10618. ;; Get the correct level to match
  10619. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10620. org-outline-regexp)
  10621. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10622. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10623. (props (list 'face 'default
  10624. 'done-face 'org-agenda-done
  10625. 'undone-face 'default
  10626. 'mouse-face 'highlight
  10627. 'org-not-done-regexp org-not-done-regexp
  10628. 'org-todo-regexp org-todo-regexp
  10629. 'org-complex-heading-regexp org-complex-heading-regexp
  10630. 'help-echo
  10631. (format "mouse-2 or RET jump to Org file %S"
  10632. (abbreviate-file-name
  10633. (or (buffer-file-name (buffer-base-buffer))
  10634. (buffer-name (buffer-base-buffer)))))))
  10635. (org-map-continue-from nil)
  10636. lspos tags tags-list
  10637. (tags-alist (list (cons 0 org-file-tags)))
  10638. (llast 0) rtn rtn1 level category i txt
  10639. todo marker entry priority
  10640. ts-date ts-date-type ts-date-pair)
  10641. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10642. (setq action (list 'lambda nil action)))
  10643. (save-excursion
  10644. (goto-char (point-min))
  10645. (when (eq action 'sparse-tree)
  10646. (org-overview)
  10647. (org-remove-occur-highlights))
  10648. (while (let (case-fold-search)
  10649. (re-search-forward re nil t))
  10650. (setq org-map-continue-from nil)
  10651. (catch :skip
  10652. ;; Ignore closing parts of inline tasks.
  10653. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10654. (throw :skip t))
  10655. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10656. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10657. (goto-char (setq lspos (match-beginning 0)))
  10658. (setq level (org-reduced-level (org-outline-level))
  10659. category (org-get-category))
  10660. (when (eq action 'agenda)
  10661. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10662. ts-date (car ts-date-pair)
  10663. ts-date-type (cdr ts-date-pair)))
  10664. (setq i llast llast level)
  10665. ;; remove tag lists from same and sublevels
  10666. (while (>= i level)
  10667. (when (setq entry (assoc i tags-alist))
  10668. (setq tags-alist (delete entry tags-alist)))
  10669. (setq i (1- i)))
  10670. ;; add the next tags
  10671. (when tags
  10672. (setq tags (org-split-string tags ":")
  10673. tags-alist
  10674. (cons (cons level tags) tags-alist)))
  10675. ;; compile tags for current headline
  10676. (setq tags-list
  10677. (if org-use-tag-inheritance
  10678. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10679. tags)
  10680. org-scanner-tags tags-list)
  10681. (when org-use-tag-inheritance
  10682. (setcdr (car tags-alist)
  10683. (mapcar (lambda (x)
  10684. (setq x (copy-sequence x))
  10685. (org-add-prop-inherited x))
  10686. (cdar tags-alist))))
  10687. (when (and tags org-use-tag-inheritance
  10688. (or (not (eq t org-use-tag-inheritance))
  10689. org-tags-exclude-from-inheritance))
  10690. ;; Selective inheritance, remove uninherited ones.
  10691. (setcdr (car tags-alist)
  10692. (org-remove-uninherited-tags (cdar tags-alist))))
  10693. (when (and
  10694. ;; eval matcher only when the todo condition is OK
  10695. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10696. (if (functionp matcher)
  10697. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10698. (funcall matcher todo tags-list level))
  10699. matcher))
  10700. ;; Call the skipper, but return t if it does not
  10701. ;; skip, so that the `and' form continues evaluating.
  10702. (progn
  10703. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10704. t)
  10705. ;; Check if timestamps are deselecting this entry
  10706. (or (not todo-only)
  10707. (and (member todo org-todo-keywords-1)
  10708. (or (not org-agenda-tags-todo-honor-ignore-options)
  10709. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10710. ;; select this headline
  10711. (cond
  10712. ((eq action 'sparse-tree)
  10713. (and org-highlight-sparse-tree-matches
  10714. (org-get-heading) (match-end 0)
  10715. (org-highlight-new-match
  10716. (match-beginning 1) (match-end 1)))
  10717. (org-show-context 'tags-tree))
  10718. ((eq action 'agenda)
  10719. (setq txt (org-agenda-format-item
  10720. ""
  10721. (concat
  10722. (if (eq org-tags-match-list-sublevels 'indented)
  10723. (make-string (1- level) ?.) "")
  10724. (org-get-heading))
  10725. (make-string level ?\s)
  10726. category
  10727. tags-list)
  10728. priority (org-get-priority txt))
  10729. (goto-char lspos)
  10730. (setq marker (org-agenda-new-marker))
  10731. (org-add-props txt props
  10732. 'org-marker marker 'org-hd-marker marker 'org-category category
  10733. 'todo-state todo
  10734. 'ts-date ts-date
  10735. 'priority priority
  10736. 'type (concat "tagsmatch" ts-date-type))
  10737. (push txt rtn))
  10738. ((functionp action)
  10739. (setq org-map-continue-from nil)
  10740. (save-excursion
  10741. (setq rtn1 (funcall action))
  10742. (push rtn1 rtn)))
  10743. (t (user-error "Invalid action")))
  10744. ;; if we are to skip sublevels, jump to end of subtree
  10745. (unless org-tags-match-list-sublevels
  10746. (org-end-of-subtree t)
  10747. (backward-char 1))))
  10748. ;; Get the correct position from where to continue
  10749. (if org-map-continue-from
  10750. (goto-char org-map-continue-from)
  10751. (and (= (point) lspos) (end-of-line 1)))))
  10752. (when (and (eq action 'sparse-tree)
  10753. (not org-sparse-tree-open-archived-trees))
  10754. (org-hide-archived-subtrees (point-min) (point-max)))
  10755. (nreverse rtn)))
  10756. (defun org-remove-uninherited-tags (tags)
  10757. "Remove all tags that are not inherited from the list TAGS."
  10758. (cond
  10759. ((eq org-use-tag-inheritance t)
  10760. (if org-tags-exclude-from-inheritance
  10761. (org-delete-all org-tags-exclude-from-inheritance tags)
  10762. tags))
  10763. ((not org-use-tag-inheritance) nil)
  10764. ((stringp org-use-tag-inheritance)
  10765. (delq nil (mapcar
  10766. (lambda (x)
  10767. (if (and (string-match org-use-tag-inheritance x)
  10768. (not (member x org-tags-exclude-from-inheritance)))
  10769. x nil))
  10770. tags)))
  10771. ((listp org-use-tag-inheritance)
  10772. (delq nil (mapcar
  10773. (lambda (x)
  10774. (if (member x org-use-tag-inheritance) x nil))
  10775. tags)))))
  10776. (defun org-match-sparse-tree (&optional todo-only match)
  10777. "Create a sparse tree according to tags string MATCH.
  10778. MATCH is a string with match syntax. It can contain a selection
  10779. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10780. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10781. those. See the manual for details.
  10782. If optional argument TODO-ONLY is non-nil, only select lines that
  10783. are also TODO tasks."
  10784. (interactive "P")
  10785. (org-agenda-prepare-buffers (list (current-buffer)))
  10786. (let ((org--matcher-tags-todo-only todo-only))
  10787. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  10788. org--matcher-tags-todo-only)))
  10789. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10790. (defvar org-cached-props nil)
  10791. (defun org-cached-entry-get (pom property)
  10792. (if (or (eq t org-use-property-inheritance)
  10793. (and (stringp org-use-property-inheritance)
  10794. (let ((case-fold-search t))
  10795. (string-match-p org-use-property-inheritance property)))
  10796. (and (listp org-use-property-inheritance)
  10797. (member-ignore-case property org-use-property-inheritance)))
  10798. ;; Caching is not possible, check it directly.
  10799. (org-entry-get pom property 'inherit)
  10800. ;; Get all properties, so we can do complicated checks easily.
  10801. (cdr (assoc-string property
  10802. (or org-cached-props
  10803. (setq org-cached-props (org-entry-properties pom)))
  10804. t))))
  10805. (defun org-global-tags-completion-table (&optional files)
  10806. "Return the list of all tags in all agenda buffer/files.
  10807. Optional FILES argument is a list of files which can be used
  10808. instead of the agenda files."
  10809. (save-excursion
  10810. (org-uniquify
  10811. (delq nil
  10812. (apply #'append
  10813. (mapcar
  10814. (lambda (file)
  10815. (set-buffer (find-file-noselect file))
  10816. (org--tag-add-to-alist
  10817. (org-get-buffer-tags)
  10818. (mapcar (lambda (x)
  10819. (and (stringp (car-safe x))
  10820. (list (car-safe x))))
  10821. org-current-tag-alist)))
  10822. (if (car-safe files) files
  10823. (org-agenda-files))))))))
  10824. (defun org-make-tags-matcher (match)
  10825. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10826. Returns a cons of the selection string MATCH and a function
  10827. implementing the matcher.
  10828. The matcher is to be called at an Org entry, with point on the
  10829. headline, and returns non-nil if the entry matches the selection
  10830. string MATCH. It must be called with three arguments: the TODO
  10831. keyword at the entry (or nil if none), the list of all tags at
  10832. the entry including inherited ones and the reduced level of the
  10833. headline. Additionally, the category of the entry, if any, must
  10834. be specified as the text property `org-category' on the headline.
  10835. This function sets the variable `org--matcher-tags-todo-only' to
  10836. a non-nil value if the matcher restricts matching to TODO
  10837. entries, otherwise it is not touched.
  10838. See also `org-scan-tags'."
  10839. (unless match
  10840. ;; Get a new match request, with completion against the global
  10841. ;; tags table and the local tags in current buffer.
  10842. (let ((org-last-tags-completion-table
  10843. (org--tag-add-to-alist
  10844. (org-get-buffer-tags)
  10845. (org-global-tags-completion-table))))
  10846. (setq match
  10847. (completing-read
  10848. "Match: "
  10849. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10850. (let ((match0 match)
  10851. (re (concat
  10852. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10853. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10854. "\\([<>=]\\{1,2\\}\\)"
  10855. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10856. "\\|" org-tag-re "\\)"))
  10857. (start 0)
  10858. tagsmatch todomatch tagsmatcher todomatcher)
  10859. ;; Expand group tags.
  10860. (setq match (org-tags-expand match))
  10861. ;; Check if there is a TODO part of this match, which would be the
  10862. ;; part after a "/". To make sure that this slash is not part of
  10863. ;; a property value to be matched against, we also check that
  10864. ;; there is no / after that slash. First, find the last slash.
  10865. (let ((s 0))
  10866. (while (string-match "/+" match s)
  10867. (setq start (match-beginning 0))
  10868. (setq s (match-end 0))))
  10869. (if (and (string-match "/+" match start)
  10870. (not (string-match-p "\"" match start)))
  10871. ;; Match contains also a TODO-matching request.
  10872. (progn
  10873. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10874. (setq todomatch (substring match (match-end 0)))
  10875. (when (string-prefix-p "!" todomatch)
  10876. (setq org--matcher-tags-todo-only t)
  10877. (setq todomatch (substring todomatch 1)))
  10878. (when (string-match "\\`\\s-*\\'" todomatch)
  10879. (setq todomatch nil)))
  10880. ;; Only matching tags.
  10881. (setq tagsmatch match)
  10882. (setq todomatch nil))
  10883. ;; Make the tags matcher.
  10884. (when (org-string-nw-p tagsmatch)
  10885. (let ((orlist nil)
  10886. (orterms (org-split-string tagsmatch "|"))
  10887. term)
  10888. (while (setq term (pop orterms))
  10889. (while (and (equal (substring term -1) "\\") orterms)
  10890. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10891. (while (string-match re term)
  10892. (let* ((rest (substring term (match-end 0)))
  10893. (minus (and (match-end 1)
  10894. (equal (match-string 1 term) "-")))
  10895. (tag (save-match-data
  10896. (replace-regexp-in-string
  10897. "\\\\-" "-" (match-string 2 term))))
  10898. (regexp (eq (string-to-char tag) ?{))
  10899. (levelp (match-end 4))
  10900. (propp (match-end 5))
  10901. (mm
  10902. (cond
  10903. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10904. (levelp
  10905. `(,(org-op-to-function (match-string 3 term))
  10906. level
  10907. ,(string-to-number (match-string 4 term))))
  10908. (propp
  10909. (let* ((gv (pcase (upcase (match-string 5 term))
  10910. ("CATEGORY"
  10911. '(get-text-property (point) 'org-category))
  10912. ("TODO" 'todo)
  10913. (p `(org-cached-entry-get nil ,p))))
  10914. (pv (match-string 7 term))
  10915. (regexp (eq (string-to-char pv) ?{))
  10916. (strp (eq (string-to-char pv) ?\"))
  10917. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10918. (po (org-op-to-function (match-string 6 term)
  10919. (if timep 'time strp))))
  10920. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10921. (when timep (setq pv (org-matcher-time pv)))
  10922. (cond ((and regexp (eq po '/=))
  10923. `(not (string-match ,pv (or ,gv ""))))
  10924. (regexp `(string-match ,pv (or ,gv "")))
  10925. (strp `(,po (or ,gv "") ,pv))
  10926. (t
  10927. `(,po
  10928. (string-to-number (or ,gv ""))
  10929. ,(string-to-number pv))))))
  10930. (t `(member ,tag tags-list)))))
  10931. (push (if minus `(not ,mm) mm) tagsmatcher)
  10932. (setq term rest)))
  10933. (push `(and ,@tagsmatcher) orlist)
  10934. (setq tagsmatcher nil))
  10935. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10936. ;; Make the TODO matcher.
  10937. (when (org-string-nw-p todomatch)
  10938. (let ((orlist nil))
  10939. (dolist (term (org-split-string todomatch "|"))
  10940. (while (string-match re term)
  10941. (let* ((minus (and (match-end 1)
  10942. (equal (match-string 1 term) "-")))
  10943. (kwd (match-string 2 term))
  10944. (regexp (eq (string-to-char kwd) ?{))
  10945. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10946. `(equal todo ,kwd))))
  10947. (push (if minus `(not ,mm) mm) todomatcher))
  10948. (setq term (substring term (match-end 0))))
  10949. (push (if (> (length todomatcher) 1)
  10950. (cons 'and todomatcher)
  10951. (car todomatcher))
  10952. orlist)
  10953. (setq todomatcher nil))
  10954. (setq todomatcher (cons 'or orlist))))
  10955. ;; Return the string and function of the matcher. If no
  10956. ;; tags-specific or todo-specific matcher exists, match
  10957. ;; everything.
  10958. (let ((matcher (if (and tagsmatcher todomatcher)
  10959. `(and ,tagsmatcher ,todomatcher)
  10960. (or tagsmatcher todomatcher t))))
  10961. (when org--matcher-tags-todo-only
  10962. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10963. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10964. (defun org--tags-expand-group (group tag-groups expanded)
  10965. "Recursively Expand all tags in GROUP, according to TAG-GROUPS.
  10966. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10967. an accumulator used in recursive calls."
  10968. (dolist (tag group)
  10969. (unless (member tag expanded)
  10970. (let ((group (assoc tag tag-groups)))
  10971. (push tag expanded)
  10972. (when group
  10973. (setq expanded
  10974. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10975. expanded)
  10976. (defun org-tags-expand (match &optional single-as-list downcased)
  10977. "Expand group tags in MATCH.
  10978. This replaces every group tag in MATCH with a regexp tag search.
  10979. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10980. will be replaced like this:
  10981. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10982. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10983. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10984. Replacing by a regexp preserves the structure of the match.
  10985. E.g., this expansion
  10986. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10987. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10988. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10989. A group tag in MATCH can contain regular expressions of its own.
  10990. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10991. will be replaced like this:
  10992. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10993. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10994. assumed to be a single group tag, and the function will return
  10995. the list of tags in this group.
  10996. When DOWNCASED is non-nil, expand downcased TAGS."
  10997. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10998. (let ((tag-groups
  10999. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  11000. (if (not downcased) g
  11001. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  11002. (cond
  11003. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  11004. (org-group-tags
  11005. (let* ((case-fold-search t)
  11006. (tag-syntax org-mode-syntax-table)
  11007. (group-keys (mapcar #'car tag-groups))
  11008. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  11009. (return-match (if downcased (downcase match) match)))
  11010. ;; Mark regexp-expressions in the match-expression so that we
  11011. ;; do not replace them later on.
  11012. (let ((s 0))
  11013. (while (string-match "{.+?}" return-match s)
  11014. (setq s (match-end 0))
  11015. (add-text-properties
  11016. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  11017. ;; @ and _ are allowed as word-components in tags.
  11018. (modify-syntax-entry ?@ "w" tag-syntax)
  11019. (modify-syntax-entry ?_ "w" tag-syntax)
  11020. ;; For each tag token found in MATCH, compute a regexp and it
  11021. (with-syntax-table tag-syntax
  11022. (replace-regexp-in-string
  11023. key-regexp
  11024. (lambda (m)
  11025. (if (get-text-property (match-beginning 2) 'regexp m)
  11026. m ;regexp tag: ignore
  11027. (let* ((operator (match-string 1 m))
  11028. (tag-token (let ((tag (match-string 2 m)))
  11029. (list (if downcased (downcase tag) tag))))
  11030. regexp-tags regular-tags)
  11031. ;; Partition tags between regexp and regular tags.
  11032. ;; Remove curly bracket syntax from regexp tags.
  11033. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  11034. (save-match-data
  11035. (if (string-match "{\\(.+?\\)}" tag)
  11036. (push (match-string 1 tag) regexp-tags)
  11037. (push tag regular-tags))))
  11038. ;; Replace tag token by the appropriate regexp.
  11039. ;; Regular tags need to be regexp-quoted, whereas
  11040. ;; regexp-tags are inserted as-is.
  11041. (let ((regular (regexp-opt regular-tags))
  11042. (regexp (mapconcat #'identity regexp-tags "\\|")))
  11043. (concat operator
  11044. (cond
  11045. ((null regular-tags) (format "{%s}" regexp))
  11046. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  11047. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  11048. return-match
  11049. t t))))
  11050. (t match))))
  11051. (defun org-op-to-function (op &optional stringp)
  11052. "Turn an operator into the appropriate function."
  11053. (setq op
  11054. (cond
  11055. ((equal op "<" ) '(< org-string< org-time<))
  11056. ((equal op ">" ) '(> org-string> org-time>))
  11057. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  11058. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  11059. ((member op '("=" "==")) '(= string= org-time=))
  11060. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  11061. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  11062. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  11063. (defvar org-tags-overlay (make-overlay 1 1))
  11064. (delete-overlay org-tags-overlay)
  11065. (defun org-add-prop-inherited (s)
  11066. (add-text-properties 0 (length s) '(inherited t) s)
  11067. s)
  11068. (defun org-toggle-tag (tag &optional onoff)
  11069. "Toggle the tag TAG for the current line.
  11070. If ONOFF is `on' or `off', don't toggle but set to this state."
  11071. (save-excursion
  11072. (org-back-to-heading t)
  11073. (let ((current
  11074. ;; Reverse the tags list so any new tag is appended to the
  11075. ;; current list of tags.
  11076. (nreverse (org-get-tags nil t)))
  11077. res)
  11078. (pcase onoff
  11079. (`off (setq current (delete tag current)))
  11080. ((or `on (guard (not (member tag current))))
  11081. (setq res t)
  11082. (cl-pushnew tag current :test #'equal))
  11083. (_ (setq current (delete tag current))))
  11084. (org-set-tags (nreverse current))
  11085. res)))
  11086. (defun org--align-tags-here (to-col)
  11087. "Align tags on the current headline to TO-COL.
  11088. Assume point is on a headline. Preserve point when aligning
  11089. tags."
  11090. (when (org-match-line org-tag-line-re)
  11091. (let* ((tags-start (match-beginning 1))
  11092. (blank-start (save-excursion
  11093. (goto-char tags-start)
  11094. (skip-chars-backward " \t")
  11095. (point)))
  11096. (new (max (if (>= to-col 0) to-col
  11097. (- (abs to-col) (string-width (match-string 1))))
  11098. ;; Introduce at least one space after the heading
  11099. ;; or the stars.
  11100. (save-excursion
  11101. (goto-char blank-start)
  11102. (1+ (current-column)))))
  11103. (current
  11104. (save-excursion (goto-char tags-start) (current-column)))
  11105. (origin (point-marker))
  11106. (column (current-column))
  11107. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  11108. (when (/= new current)
  11109. (delete-region blank-start tags-start)
  11110. (goto-char blank-start)
  11111. (let ((indent-tabs-mode nil)) (indent-to new))
  11112. ;; Try to move back to original position. If point was in the
  11113. ;; blanks before the tags, ORIGIN marker is of no use because
  11114. ;; it now points to BLANK-START. Use COLUMN instead.
  11115. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  11116. (defun org-set-tags-command (&optional arg)
  11117. "Set the tags for the current visible entry.
  11118. When called with `\\[universal-argument]' prefix argument ARG, \
  11119. realign all tags
  11120. in the current buffer.
  11121. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  11122. unconditionally do not
  11123. offer the fast tag selection interface.
  11124. If a region is active, set tags in the region according to the
  11125. setting of `org-loop-over-headlines-in-active-region'.
  11126. This function is for interactive use only;
  11127. in Lisp code use `org-set-tags' instead."
  11128. (interactive "P")
  11129. (let ((org-use-fast-tag-selection
  11130. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  11131. (cond
  11132. ((equal '(4) arg) (org-align-tags t))
  11133. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11134. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  11135. (org-map-entries
  11136. #'org-set-tags-command
  11137. nil
  11138. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11139. 'region-start-level
  11140. 'region)
  11141. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  11142. (t
  11143. (save-excursion
  11144. (org-back-to-heading)
  11145. (let* ((all-tags (org-get-tags))
  11146. (table (setq org-last-tags-completion-table
  11147. (org--tag-add-to-alist
  11148. (and org-complete-tags-always-offer-all-agenda-tags
  11149. (org-global-tags-completion-table
  11150. (org-agenda-files)))
  11151. (or org-current-tag-alist (org-get-buffer-tags)))))
  11152. (current-tags
  11153. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  11154. all-tags))
  11155. (inherited-tags
  11156. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  11157. all-tags))
  11158. (tags
  11159. (replace-regexp-in-string
  11160. ;; Ignore all forbidden characters in tags.
  11161. "[^[:alnum:]_@#%]+" ":"
  11162. (if (or (eq t org-use-fast-tag-selection)
  11163. (and org-use-fast-tag-selection
  11164. (delq nil (mapcar #'cdr table))))
  11165. (org-fast-tag-selection
  11166. current-tags
  11167. inherited-tags
  11168. table
  11169. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  11170. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  11171. (org-trim (completing-read
  11172. "Tags: "
  11173. #'org-tags-completion-function
  11174. nil nil (org-make-tag-string current-tags)
  11175. 'org-tags-history)))))))
  11176. (org-set-tags tags)))))))
  11177. (defun org-align-tags (&optional all)
  11178. "Align tags in current entry.
  11179. When optional argument ALL is non-nil, align all tags in the
  11180. visible part of the buffer."
  11181. (let ((get-indent-column
  11182. (lambda ()
  11183. (let ((offset (if (bound-and-true-p org-indent-mode)
  11184. (* (1- org-indent-indentation-per-level)
  11185. (1- (org-current-level)))
  11186. 0)))
  11187. (+ org-tags-column
  11188. (if (> org-tags-column 0) (- offset) offset))))))
  11189. (if (and (not all) (org-at-heading-p))
  11190. (org--align-tags-here (funcall get-indent-column))
  11191. (save-excursion
  11192. (if all
  11193. (progn
  11194. (goto-char (point-min))
  11195. (while (re-search-forward org-tag-line-re nil t)
  11196. (org--align-tags-here (funcall get-indent-column))))
  11197. (org-back-to-heading t)
  11198. (org--align-tags-here (funcall get-indent-column)))))))
  11199. (defun org-set-tags (tags)
  11200. "Set the tags of the current entry to TAGS, replacing current tags.
  11201. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  11202. If TAGS is nil or the empty string, all tags are removed.
  11203. This function assumes point is on a headline."
  11204. (org-with-wide-buffer
  11205. (let ((tags (pcase tags
  11206. ((pred listp) tags)
  11207. ((pred stringp) (split-string (org-trim tags) ":" t))
  11208. (_ (error "Invalid tag specification: %S" tags))))
  11209. (old-tags (org-get-tags nil t))
  11210. (tags-change? nil))
  11211. (when (functionp org-tags-sort-function)
  11212. (setq tags (sort tags org-tags-sort-function)))
  11213. (setq tags-change? (not (equal tags old-tags)))
  11214. (when tags-change?
  11215. ;; Delete previous tags and any trailing white space.
  11216. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  11217. (line-end-position)))
  11218. (skip-chars-backward " \t")
  11219. (delete-region (point) (line-end-position))
  11220. ;; Deleting white spaces may break an otherwise empty headline.
  11221. ;; Re-introduce one space in this case.
  11222. (unless (org-at-heading-p) (insert " "))
  11223. (when tags
  11224. (save-excursion (insert " " (org-make-tag-string tags)))
  11225. ;; When text is being inserted on an invisible region
  11226. ;; boundary, it can be inadvertently sucked into
  11227. ;; invisibility.
  11228. (unless (org-invisible-p (line-beginning-position))
  11229. (org-flag-region (point) (line-end-position) nil 'outline))))
  11230. ;; Align tags, if any.
  11231. (when tags (org-align-tags))
  11232. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  11233. (defun org-change-tag-in-region (beg end tag off)
  11234. "Add or remove TAG for each entry in the region.
  11235. This works in the agenda, and also in an Org buffer."
  11236. (interactive
  11237. (list (region-beginning) (region-end)
  11238. (let ((org-last-tags-completion-table
  11239. (if (derived-mode-p 'org-mode)
  11240. (org--tag-add-to-alist
  11241. (org-get-buffer-tags)
  11242. (org-global-tags-completion-table))
  11243. (org-global-tags-completion-table))))
  11244. (completing-read
  11245. "Tag: " 'org-tags-completion-function nil nil nil
  11246. 'org-tags-history))
  11247. (progn
  11248. (message "[s]et or [r]emove? ")
  11249. (equal (read-char-exclusive) ?r))))
  11250. (when (fboundp 'deactivate-mark) (deactivate-mark))
  11251. (let ((agendap (equal major-mode 'org-agenda-mode))
  11252. l1 l2 m buf pos newhead (cnt 0))
  11253. (goto-char end)
  11254. (setq l2 (1- (org-current-line)))
  11255. (goto-char beg)
  11256. (setq l1 (org-current-line))
  11257. (cl-loop for l from l1 to l2 do
  11258. (org-goto-line l)
  11259. (setq m (get-text-property (point) 'org-hd-marker))
  11260. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  11261. (and agendap m))
  11262. (setq buf (if agendap (marker-buffer m) (current-buffer))
  11263. pos (if agendap m (point)))
  11264. (with-current-buffer buf
  11265. (save-excursion
  11266. (save-restriction
  11267. (goto-char pos)
  11268. (setq cnt (1+ cnt))
  11269. (org-toggle-tag tag (if off 'off 'on))
  11270. (setq newhead (org-get-heading)))))
  11271. (and agendap (org-agenda-change-all-lines newhead m))))
  11272. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  11273. (defun org-tags-completion-function (string _predicate &optional flag)
  11274. "Complete tag STRING.
  11275. FLAG specifies the type of completion operation to perform. This
  11276. function is passed as a collection function to `completing-read',
  11277. which see."
  11278. (let ((completion-ignore-case nil) ;tags are case-sensitive
  11279. (confirm (lambda (x) (stringp (car x))))
  11280. (prefix ""))
  11281. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  11282. (setq prefix (match-string 1 string))
  11283. (setq string (match-string 2 string)))
  11284. (pcase flag
  11285. (`t (all-completions string org-last-tags-completion-table confirm))
  11286. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  11287. (`nil
  11288. (pcase (try-completion string org-last-tags-completion-table confirm)
  11289. ((and completion (pred stringp))
  11290. (concat prefix
  11291. completion
  11292. (if (and org-add-colon-after-tag-completion
  11293. (assoc completion org-last-tags-completion-table))
  11294. ":"
  11295. "")))
  11296. (completion completion)))
  11297. (_ nil))))
  11298. (defun org-fast-tag-insert (kwd tags face &optional end)
  11299. "Insert KWD, and the TAGS, the latter with face FACE.
  11300. Also insert END."
  11301. (insert (format "%-12s" (concat kwd ":"))
  11302. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  11303. (or end "")))
  11304. (defun org-fast-tag-show-exit (flag)
  11305. (save-excursion
  11306. (org-goto-line 3)
  11307. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  11308. (replace-match ""))
  11309. (when flag
  11310. (end-of-line 1)
  11311. (org-move-to-column (- (window-width) 19) t)
  11312. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  11313. (defun org-set-current-tags-overlay (current prefix)
  11314. "Add an overlay to CURRENT tag with PREFIX."
  11315. (let ((s (org-make-tag-string current)))
  11316. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  11317. (org-overlay-display org-tags-overlay (concat prefix s))))
  11318. (defvar org-last-tag-selection-key nil)
  11319. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  11320. "Fast tag selection with single keys.
  11321. CURRENT is the current list of tags in the headline, INHERITED is the
  11322. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  11323. possibly with grouping information. TODO-TABLE is a similar table with
  11324. TODO keywords, should these have keys assigned to them.
  11325. If the keys are nil, a-z are automatically assigned.
  11326. Returns the new tags string, or nil to not change the current settings."
  11327. (let* ((fulltable (append table todo-table))
  11328. (maxlen (if (null fulltable) 0
  11329. (apply #'max
  11330. (mapcar (lambda (x)
  11331. (if (stringp (car x)) (string-width (car x))
  11332. 0))
  11333. fulltable))))
  11334. (buf (current-buffer))
  11335. (expert (eq org-fast-tag-selection-single-key 'expert))
  11336. (buffer-tags nil)
  11337. (fwidth (+ maxlen 3 1 3))
  11338. (ncol (/ (- (window-width) 4) fwidth))
  11339. (i-face 'org-done)
  11340. (c-face 'org-todo)
  11341. tg cnt e c char c1 c2 ntable tbl rtn
  11342. ov-start ov-end ov-prefix
  11343. (exit-after-next org-fast-tag-selection-single-key)
  11344. (done-keywords org-done-keywords)
  11345. groups ingroup intaggroup)
  11346. (save-excursion
  11347. (beginning-of-line)
  11348. (if (looking-at org-tag-line-re)
  11349. (setq ov-start (match-beginning 1)
  11350. ov-end (match-end 1)
  11351. ov-prefix "")
  11352. (setq ov-start (1- (point-at-eol))
  11353. ov-end (1+ ov-start))
  11354. (skip-chars-forward "^\n\r")
  11355. (setq ov-prefix
  11356. (concat
  11357. (buffer-substring (1- (point)) (point))
  11358. (if (> (current-column) org-tags-column)
  11359. " "
  11360. (make-string (- org-tags-column (current-column)) ?\ ))))))
  11361. (move-overlay org-tags-overlay ov-start ov-end)
  11362. (save-excursion
  11363. (save-window-excursion
  11364. (if expert
  11365. (set-buffer (get-buffer-create " *Org tags*"))
  11366. (delete-other-windows)
  11367. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  11368. (org-switch-to-buffer-other-window " *Org tags*"))
  11369. (erase-buffer)
  11370. (setq-local org-done-keywords done-keywords)
  11371. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  11372. (org-fast-tag-insert "Current" current c-face "\n\n")
  11373. (org-fast-tag-show-exit exit-after-next)
  11374. (org-set-current-tags-overlay current ov-prefix)
  11375. (setq tbl fulltable char ?a cnt 0)
  11376. (while (setq e (pop tbl))
  11377. (cond
  11378. ((eq (car e) :startgroup)
  11379. (push '() groups) (setq ingroup t)
  11380. (unless (zerop cnt)
  11381. (setq cnt 0)
  11382. (insert "\n"))
  11383. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11384. ((eq (car e) :endgroup)
  11385. (setq ingroup nil cnt 0)
  11386. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11387. ((eq (car e) :startgrouptag)
  11388. (setq intaggroup t)
  11389. (unless (zerop cnt)
  11390. (setq cnt 0)
  11391. (insert "\n"))
  11392. (insert "[ "))
  11393. ((eq (car e) :endgrouptag)
  11394. (setq intaggroup nil cnt 0)
  11395. (insert "]\n"))
  11396. ((equal e '(:newline))
  11397. (unless (zerop cnt)
  11398. (setq cnt 0)
  11399. (insert "\n")
  11400. (setq e (car tbl))
  11401. (while (equal (car tbl) '(:newline))
  11402. (insert "\n")
  11403. (setq tbl (cdr tbl)))))
  11404. ((equal e '(:grouptags)) (insert " : "))
  11405. (t
  11406. (setq tg (copy-sequence (car e)) c2 nil)
  11407. (if (cdr e)
  11408. (setq c (cdr e))
  11409. ;; automatically assign a character.
  11410. (setq c1 (string-to-char
  11411. (downcase (substring
  11412. tg (if (= (string-to-char tg) ?@) 1 0)))))
  11413. (if (or (rassoc c1 ntable) (rassoc c1 table))
  11414. (while (or (rassoc char ntable) (rassoc char table))
  11415. (setq char (1+ char)))
  11416. (setq c2 c1))
  11417. (setq c (or c2 char)))
  11418. (when ingroup (push tg (car groups)))
  11419. (setq tg (org-add-props tg nil 'face
  11420. (cond
  11421. ((not (assoc tg table))
  11422. (org-get-todo-face tg))
  11423. ((member tg current) c-face)
  11424. ((member tg inherited) i-face))))
  11425. (when (equal (caar tbl) :grouptags)
  11426. (org-add-props tg nil 'face 'org-tag-group))
  11427. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  11428. (insert "[" c "] " tg (make-string
  11429. (- fwidth 4 (length tg)) ?\ ))
  11430. (push (cons tg c) ntable)
  11431. (when (= (cl-incf cnt) ncol)
  11432. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11433. (insert "\n")
  11434. (when (or ingroup intaggroup) (insert " ")))
  11435. (setq cnt 0)))))
  11436. (setq ntable (nreverse ntable))
  11437. (insert "\n")
  11438. (goto-char (point-min))
  11439. (unless expert (org-fit-window-to-buffer))
  11440. (setq rtn
  11441. (catch 'exit
  11442. (while t
  11443. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11444. (if (not groups) "no " "")
  11445. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11446. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11447. (setq org-last-tag-selection-key c)
  11448. (cond
  11449. ((= c ?\r) (throw 'exit t))
  11450. ((= c ?!)
  11451. (setq groups (not groups))
  11452. (goto-char (point-min))
  11453. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11454. ((= c ?\C-c)
  11455. (if (not expert)
  11456. (org-fast-tag-show-exit
  11457. (setq exit-after-next (not exit-after-next)))
  11458. (setq expert nil)
  11459. (delete-other-windows)
  11460. (set-window-buffer (split-window-vertically) " *Org tags*")
  11461. (org-switch-to-buffer-other-window " *Org tags*")
  11462. (org-fit-window-to-buffer)))
  11463. ((or (= c ?\C-g)
  11464. (and (= c ?q) (not (rassoc c ntable))))
  11465. (delete-overlay org-tags-overlay)
  11466. (setq quit-flag t))
  11467. ((= c ?\ )
  11468. (setq current nil)
  11469. (when exit-after-next (setq exit-after-next 'now)))
  11470. ((= c ?\t)
  11471. (condition-case nil
  11472. (setq tg (completing-read
  11473. "Tag: "
  11474. (or buffer-tags
  11475. (with-current-buffer buf
  11476. (setq buffer-tags
  11477. (org-get-buffer-tags))))))
  11478. (quit (setq tg "")))
  11479. (when (string-match "\\S-" tg)
  11480. (cl-pushnew (list tg) buffer-tags :test #'equal)
  11481. (if (member tg current)
  11482. (setq current (delete tg current))
  11483. (push tg current)))
  11484. (when exit-after-next (setq exit-after-next 'now)))
  11485. ((setq e (rassoc c todo-table) tg (car e))
  11486. (with-current-buffer buf
  11487. (save-excursion (org-todo tg)))
  11488. (when exit-after-next (setq exit-after-next 'now)))
  11489. ((setq e (rassoc c ntable) tg (car e))
  11490. (if (member tg current)
  11491. (setq current (delete tg current))
  11492. (cl-loop for g in groups do
  11493. (when (member tg g)
  11494. (dolist (x g) (setq current (delete x current)))))
  11495. (push tg current))
  11496. (when exit-after-next (setq exit-after-next 'now))))
  11497. ;; Create a sorted list
  11498. (setq current
  11499. (sort current
  11500. (lambda (a b)
  11501. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11502. (when (eq exit-after-next 'now) (throw 'exit t))
  11503. (goto-char (point-min))
  11504. (beginning-of-line 2)
  11505. (delete-region (point) (point-at-eol))
  11506. (org-fast-tag-insert "Current" current c-face)
  11507. (org-set-current-tags-overlay current ov-prefix)
  11508. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11509. (while (re-search-forward tag-re nil t)
  11510. (let ((tag (match-string 1)))
  11511. (add-text-properties
  11512. (match-beginning 1) (match-end 1)
  11513. (list 'face
  11514. (cond
  11515. ((member tag current) c-face)
  11516. ((member tag inherited) i-face)
  11517. (t (get-text-property (match-beginning 1) '
  11518. face))))))))
  11519. (goto-char (point-min)))))
  11520. (delete-overlay org-tags-overlay)
  11521. (if rtn
  11522. (mapconcat 'identity current ":")
  11523. nil)))))
  11524. (defun org-make-tag-string (tags)
  11525. "Return string associated to TAGS.
  11526. TAGS is a list of strings."
  11527. (if (null tags) ""
  11528. (format ":%s:" (mapconcat #'identity tags ":"))))
  11529. (defun org--get-local-tags ()
  11530. "Return list of tags for the current headline.
  11531. Assume point is at the beginning of the headline."
  11532. (and (looking-at org-tag-line-re)
  11533. (split-string (match-string-no-properties 2) ":" t)))
  11534. (defun org-get-tags (&optional pos local)
  11535. "Get the list of tags specified in the current headline.
  11536. When argument POS is non-nil, retrieve tags for headline at POS.
  11537. According to `org-use-tag-inheritance', tags may be inherited
  11538. from parent headlines, and from the whole document, through
  11539. `org-file-tags'. In this case, the returned list of tags
  11540. contains tags in this order: file tags, tags inherited from
  11541. parent headlines, local tags.
  11542. However, when optional argument LOCAL is non-nil, only return
  11543. tags specified at the headline.
  11544. Inherited tags have the `inherited' text property."
  11545. (if (and org-trust-scanner-tags
  11546. (or (not pos) (eq pos (point)))
  11547. (not local))
  11548. org-scanner-tags
  11549. (org-with-point-at (or pos (point))
  11550. (unless (org-before-first-heading-p)
  11551. (org-back-to-heading t)
  11552. (let ((ltags (org--get-local-tags)) itags)
  11553. (if (or local (not org-use-tag-inheritance)) ltags
  11554. (while (org-up-heading-safe)
  11555. (setq itags (append (mapcar #'org-add-prop-inherited
  11556. (org--get-local-tags))
  11557. itags)))
  11558. (setq itags (append org-file-tags itags))
  11559. (delete-dups
  11560. (append (org-remove-uninherited-tags itags) ltags))))))))
  11561. (defun org-get-buffer-tags ()
  11562. "Get a table of all tags used in the buffer, for completion."
  11563. (org-with-point-at 1
  11564. (let (tags)
  11565. (while (re-search-forward org-tag-line-re nil t)
  11566. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11567. tags)))
  11568. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11569. ;;;; The mapping API
  11570. (defvar org-agenda-skip-comment-trees)
  11571. (defvar org-agenda-skip-function)
  11572. (defun org-map-entries (func &optional match scope &rest skip)
  11573. "Call FUNC at each headline selected by MATCH in SCOPE.
  11574. FUNC is a function or a lisp form. The function will be called without
  11575. arguments, with the cursor positioned at the beginning of the headline.
  11576. The return values of all calls to the function will be collected and
  11577. returned as a list.
  11578. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  11579. does not need to preserve point. After evaluation, the cursor will be
  11580. moved to the end of the line (presumably of the headline of the
  11581. processed entry) and search continues from there. Under some
  11582. circumstances, this may not produce the wanted results. For example,
  11583. if you have removed (e.g. archived) the current (sub)tree it could
  11584. mean that the next entry will be skipped entirely. In such cases, you
  11585. can specify the position from where search should continue by making
  11586. FUNC set the variable `org-map-continue-from' to the desired buffer
  11587. position.
  11588. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11589. Only headlines that are matched by this query will be considered during
  11590. the iteration. When MATCH is nil or t, all headlines will be
  11591. visited by the iteration.
  11592. SCOPE determines the scope of this command. It can be any of:
  11593. nil The current buffer, respecting the restriction if any
  11594. tree The subtree started with the entry at point
  11595. region The entries within the active region, if any
  11596. region-start-level
  11597. The entries within the active region, but only those at
  11598. the same level than the first one.
  11599. file The current buffer, without restriction
  11600. file-with-archives
  11601. The current buffer, and any archives associated with it
  11602. agenda All agenda files
  11603. agenda-with-archives
  11604. All agenda files with any archive files associated with them
  11605. \(file1 file2 ...)
  11606. If this is a list, all files in the list will be scanned
  11607. The remaining args are treated as settings for the skipping facilities of
  11608. the scanner. The following items can be given here:
  11609. archive skip trees with the archive tag
  11610. comment skip trees with the COMMENT keyword
  11611. function or Emacs Lisp form:
  11612. will be used as value for `org-agenda-skip-function', so
  11613. whenever the function returns a position, FUNC will not be
  11614. called for that entry and search will continue from the
  11615. position returned
  11616. If your function needs to retrieve the tags including inherited tags
  11617. at the *current* entry, you can use the value of the variable
  11618. `org-scanner-tags' which will be much faster than getting the value
  11619. with `org-get-tags'. If your function gets properties with
  11620. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11621. to t around the call to `org-entry-properties' to get the same speedup.
  11622. Note that if your function moves around to retrieve tags and properties at
  11623. a *different* entry, you cannot use these techniques."
  11624. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11625. (not (org-region-active-p)))
  11626. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11627. (org-agenda-skip-archived-trees (memq 'archive skip))
  11628. (org-agenda-skip-comment-trees (memq 'comment skip))
  11629. (org-agenda-skip-function
  11630. (car (org-delete-all '(comment archive) skip)))
  11631. (org-tags-match-list-sublevels t)
  11632. (start-level (eq scope 'region-start-level))
  11633. matcher res
  11634. org-todo-keywords-for-agenda
  11635. org-done-keywords-for-agenda
  11636. org-todo-keyword-alist-for-agenda
  11637. org-tag-alist-for-agenda
  11638. org--matcher-tags-todo-only)
  11639. (cond
  11640. ((eq match t) (setq matcher t))
  11641. ((eq match nil) (setq matcher t))
  11642. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11643. (save-excursion
  11644. (save-restriction
  11645. (cond ((eq scope 'tree)
  11646. (org-back-to-heading t)
  11647. (org-narrow-to-subtree)
  11648. (setq scope nil))
  11649. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11650. (org-region-active-p))
  11651. ;; If needed, set start-level to a string like "2"
  11652. (when start-level
  11653. (save-excursion
  11654. (goto-char (region-beginning))
  11655. (unless (org-at-heading-p) (outline-next-heading))
  11656. (setq start-level (org-current-level))))
  11657. (narrow-to-region (region-beginning)
  11658. (save-excursion
  11659. (goto-char (region-end))
  11660. (unless (and (bolp) (org-at-heading-p))
  11661. (outline-next-heading))
  11662. (point)))
  11663. (setq scope nil)))
  11664. (if (not scope)
  11665. (progn
  11666. (org-agenda-prepare-buffers
  11667. (and buffer-file-name (list buffer-file-name)))
  11668. (setq res
  11669. (org-scan-tags
  11670. func matcher org--matcher-tags-todo-only start-level)))
  11671. ;; Get the right scope
  11672. (cond
  11673. ((and scope (listp scope) (symbolp (car scope)))
  11674. (setq scope (eval scope)))
  11675. ((eq scope 'agenda)
  11676. (setq scope (org-agenda-files t)))
  11677. ((eq scope 'agenda-with-archives)
  11678. (setq scope (org-agenda-files t))
  11679. (setq scope (org-add-archive-files scope)))
  11680. ((eq scope 'file)
  11681. (setq scope (and buffer-file-name (list buffer-file-name))))
  11682. ((eq scope 'file-with-archives)
  11683. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11684. (org-agenda-prepare-buffers scope)
  11685. (dolist (file scope)
  11686. (with-current-buffer (org-find-base-buffer-visiting file)
  11687. (org-with-wide-buffer
  11688. (goto-char (point-min))
  11689. (setq res
  11690. (append
  11691. res
  11692. (org-scan-tags
  11693. func matcher org--matcher-tags-todo-only)))))))))
  11694. res)))
  11695. ;;; Properties API
  11696. (defconst org-special-properties
  11697. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11698. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11699. "The special properties valid in Org mode.
  11700. These are properties that are not defined in the property drawer,
  11701. but in some other way.")
  11702. (defconst org-default-properties
  11703. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11704. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11705. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11706. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11707. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11708. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11709. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11710. "Some properties that are used by Org mode for various purposes.
  11711. Being in this list makes sure that they are offered for completion.")
  11712. (defun org--valid-property-p (property)
  11713. "Non-nil when string PROPERTY is a valid property name."
  11714. (not
  11715. (or (equal property "")
  11716. (string-match-p "\\s-" property))))
  11717. (defun org--update-property-plist (key val props)
  11718. "Associate KEY to VAL in alist PROPS.
  11719. Modifications are made by side-effect. Return new alist."
  11720. (let* ((appending (string= (substring key -1) "+"))
  11721. (key (if appending (substring key 0 -1) key))
  11722. (old (assoc-string key props t)))
  11723. (if (not old) (cons (cons key val) props)
  11724. (setcdr old (if appending (concat (cdr old) " " val) val))
  11725. props)))
  11726. (defun org-get-property-block (&optional beg force)
  11727. "Return the (beg . end) range of the body of the property drawer.
  11728. BEG is the beginning of the current subtree, or of the part
  11729. before the first headline. If it is not given, it will be found.
  11730. If the drawer does not exist, create it if FORCE is non-nil, or
  11731. return nil."
  11732. (org-with-wide-buffer
  11733. (when beg (goto-char beg))
  11734. (unless (org-before-first-heading-p)
  11735. (let ((beg (cond (beg)
  11736. ((or (not (featurep 'org-inlinetask))
  11737. (org-inlinetask-in-task-p))
  11738. (org-back-to-heading t))
  11739. (t (org-with-limited-levels (org-back-to-heading t))))))
  11740. (forward-line)
  11741. (when (looking-at-p org-planning-line-re) (forward-line))
  11742. (cond ((looking-at org-property-drawer-re)
  11743. (forward-line)
  11744. (cons (point) (progn (goto-char (match-end 0))
  11745. (line-beginning-position))))
  11746. (force
  11747. (goto-char beg)
  11748. (org-insert-property-drawer)
  11749. (let ((pos (save-excursion (search-forward ":END:")
  11750. (line-beginning-position))))
  11751. (cons pos pos))))))))
  11752. (defun org-at-property-p ()
  11753. "Non-nil when point is inside a property drawer.
  11754. See `org-property-re' for match data, if applicable."
  11755. (save-excursion
  11756. (beginning-of-line)
  11757. (and (looking-at org-property-re)
  11758. (let ((property-drawer (save-match-data (org-get-property-block))))
  11759. (and property-drawer
  11760. (>= (point) (car property-drawer))
  11761. (< (point) (cdr property-drawer)))))))
  11762. (defun org-property-action ()
  11763. "Do an action on properties."
  11764. (interactive)
  11765. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11766. (let ((c (read-char-exclusive)))
  11767. (cl-case c
  11768. (?s (call-interactively #'org-set-property))
  11769. (?d (call-interactively #'org-delete-property))
  11770. (?D (call-interactively #'org-delete-property-globally))
  11771. (?c (call-interactively #'org-compute-property-at-point))
  11772. (otherwise (user-error "No such property action %c" c)))))
  11773. (defun org-inc-effort ()
  11774. "Increment the value of the effort property in the current entry."
  11775. (interactive)
  11776. (org-set-effort t))
  11777. (defvar org-clock-effort) ; Defined in org-clock.el.
  11778. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11779. (defun org-set-effort (&optional increment value)
  11780. "Set the effort property of the current entry.
  11781. If INCREMENT is non-nil, set the property to the next allowed
  11782. value. Otherwise, if optional argument VALUE is provided, use
  11783. it. Eventually, prompt for the new value if none of the previous
  11784. variables is set."
  11785. (interactive "P")
  11786. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11787. (current (org-entry-get nil org-effort-property))
  11788. (value
  11789. (cond
  11790. (increment
  11791. (unless allowed (user-error "Allowed effort values are not set"))
  11792. (or (cl-caadr (member (list current) allowed))
  11793. (user-error "Unknown value %S among allowed values" current)))
  11794. (value
  11795. (if (stringp value) value
  11796. (error "Invalid effort value: %S" value)))
  11797. (t
  11798. (let ((must-match
  11799. (and allowed
  11800. (not (get-text-property 0 'org-unrestricted
  11801. (caar allowed))))))
  11802. (completing-read "Effort: " allowed nil must-match))))))
  11803. ;; Test whether the value can be interpreted as a duration before
  11804. ;; inserting it in the buffer:
  11805. (org-duration-to-minutes value)
  11806. ;; Maybe update the effort value:
  11807. (unless (equal current value)
  11808. (org-entry-put nil org-effort-property value))
  11809. (org-refresh-property '((effort . identity)
  11810. (effort-minutes . org-duration-to-minutes))
  11811. value)
  11812. (when (equal (org-get-heading t t t t)
  11813. (bound-and-true-p org-clock-current-task))
  11814. (setq org-clock-effort value)
  11815. (org-clock-update-mode-line))
  11816. (message "%s is now %s" org-effort-property value)))
  11817. (defun org-entry-properties (&optional pom which)
  11818. "Get all properties of the current entry.
  11819. When POM is a buffer position, get all properties from the entry
  11820. there instead.
  11821. This includes the TODO keyword, the tags, time strings for
  11822. deadline, scheduled, and clocking, and any additional properties
  11823. defined in the entry.
  11824. If WHICH is nil or `all', get all properties. If WHICH is
  11825. `special' or `standard', only get that subclass. If WHICH is
  11826. a string, only get that property.
  11827. Return value is an alist. Keys are properties, as upcased
  11828. strings."
  11829. (org-with-point-at pom
  11830. (when (and (derived-mode-p 'org-mode)
  11831. (ignore-errors (org-back-to-heading t)))
  11832. (catch 'exit
  11833. (let* ((beg (point))
  11834. (specific (and (stringp which) (upcase which)))
  11835. (which (cond ((not specific) which)
  11836. ((member specific org-special-properties) 'special)
  11837. (t 'standard)))
  11838. props)
  11839. ;; Get the special properties, like TODO and TAGS.
  11840. (when (memq which '(nil all special))
  11841. (when (or (not specific) (string= specific "CLOCKSUM"))
  11842. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11843. (when clocksum
  11844. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11845. props)))
  11846. (when specific (throw 'exit props)))
  11847. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11848. (let ((clocksumt (get-text-property (point)
  11849. :org-clock-minutes-today)))
  11850. (when clocksumt
  11851. (push (cons "CLOCKSUM_T"
  11852. (org-duration-from-minutes clocksumt))
  11853. props)))
  11854. (when specific (throw 'exit props)))
  11855. (when (or (not specific) (string= specific "ITEM"))
  11856. (let ((case-fold-search nil))
  11857. (when (looking-at org-complex-heading-regexp)
  11858. (push (cons "ITEM"
  11859. (let ((title (match-string-no-properties 4)))
  11860. (if (org-string-nw-p title)
  11861. (org-remove-tabs title)
  11862. "")))
  11863. props)))
  11864. (when specific (throw 'exit props)))
  11865. (when (or (not specific) (string= specific "TODO"))
  11866. (let ((case-fold-search nil))
  11867. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11868. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11869. (when specific (throw 'exit props)))
  11870. (when (or (not specific) (string= specific "PRIORITY"))
  11871. (push (cons "PRIORITY"
  11872. (if (looking-at org-priority-regexp)
  11873. (match-string-no-properties 2)
  11874. (char-to-string org-default-priority)))
  11875. props)
  11876. (when specific (throw 'exit props)))
  11877. (when (or (not specific) (string= specific "FILE"))
  11878. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11879. props)
  11880. (when specific (throw 'exit props)))
  11881. (when (or (not specific) (string= specific "TAGS"))
  11882. (let ((tags (org-get-tags nil t)))
  11883. (when tags
  11884. (push (cons "TAGS" (org-make-tag-string tags))
  11885. props)))
  11886. (when specific (throw 'exit props)))
  11887. (when (or (not specific) (string= specific "ALLTAGS"))
  11888. (let ((tags (org-get-tags)))
  11889. (when tags
  11890. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11891. props)))
  11892. (when specific (throw 'exit props)))
  11893. (when (or (not specific) (string= specific "BLOCKED"))
  11894. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11895. (when specific (throw 'exit props)))
  11896. (when (or (not specific)
  11897. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11898. (forward-line)
  11899. (when (looking-at-p org-planning-line-re)
  11900. (end-of-line)
  11901. (let ((bol (line-beginning-position))
  11902. ;; Backward compatibility: time keywords used to
  11903. ;; be configurable (before 8.3). Make sure we
  11904. ;; get the correct keyword.
  11905. (key-assoc `(("CLOSED" . ,org-closed-string)
  11906. ("DEADLINE" . ,org-deadline-string)
  11907. ("SCHEDULED" . ,org-scheduled-string))))
  11908. (dolist (pair (if specific (list (assoc specific key-assoc))
  11909. key-assoc))
  11910. (save-excursion
  11911. (when (search-backward (cdr pair) bol t)
  11912. (goto-char (match-end 0))
  11913. (skip-chars-forward " \t")
  11914. (and (looking-at org-ts-regexp-both)
  11915. (push (cons (car pair)
  11916. (match-string-no-properties 0))
  11917. props)))))))
  11918. (when specific (throw 'exit props)))
  11919. (when (or (not specific)
  11920. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11921. (let ((find-ts
  11922. (lambda (end ts)
  11923. ;; Fix next time-stamp before END. TS is the
  11924. ;; list of time-stamps found so far.
  11925. (let ((ts ts)
  11926. (regexp (cond
  11927. ((string= specific "TIMESTAMP")
  11928. org-ts-regexp)
  11929. ((string= specific "TIMESTAMP_IA")
  11930. org-ts-regexp-inactive)
  11931. ((assoc "TIMESTAMP_IA" ts)
  11932. org-ts-regexp)
  11933. ((assoc "TIMESTAMP" ts)
  11934. org-ts-regexp-inactive)
  11935. (t org-ts-regexp-both))))
  11936. (catch 'next
  11937. (while (re-search-forward regexp end t)
  11938. (backward-char)
  11939. (let ((object (org-element-context)))
  11940. ;; Accept to match timestamps in node
  11941. ;; properties, too.
  11942. (when (memq (org-element-type object)
  11943. '(node-property timestamp))
  11944. (let ((type
  11945. (org-element-property :type object)))
  11946. (cond
  11947. ((and (memq type '(active active-range))
  11948. (not (equal specific "TIMESTAMP_IA")))
  11949. (unless (assoc "TIMESTAMP" ts)
  11950. (push (cons "TIMESTAMP"
  11951. (org-element-property
  11952. :raw-value object))
  11953. ts)
  11954. (when specific (throw 'exit ts))))
  11955. ((and (memq type '(inactive inactive-range))
  11956. (not (string= specific "TIMESTAMP")))
  11957. (unless (assoc "TIMESTAMP_IA" ts)
  11958. (push (cons "TIMESTAMP_IA"
  11959. (org-element-property
  11960. :raw-value object))
  11961. ts)
  11962. (when specific (throw 'exit ts))))))
  11963. ;; Both timestamp types are found,
  11964. ;; move to next part.
  11965. (when (= (length ts) 2) (throw 'next ts)))))
  11966. ts)))))
  11967. (goto-char beg)
  11968. ;; First look for timestamps within headline.
  11969. (let ((ts (funcall find-ts (line-end-position) nil)))
  11970. (if (= (length ts) 2) (setq props (nconc ts props))
  11971. ;; Then find timestamps in the section, skipping
  11972. ;; planning line.
  11973. (let ((end (save-excursion (outline-next-heading))))
  11974. (forward-line)
  11975. (when (looking-at-p org-planning-line-re) (forward-line))
  11976. (setq props (nconc (funcall find-ts end ts) props))))))))
  11977. ;; Get the standard properties, like :PROP:.
  11978. (when (memq which '(nil all standard))
  11979. ;; If we are looking after a specific property, delegate
  11980. ;; to `org-entry-get', which is faster. However, make an
  11981. ;; exception for "CATEGORY", since it can be also set
  11982. ;; through keywords (i.e. #+CATEGORY).
  11983. (if (and specific (not (equal specific "CATEGORY")))
  11984. (let ((value (org-entry-get beg specific nil t)))
  11985. (throw 'exit (and value (list (cons specific value)))))
  11986. (let ((range (org-get-property-block beg)))
  11987. (when range
  11988. (let ((end (cdr range)) seen-base)
  11989. (goto-char (car range))
  11990. ;; Unlike to `org--update-property-plist', we
  11991. ;; handle the case where base values is found
  11992. ;; after its extension. We also forbid standard
  11993. ;; properties to be named as special properties.
  11994. (while (re-search-forward org-property-re end t)
  11995. (let* ((key (upcase (match-string-no-properties 2)))
  11996. (extendp (string-match-p "\\+\\'" key))
  11997. (key-base (if extendp (substring key 0 -1) key))
  11998. (value (match-string-no-properties 3)))
  11999. (cond
  12000. ((member-ignore-case key-base org-special-properties))
  12001. (extendp
  12002. (setq props
  12003. (org--update-property-plist key value props)))
  12004. ((member key seen-base))
  12005. (t (push key seen-base)
  12006. (let ((p (assoc-string key props t)))
  12007. (if p (setcdr p (concat value " " (cdr p)))
  12008. (push (cons key value) props))))))))))))
  12009. (unless (assoc "CATEGORY" props)
  12010. (push (cons "CATEGORY" (org-get-category beg)) props)
  12011. (when (string= specific "CATEGORY") (throw 'exit props)))
  12012. ;; Return value.
  12013. props)))))
  12014. (defun org--property-local-values (property literal-nil)
  12015. "Return value for PROPERTY in current entry.
  12016. Value is a list whose car is the base value for PROPERTY and cdr
  12017. a list of accumulated values. Return nil if neither is found in
  12018. the entry. Also return nil when PROPERTY is set to \"nil\",
  12019. unless LITERAL-NIL is non-nil."
  12020. (let ((range (org-get-property-block)))
  12021. (when range
  12022. (goto-char (car range))
  12023. (let* ((case-fold-search t)
  12024. (end (cdr range))
  12025. (value
  12026. ;; Base value.
  12027. (save-excursion
  12028. (let ((v (and (re-search-forward
  12029. (org-re-property property nil t) end t)
  12030. (match-string-no-properties 3))))
  12031. (list (if literal-nil v (org-not-nil v)))))))
  12032. ;; Find additional values.
  12033. (let* ((property+ (org-re-property (concat property "+") nil t)))
  12034. (while (re-search-forward property+ end t)
  12035. (push (match-string-no-properties 3) value)))
  12036. ;; Return final values.
  12037. (and (not (equal value '(nil))) (nreverse value))))))
  12038. (defun org--property-global-value (property literal-nil)
  12039. "Return value for PROPERTY in current buffer.
  12040. Return value is a string. Return nil if property is not set
  12041. globally. Also return nil when PROPERTY is set to \"nil\",
  12042. unless LITERAL-NIL is non-nil."
  12043. (let ((global
  12044. (cdr (or (assoc-string property org-file-properties t)
  12045. (assoc-string property org-global-properties t)
  12046. (assoc-string property org-global-properties-fixed t)))))
  12047. (if literal-nil global (org-not-nil global))))
  12048. (defun org-entry-get (pom property &optional inherit literal-nil)
  12049. "Get value of PROPERTY for entry or content at point-or-marker POM.
  12050. If INHERIT is non-nil and the entry does not have the property,
  12051. then also check higher levels of the hierarchy. If INHERIT is
  12052. the symbol `selective', use inheritance only if the setting in
  12053. `org-use-property-inheritance' selects PROPERTY for inheritance.
  12054. If the property is present but empty, the return value is the
  12055. empty string. If the property is not present at all, nil is
  12056. returned. In any other case, return the value as a string.
  12057. Search is case-insensitive.
  12058. If LITERAL-NIL is set, return the string value \"nil\" as
  12059. a string, do not interpret it as the list atom nil. This is used
  12060. for inheritance when a \"nil\" value can supersede a non-nil
  12061. value higher up the hierarchy."
  12062. (org-with-point-at pom
  12063. (cond
  12064. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  12065. ;; We need a special property. Use `org-entry-properties' to
  12066. ;; retrieve it, but specify the wanted property.
  12067. (cdr (assoc-string property (org-entry-properties nil property))))
  12068. ((and inherit
  12069. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  12070. (org-entry-get-with-inheritance property literal-nil))
  12071. (t
  12072. (let* ((local (org--property-local-values property literal-nil))
  12073. (value (and local (mapconcat #'identity (delq nil local) " "))))
  12074. (if literal-nil value (org-not-nil value)))))))
  12075. (defun org-property-or-variable-value (var &optional inherit)
  12076. "Check if there is a property fixing the value of VAR.
  12077. If yes, return this value. If not, return the current value of the variable."
  12078. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  12079. (if (and prop (stringp prop) (string-match "\\S-" prop))
  12080. (read prop)
  12081. (symbol-value var))))
  12082. (defun org-entry-delete (pom property)
  12083. "Delete PROPERTY from entry at point-or-marker POM.
  12084. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  12085. non-nil when a property was removed."
  12086. (org-with-point-at pom
  12087. (pcase (org-get-property-block)
  12088. (`(,begin . ,origin)
  12089. (let* ((end (copy-marker origin))
  12090. (re (org-re-property
  12091. (concat (regexp-quote property) "\\+?") t t)))
  12092. (goto-char begin)
  12093. (while (re-search-forward re end t)
  12094. (delete-region (match-beginning 0) (line-beginning-position 2)))
  12095. ;; If drawer is empty, remove it altogether.
  12096. (when (= begin end)
  12097. (delete-region (line-beginning-position 0)
  12098. (line-beginning-position 2)))
  12099. ;; Return non-nil if some property was removed.
  12100. (prog1 (/= end origin) (set-marker end nil))))
  12101. (_ nil))))
  12102. ;; Multi-values properties are properties that contain multiple values
  12103. ;; These values are assumed to be single words, separated by whitespace.
  12104. (defun org-entry-add-to-multivalued-property (pom property value)
  12105. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  12106. (let* ((old (org-entry-get pom property))
  12107. (values (and old (split-string old))))
  12108. (setq value (org-entry-protect-space value))
  12109. (unless (member value values)
  12110. (setq values (append values (list value)))
  12111. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12112. (defun org-entry-remove-from-multivalued-property (pom property value)
  12113. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  12114. (let* ((old (org-entry-get pom property))
  12115. (values (and old (split-string old))))
  12116. (setq value (org-entry-protect-space value))
  12117. (when (member value values)
  12118. (setq values (delete value values))
  12119. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12120. (defun org-entry-member-in-multivalued-property (pom property value)
  12121. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  12122. (let* ((old (org-entry-get pom property))
  12123. (values (and old (split-string old))))
  12124. (setq value (org-entry-protect-space value))
  12125. (member value values)))
  12126. (defun org-entry-get-multivalued-property (pom property)
  12127. "Return a list of values in a multivalued property."
  12128. (let* ((value (org-entry-get pom property))
  12129. (values (and value (split-string value))))
  12130. (mapcar #'org-entry-restore-space values)))
  12131. (defun org-entry-put-multivalued-property (pom property &rest values)
  12132. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  12133. VALUES should be a list of strings. Spaces will be protected."
  12134. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  12135. (let* ((value (org-entry-get pom property))
  12136. (values (and value (split-string value))))
  12137. (mapcar #'org-entry-restore-space values)))
  12138. (defun org-entry-protect-space (s)
  12139. "Protect spaces and newline in string S."
  12140. (while (string-match " " s)
  12141. (setq s (replace-match "%20" t t s)))
  12142. (while (string-match "\n" s)
  12143. (setq s (replace-match "%0A" t t s)))
  12144. s)
  12145. (defun org-entry-restore-space (s)
  12146. "Restore spaces and newline in string S."
  12147. (while (string-match "%20" s)
  12148. (setq s (replace-match " " t t s)))
  12149. (while (string-match "%0A" s)
  12150. (setq s (replace-match "\n" t t s)))
  12151. s)
  12152. (defvar org-entry-property-inherited-from (make-marker)
  12153. "Marker pointing to the entry from where a property was inherited.
  12154. Each call to `org-entry-get-with-inheritance' will set this marker to the
  12155. location of the entry where the inheritance search matched. If there was
  12156. no match, the marker will point nowhere.
  12157. Note that also `org-entry-get' calls this function, if the INHERIT flag
  12158. is set.")
  12159. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  12160. "Get PROPERTY of entry or content at point, search higher levels if needed.
  12161. The search will stop at the first ancestor which has the property defined.
  12162. If the value found is \"nil\", return nil to show that the property
  12163. should be considered as undefined (this is the meaning of nil here).
  12164. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  12165. (move-marker org-entry-property-inherited-from nil)
  12166. (org-with-wide-buffer
  12167. (let (value)
  12168. (catch 'exit
  12169. (while t
  12170. (let ((v (org--property-local-values property literal-nil)))
  12171. (when v
  12172. (setq value
  12173. (concat (mapconcat #'identity (delq nil v) " ")
  12174. (and value " ")
  12175. value)))
  12176. (cond
  12177. ((car v)
  12178. (org-back-to-heading t)
  12179. (move-marker org-entry-property-inherited-from (point))
  12180. (throw 'exit nil))
  12181. ((org-up-heading-safe))
  12182. (t
  12183. (let ((global (org--property-global-value property literal-nil)))
  12184. (cond ((not global))
  12185. (value (setq value (concat global " " value)))
  12186. (t (setq value global))))
  12187. (throw 'exit nil))))))
  12188. (if literal-nil value (org-not-nil value)))))
  12189. (defvar org-property-changed-functions nil
  12190. "Hook called when the value of a property has changed.
  12191. Each hook function should accept two arguments, the name of the property
  12192. and the new value.")
  12193. (defun org-entry-put (pom property value)
  12194. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  12195. If the value is nil, it is converted to the empty string. If it
  12196. is not a string, an error is raised. Also raise an error on
  12197. invalid property names.
  12198. PROPERTY can be any regular property (see
  12199. `org-special-properties'). It can also be \"TODO\",
  12200. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  12201. For the last two properties, VALUE may have any of the special
  12202. values \"earlier\" and \"later\". The function then increases or
  12203. decreases scheduled or deadline date by one day."
  12204. (cond ((null value) (setq value ""))
  12205. ((not (stringp value)) (error "Properties values should be strings"))
  12206. ((not (org--valid-property-p property))
  12207. (user-error "Invalid property name: \"%s\"" property)))
  12208. (org-with-point-at pom
  12209. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12210. (org-back-to-heading t)
  12211. (org-with-limited-levels (org-back-to-heading t)))
  12212. (let ((beg (point)))
  12213. (cond
  12214. ((equal property "TODO")
  12215. (cond ((not (org-string-nw-p value)) (setq value 'none))
  12216. ((not (member value org-todo-keywords-1))
  12217. (user-error "\"%s\" is not a valid TODO state" value)))
  12218. (org-todo value)
  12219. (org-align-tags))
  12220. ((equal property "PRIORITY")
  12221. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  12222. (org-align-tags))
  12223. ((equal property "SCHEDULED")
  12224. (forward-line)
  12225. (if (and (looking-at-p org-planning-line-re)
  12226. (re-search-forward
  12227. org-scheduled-time-regexp (line-end-position) t))
  12228. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12229. ((string= value "later") (org-timestamp-change 1 'day))
  12230. ((string= value "") (org-schedule '(4)))
  12231. (t (org-schedule nil value)))
  12232. (if (member value '("earlier" "later" ""))
  12233. (call-interactively #'org-schedule)
  12234. (org-schedule nil value))))
  12235. ((equal property "DEADLINE")
  12236. (forward-line)
  12237. (if (and (looking-at-p org-planning-line-re)
  12238. (re-search-forward
  12239. org-deadline-time-regexp (line-end-position) t))
  12240. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12241. ((string= value "later") (org-timestamp-change 1 'day))
  12242. ((string= value "") (org-deadline '(4)))
  12243. (t (org-deadline nil value)))
  12244. (if (member value '("earlier" "later" ""))
  12245. (call-interactively #'org-deadline)
  12246. (org-deadline nil value))))
  12247. ((member property org-special-properties)
  12248. (error "The %s property cannot be set with `org-entry-put'" property))
  12249. (t
  12250. (let* ((range (org-get-property-block beg 'force))
  12251. (end (cdr range))
  12252. (case-fold-search t))
  12253. (goto-char (car range))
  12254. (if (re-search-forward (org-re-property property nil t) end t)
  12255. (progn (delete-region (match-beginning 0) (match-end 0))
  12256. (goto-char (match-beginning 0)))
  12257. (goto-char end)
  12258. (insert "\n")
  12259. (backward-char))
  12260. (insert ":" property ":")
  12261. (when value (insert " " value))
  12262. (org-indent-line)))))
  12263. (run-hook-with-args 'org-property-changed-functions property value)))
  12264. (defun org-buffer-property-keys (&optional specials defaults columns)
  12265. "Get all property keys in the current buffer.
  12266. When SPECIALS is non-nil, also list the special properties that
  12267. reflect things like tags and TODO state.
  12268. When DEFAULTS is non-nil, also include properties that has
  12269. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  12270. DESCRIPTION, LOCATION, and LOGGING and others.
  12271. When COLUMNS in non-nil, also include property names given in
  12272. COLUMN formats in the current buffer."
  12273. (let ((case-fold-search t)
  12274. (props (append
  12275. (and specials org-special-properties)
  12276. (and defaults (cons org-effort-property org-default-properties))
  12277. nil)))
  12278. (org-with-wide-buffer
  12279. (goto-char (point-min))
  12280. (while (re-search-forward org-property-start-re nil t)
  12281. (catch :skip
  12282. (let ((range (org-get-property-block)))
  12283. (unless range (throw :skip nil))
  12284. (goto-char (car range))
  12285. (let ((begin (car range))
  12286. (end (cdr range)))
  12287. ;; Make sure that found property block is not located
  12288. ;; before current point, as it would generate an infloop.
  12289. ;; It can happen, for example, in the following
  12290. ;; situation:
  12291. ;;
  12292. ;; * Headline
  12293. ;; :PROPERTIES:
  12294. ;; ...
  12295. ;; :END:
  12296. ;; *************** Inlinetask
  12297. ;; #+BEGIN_EXAMPLE
  12298. ;; :PROPERTIES:
  12299. ;; #+END_EXAMPLE
  12300. ;;
  12301. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  12302. (while (< (point) end)
  12303. (let ((p (progn (looking-at org-property-re)
  12304. (match-string-no-properties 2))))
  12305. ;; Only add true property name, not extension symbol.
  12306. (push (if (not (string-match-p "\\+\\'" p)) p
  12307. (substring p 0 -1))
  12308. props))
  12309. (forward-line))))
  12310. (outline-next-heading)))
  12311. (when columns
  12312. (goto-char (point-min))
  12313. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  12314. (let ((element (org-element-at-point)))
  12315. (when (memq (org-element-type element) '(keyword node-property))
  12316. (let ((value (org-element-property :value element))
  12317. (start 0))
  12318. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  12319. \\(?:{[^}]+}\\)?"
  12320. value start)
  12321. (setq start (match-end 0))
  12322. (let ((p (match-string-no-properties 1 value)))
  12323. (unless (member-ignore-case p org-special-properties)
  12324. (push p props))))))))))
  12325. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  12326. (defun org-property-values (key)
  12327. "List all non-nil values of property KEY in current buffer."
  12328. (org-with-wide-buffer
  12329. (goto-char (point-min))
  12330. (let ((case-fold-search t)
  12331. (re (org-re-property key))
  12332. values)
  12333. (while (re-search-forward re nil t)
  12334. (push (org-entry-get (point) key) values))
  12335. (delete-dups values))))
  12336. (defun org-insert-property-drawer ()
  12337. "Insert a property drawer into the current entry.
  12338. Do nothing if the drawer already exists. The newly created
  12339. drawer is immediately hidden."
  12340. (org-with-wide-buffer
  12341. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12342. (org-back-to-heading t)
  12343. (org-with-limited-levels (org-back-to-heading t)))
  12344. (forward-line)
  12345. (when (looking-at-p org-planning-line-re) (forward-line))
  12346. (unless (looking-at-p org-property-drawer-re)
  12347. ;; Make sure we start editing a line from current entry, not from
  12348. ;; next one. It prevents extending text properties or overlays
  12349. ;; belonging to the latter.
  12350. (when (bolp) (backward-char))
  12351. (let ((begin (1+ (point)))
  12352. (inhibit-read-only t))
  12353. (insert "\n:PROPERTIES:\n:END:")
  12354. (org-flag-drawer t nil (line-end-position 0) (point))
  12355. (when (eobp) (insert "\n"))
  12356. (org-indent-region begin (point))))))
  12357. (defun org-insert-drawer (&optional arg drawer)
  12358. "Insert a drawer at point.
  12359. When optional argument ARG is non-nil, insert a property drawer.
  12360. Optional argument DRAWER, when non-nil, is a string representing
  12361. drawer's name. Otherwise, the user is prompted for a name.
  12362. If a region is active, insert the drawer around that region
  12363. instead.
  12364. Point is left between drawer's boundaries."
  12365. (interactive "P")
  12366. (let* ((drawer (if arg "PROPERTIES"
  12367. (or drawer (read-from-minibuffer "Drawer: ")))))
  12368. (cond
  12369. ;; With C-u, fall back on `org-insert-property-drawer'
  12370. (arg (org-insert-property-drawer))
  12371. ;; Check validity of suggested drawer's name.
  12372. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  12373. (user-error "Invalid drawer name"))
  12374. ;; With an active region, insert a drawer at point.
  12375. ((not (org-region-active-p))
  12376. (progn
  12377. (unless (bolp) (insert "\n"))
  12378. (insert (format ":%s:\n\n:END:\n" drawer))
  12379. (forward-line -2)))
  12380. ;; Otherwise, insert the drawer at point
  12381. (t
  12382. (let ((rbeg (region-beginning))
  12383. (rend (copy-marker (region-end))))
  12384. (unwind-protect
  12385. (progn
  12386. (goto-char rbeg)
  12387. (beginning-of-line)
  12388. (when (save-excursion
  12389. (re-search-forward org-outline-regexp-bol rend t))
  12390. (user-error "Drawers cannot contain headlines"))
  12391. ;; Position point at the beginning of the first
  12392. ;; non-blank line in region. Insert drawer's opening
  12393. ;; there, then indent it.
  12394. (org-skip-whitespace)
  12395. (beginning-of-line)
  12396. (insert ":" drawer ":\n")
  12397. (forward-line -1)
  12398. (indent-for-tab-command)
  12399. ;; Move point to the beginning of the first blank line
  12400. ;; after the last non-blank line in region. Insert
  12401. ;; drawer's closing, then indent it.
  12402. (goto-char rend)
  12403. (skip-chars-backward " \r\t\n")
  12404. (insert "\n:END:")
  12405. (deactivate-mark t)
  12406. (indent-for-tab-command)
  12407. (unless (eolp) (insert "\n")))
  12408. ;; Clear marker, whatever the outcome of insertion is.
  12409. (set-marker rend nil)))))))
  12410. (defvar org-property-set-functions-alist nil
  12411. "Property set function alist.
  12412. Each entry should have the following format:
  12413. (PROPERTY . READ-FUNCTION)
  12414. The read function will be called with the same argument as
  12415. `org-completing-read'.")
  12416. (defun org-set-property-function (property)
  12417. "Get the function that should be used to set PROPERTY.
  12418. This is computed according to `org-property-set-functions-alist'."
  12419. (or (cdr (assoc property org-property-set-functions-alist))
  12420. 'org-completing-read))
  12421. (defun org-read-property-value (property &optional pom)
  12422. "Read value for PROPERTY, as a string.
  12423. When optional argument POM is non-nil, completion uses additional
  12424. information, i.e., allowed or existing values at point or marker
  12425. POM."
  12426. (let* ((completion-ignore-case t)
  12427. (allowed
  12428. (or (org-property-get-allowed-values nil property 'table)
  12429. (and pom (org-property-get-allowed-values pom property 'table))))
  12430. (current (org-entry-get nil property))
  12431. (prompt (format "%s value%s: "
  12432. property
  12433. (if (org-string-nw-p current)
  12434. (format " [%s]" current)
  12435. "")))
  12436. (set-function (org-set-property-function property)))
  12437. (org-trim
  12438. (if allowed
  12439. (funcall set-function
  12440. prompt allowed nil
  12441. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  12442. (let ((all (mapcar #'list
  12443. (append (org-property-values property)
  12444. (and pom
  12445. (org-with-point-at pom
  12446. (org-property-values property)))))))
  12447. (funcall set-function prompt all nil nil "" nil current))))))
  12448. (defvar org-last-set-property nil)
  12449. (defvar org-last-set-property-value nil)
  12450. (defun org-read-property-name ()
  12451. "Read a property name."
  12452. (let ((completion-ignore-case t)
  12453. (default-prop (or (and (org-at-property-p)
  12454. (match-string-no-properties 2))
  12455. org-last-set-property)))
  12456. (org-completing-read
  12457. (concat "Property"
  12458. (if default-prop (concat " [" default-prop "]") "")
  12459. ": ")
  12460. (mapcar #'list (org-buffer-property-keys nil t t))
  12461. nil nil nil nil default-prop)))
  12462. (defun org-set-property-and-value (use-last)
  12463. "Allow to set [PROPERTY]: [value] direction from prompt.
  12464. When use-default, don't even ask, just use the last
  12465. \"[PROPERTY]: [value]\" string from the history."
  12466. (interactive "P")
  12467. (let* ((completion-ignore-case t)
  12468. (pv (or (and use-last org-last-set-property-value)
  12469. (org-completing-read
  12470. "Enter a \"[Property]: [value]\" pair: "
  12471. nil nil nil nil nil
  12472. org-last-set-property-value)))
  12473. prop val)
  12474. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12475. (setq prop (match-string 1 pv)
  12476. val (match-string 2 pv))
  12477. (org-set-property prop val))))
  12478. (defun org-set-property (property value)
  12479. "In the current entry, set PROPERTY to VALUE.
  12480. When called interactively, this will prompt for a property name, offering
  12481. completion on existing and default properties. And then it will prompt
  12482. for a value, offering completion either on allowed values (via an inherited
  12483. xxx_ALL property) or on existing values in other instances of this property
  12484. in the current file.
  12485. Throw an error when trying to set a property with an invalid name."
  12486. (interactive (list nil nil))
  12487. (let ((property (or property (org-read-property-name))))
  12488. ;; `org-entry-put' also makes the following check, but this one
  12489. ;; avoids polluting `org-last-set-property' and
  12490. ;; `org-last-set-property-value' needlessly.
  12491. (unless (org--valid-property-p property)
  12492. (user-error "Invalid property name: \"%s\"" property))
  12493. (let ((value (or value (org-read-property-value property)))
  12494. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12495. (setq org-last-set-property property)
  12496. (setq org-last-set-property-value (concat property ": " value))
  12497. ;; Possibly postprocess the inserted value:
  12498. (when fn (setq value (funcall fn value)))
  12499. (unless (equal (org-entry-get nil property) value)
  12500. (org-entry-put nil property value)))))
  12501. (defun org-find-property (property &optional value)
  12502. "Find first entry in buffer that sets PROPERTY.
  12503. When optional argument VALUE is non-nil, only consider an entry
  12504. if it contains PROPERTY set to this value. If PROPERTY should be
  12505. explicitly set to nil, use string \"nil\" for VALUE.
  12506. Return position where the entry begins, or nil if there is no
  12507. such entry. If narrowing is in effect, only search the visible
  12508. part of the buffer."
  12509. (save-excursion
  12510. (goto-char (point-min))
  12511. (let ((case-fold-search t)
  12512. (re (org-re-property property nil (not value) value)))
  12513. (catch 'exit
  12514. (while (re-search-forward re nil t)
  12515. (when (if value (org-at-property-p)
  12516. (org-entry-get (point) property nil t))
  12517. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  12518. (defun org-delete-property (property)
  12519. "In the current entry, delete PROPERTY."
  12520. (interactive
  12521. (let* ((completion-ignore-case t)
  12522. (cat (org-entry-get (point) "CATEGORY"))
  12523. (props0 (org-entry-properties nil 'standard))
  12524. (props (if cat props0
  12525. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12526. (prop (if (< 1 (length props))
  12527. (completing-read "Property: " props nil t)
  12528. (caar props))))
  12529. (list prop)))
  12530. (if (not property)
  12531. (message "No property to delete in this entry")
  12532. (org-entry-delete nil property)
  12533. (message "Property \"%s\" deleted" property)))
  12534. (defun org-delete-property-globally (property)
  12535. "Remove PROPERTY globally, from all entries.
  12536. This function ignores narrowing, if any."
  12537. (interactive
  12538. (let* ((completion-ignore-case t)
  12539. (prop (completing-read
  12540. "Globally remove property: "
  12541. (mapcar #'list (org-buffer-property-keys)))))
  12542. (list prop)))
  12543. (org-with-wide-buffer
  12544. (goto-char (point-min))
  12545. (let ((count 0)
  12546. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12547. (while (re-search-forward re nil t)
  12548. (when (org-entry-delete (point) property) (cl-incf count)))
  12549. (message "Property \"%s\" removed from %d entries" property count))))
  12550. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12551. (defun org-compute-property-at-point ()
  12552. "Compute the property at point.
  12553. This looks for an enclosing column format, extracts the operator and
  12554. then applies it to the property in the column format's scope."
  12555. (interactive)
  12556. (unless (org-at-property-p)
  12557. (user-error "Not at a property"))
  12558. (let ((prop (match-string-no-properties 2)))
  12559. (org-columns-get-format-and-top-level)
  12560. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12561. (user-error "No operator defined for property %s" prop))
  12562. (org-columns-compute prop)))
  12563. (defvar org-property-allowed-value-functions nil
  12564. "Hook for functions supplying allowed values for a specific property.
  12565. The functions must take a single argument, the name of the property, and
  12566. return a flat list of allowed values. If \":ETC\" is one of
  12567. the values, this means that these values are intended as defaults for
  12568. completion, but that other values should be allowed too.
  12569. The functions must return nil if they are not responsible for this
  12570. property.")
  12571. (defun org-property-get-allowed-values (pom property &optional table)
  12572. "Get allowed values for the property PROPERTY.
  12573. When TABLE is non-nil, return an alist that can directly be used for
  12574. completion."
  12575. (let (vals)
  12576. (cond
  12577. ((equal property "TODO")
  12578. (setq vals (org-with-point-at pom
  12579. (append org-todo-keywords-1 '("")))))
  12580. ((equal property "PRIORITY")
  12581. (let ((n org-lowest-priority))
  12582. (while (>= n org-highest-priority)
  12583. (push (char-to-string n) vals)
  12584. (setq n (1- n)))))
  12585. ((equal property "CATEGORY"))
  12586. ((member property org-special-properties))
  12587. ((setq vals (run-hook-with-args-until-success
  12588. 'org-property-allowed-value-functions property)))
  12589. (t
  12590. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12591. (when (and vals (string-match "\\S-" vals))
  12592. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12593. (setq vals (mapcar (lambda (x)
  12594. (cond ((stringp x) x)
  12595. ((numberp x) (number-to-string x))
  12596. ((symbolp x) (symbol-name x))
  12597. (t "???")))
  12598. vals)))))
  12599. (when (member ":ETC" vals)
  12600. (setq vals (remove ":ETC" vals))
  12601. (org-add-props (car vals) '(org-unrestricted t)))
  12602. (if table (mapcar 'list vals) vals)))
  12603. (defun org-property-previous-allowed-value (&optional _previous)
  12604. "Switch to the next allowed value for this property."
  12605. (interactive)
  12606. (org-property-next-allowed-value t))
  12607. (defun org-property-next-allowed-value (&optional previous)
  12608. "Switch to the next allowed value for this property."
  12609. (interactive)
  12610. (unless (org-at-property-p)
  12611. (user-error "Not at a property"))
  12612. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12613. (key (match-string 2))
  12614. (value (match-string 3))
  12615. (allowed (or (org-property-get-allowed-values (point) key)
  12616. (and (member value '("[ ]" "[-]" "[X]"))
  12617. '("[ ]" "[X]"))))
  12618. (heading (save-match-data (nth 4 (org-heading-components))))
  12619. nval)
  12620. (unless allowed
  12621. (user-error "Allowed values for this property have not been defined"))
  12622. (when previous (setq allowed (reverse allowed)))
  12623. (when (member value allowed)
  12624. (setq nval (car (cdr (member value allowed)))))
  12625. (setq nval (or nval (car allowed)))
  12626. (when (equal nval value)
  12627. (user-error "Only one allowed value for this property"))
  12628. (org-at-property-p)
  12629. (replace-match (concat " :" key ": " nval) t t)
  12630. (org-indent-line)
  12631. (beginning-of-line 1)
  12632. (skip-chars-forward " \t")
  12633. (when (equal prop org-effort-property)
  12634. (org-refresh-property
  12635. '((effort . identity)
  12636. (effort-minutes . org-duration-to-minutes))
  12637. nval)
  12638. (when (string= org-clock-current-task heading)
  12639. (setq org-clock-effort nval)
  12640. (org-clock-update-mode-line)))
  12641. (run-hook-with-args 'org-property-changed-functions key nval)))
  12642. (defun org-find-olp (path &optional this-buffer)
  12643. "Return a marker pointing to the entry at outline path OLP.
  12644. If anything goes wrong, throw an error.
  12645. You can wrap this call to catch the error like this:
  12646. (condition-case msg
  12647. (org-mobile-locate-entry (match-string 4))
  12648. (error (nth 1 msg)))
  12649. The return value will then be either a string with the error message,
  12650. or a marker if everything is OK.
  12651. If THIS-BUFFER is set, the outline path does not contain a file,
  12652. only headings."
  12653. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12654. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12655. (level 1)
  12656. (lmin 1)
  12657. (lmax 1)
  12658. end found flevel)
  12659. (unless buffer (error "File not found :%s" file))
  12660. (with-current-buffer buffer
  12661. (unless (derived-mode-p 'org-mode)
  12662. (error "Buffer %s needs to be in Org mode" buffer))
  12663. (org-with-wide-buffer
  12664. (goto-char (point-min))
  12665. (dolist (heading path)
  12666. (let ((re (format org-complex-heading-regexp-format
  12667. (regexp-quote heading)))
  12668. (cnt 0))
  12669. (while (re-search-forward re end t)
  12670. (setq level (- (match-end 1) (match-beginning 1)))
  12671. (when (and (>= level lmin) (<= level lmax))
  12672. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12673. (when (= cnt 0)
  12674. (error "Heading not found on level %d: %s" lmax heading))
  12675. (when (> cnt 1)
  12676. (error "Heading not unique on level %d: %s" lmax heading))
  12677. (goto-char found)
  12678. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12679. (setq end (save-excursion (org-end-of-subtree t t)))))
  12680. (when (org-at-heading-p)
  12681. (point-marker))))))
  12682. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12683. "Find node HEADING in BUFFER.
  12684. Return a marker to the heading if it was found, or nil if not.
  12685. If POS-ONLY is set, return just the position instead of a marker.
  12686. The heading text must match exact, but it may have a TODO keyword,
  12687. a priority cookie and tags in the standard locations."
  12688. (with-current-buffer (or buffer (current-buffer))
  12689. (org-with-wide-buffer
  12690. (goto-char (point-min))
  12691. (let (case-fold-search)
  12692. (when (re-search-forward
  12693. (format org-complex-heading-regexp-format
  12694. (regexp-quote heading)) nil t)
  12695. (if pos-only
  12696. (match-beginning 0)
  12697. (move-marker (make-marker) (match-beginning 0))))))))
  12698. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12699. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12700. When the target headline is found, return a marker to this location."
  12701. (let ((files (directory-files (or dir default-directory)
  12702. t "\\`[^.#].*\\.org\\'"))
  12703. visiting m buffer)
  12704. (catch 'found
  12705. (dolist (file files)
  12706. (message "trying %s" file)
  12707. (setq visiting (org-find-base-buffer-visiting file))
  12708. (setq buffer (or visiting (find-file-noselect file)))
  12709. (setq m (org-find-exact-headline-in-buffer
  12710. heading buffer))
  12711. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12712. (and m (throw 'found m))))))
  12713. (defun org-find-entry-with-id (ident)
  12714. "Locate the entry that contains the ID property with exact value IDENT.
  12715. IDENT can be a string, a symbol or a number, this function will search for
  12716. the string representation of it.
  12717. Return the position where this entry starts, or nil if there is no such entry."
  12718. (interactive "sID: ")
  12719. (let ((id (cond
  12720. ((stringp ident) ident)
  12721. ((symbolp ident) (symbol-name ident))
  12722. ((numberp ident) (number-to-string ident))
  12723. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12724. (org-with-wide-buffer (org-find-property "ID" id))))
  12725. ;;;; Timestamps
  12726. (defvar org-last-changed-timestamp nil)
  12727. (defvar org-last-inserted-timestamp nil
  12728. "The last time stamp inserted with `org-insert-time-stamp'.")
  12729. (defun org-time-stamp (arg &optional inactive)
  12730. "Prompt for a date/time and insert a time stamp.
  12731. If the user specifies a time like HH:MM or if this command is
  12732. called with at least one prefix argument, the time stamp contains
  12733. the date and the time. Otherwise, only the date is included.
  12734. All parts of a date not specified by the user are filled in from
  12735. the timestamp at point, if any, or the current date/time
  12736. otherwise.
  12737. If there is already a timestamp at the cursor, it is replaced.
  12738. With two universal prefix arguments, insert an active timestamp
  12739. with the current time without prompting the user.
  12740. When called from lisp, the timestamp is inactive if INACTIVE is
  12741. non-nil."
  12742. (interactive "P")
  12743. (let* ((ts (cond
  12744. ((org-at-date-range-p t)
  12745. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12746. ((org-at-timestamp-p 'lax) (match-string 0))))
  12747. ;; Default time is either the timestamp at point or today.
  12748. ;; When entering a range, only the range start is considered.
  12749. (default-time (and ts (org-time-string-to-time ts)))
  12750. (default-input (and ts (org-get-compact-tod ts)))
  12751. (repeater (and ts
  12752. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12753. (match-string 0 ts)))
  12754. org-time-was-given
  12755. org-end-time-was-given
  12756. (time
  12757. (if (equal arg '(16)) (current-time)
  12758. ;; Preserve `this-command' and `last-command'.
  12759. (let ((this-command this-command)
  12760. (last-command last-command))
  12761. (org-read-date
  12762. arg 'totime nil nil default-time default-input
  12763. inactive)))))
  12764. (cond
  12765. ((and ts
  12766. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12767. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12768. (insert "--")
  12769. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12770. (ts
  12771. ;; Make sure we're on a timestamp. When in the middle of a date
  12772. ;; range, move arbitrarily to range end.
  12773. (unless (org-at-timestamp-p 'lax)
  12774. (skip-chars-forward "-")
  12775. (org-at-timestamp-p 'lax))
  12776. (replace-match "")
  12777. (setq org-last-changed-timestamp
  12778. (org-insert-time-stamp
  12779. time (or org-time-was-given arg)
  12780. inactive nil nil (list org-end-time-was-given)))
  12781. (when repeater
  12782. (backward-char)
  12783. (insert " " repeater)
  12784. (setq org-last-changed-timestamp
  12785. (concat (substring org-last-inserted-timestamp 0 -1)
  12786. " " repeater ">")))
  12787. (message "Timestamp updated"))
  12788. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12789. (t (org-insert-time-stamp
  12790. time (or org-time-was-given arg) inactive nil nil
  12791. (list org-end-time-was-given))))))
  12792. ;; FIXME: can we use this for something else, like computing time differences?
  12793. (defun org-get-compact-tod (s)
  12794. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12795. (let* ((t1 (match-string 1 s))
  12796. (h1 (string-to-number (match-string 2 s)))
  12797. (m1 (string-to-number (match-string 3 s)))
  12798. (t2 (and (match-end 4) (match-string 5 s)))
  12799. (h2 (and t2 (string-to-number (match-string 6 s))))
  12800. (m2 (and t2 (string-to-number (match-string 7 s))))
  12801. dh dm)
  12802. (if (not t2)
  12803. t1
  12804. (setq dh (- h2 h1) dm (- m2 m1))
  12805. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12806. (concat t1 "+" (number-to-string dh)
  12807. (and (/= 0 dm) (format ":%02d" dm)))))))
  12808. (defun org-time-stamp-inactive (&optional arg)
  12809. "Insert an inactive time stamp.
  12810. An inactive time stamp is enclosed in square brackets instead of angle
  12811. brackets. It is inactive in the sense that it does not trigger agenda entries,
  12812. does not link to the calendar and cannot be changed with the S-cursor keys.
  12813. So these are more for recording a certain time/date.
  12814. If the user specifies a time like HH:MM or if this command is called with
  12815. at least one prefix argument, the time stamp contains the date and the time.
  12816. Otherwise, only the date is included.
  12817. When called with two universal prefix arguments, insert an active time stamp
  12818. with the current time without prompting the user."
  12819. (interactive "P")
  12820. (org-time-stamp arg 'inactive))
  12821. (defvar org-date-ovl (make-overlay 1 1))
  12822. (overlay-put org-date-ovl 'face 'org-date-selected)
  12823. (delete-overlay org-date-ovl)
  12824. (defvar org-ans1) ; dynamically scoped parameter
  12825. (defvar org-ans2) ; dynamically scoped parameter
  12826. (defvar org-plain-time-of-day-regexp) ; defined below
  12827. (defvar org-overriding-default-time nil) ; dynamically scoped
  12828. (defvar org-read-date-overlay nil)
  12829. (defvar org-dcst nil) ; dynamically scoped
  12830. (defvar org-read-date-history nil)
  12831. (defvar org-read-date-final-answer nil)
  12832. (defvar org-read-date-analyze-futurep nil)
  12833. (defvar org-read-date-analyze-forced-year nil)
  12834. (defvar org-read-date-inactive)
  12835. (defvar org-def)
  12836. (defvar org-defdecode)
  12837. (defvar org-with-time)
  12838. (defvar calendar-setup) ; Dynamically scoped.
  12839. (defun org-read-date (&optional with-time to-time from-string prompt
  12840. default-time default-input inactive)
  12841. "Read a date, possibly a time, and make things smooth for the user.
  12842. The prompt will suggest to enter an ISO date, but you can also enter anything
  12843. which will at least partially be understood by `parse-time-string'.
  12844. Unrecognized parts of the date will default to the current day, month, year,
  12845. hour and minute. If this command is called to replace a timestamp at point,
  12846. or to enter the second timestamp of a range, the default time is taken
  12847. from the existing stamp. Furthermore, the command prefers the future,
  12848. so if you are giving a date where the year is not given, and the day-month
  12849. combination is already past in the current year, it will assume you
  12850. mean next year. For details, see the manual. A few examples:
  12851. 3-2-5 --> 2003-02-05
  12852. feb 15 --> currentyear-02-15
  12853. 2/15 --> currentyear-02-15
  12854. sep 12 9 --> 2009-09-12
  12855. 12:45 --> today 12:45
  12856. 22 sept 0:34 --> currentyear-09-22 0:34
  12857. 12 --> currentyear-currentmonth-12
  12858. Fri --> nearest Friday after today
  12859. -Tue --> last Tuesday
  12860. etc.
  12861. Furthermore you can specify a relative date by giving, as the *first* thing
  12862. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12863. change in days weeks, months, years.
  12864. With a single plus or minus, the date is relative to today. With a double
  12865. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12866. +4d --> four days from today
  12867. +4 --> same as above
  12868. +2w --> two weeks from today
  12869. ++5 --> five days from default date
  12870. The function understands only English month and weekday abbreviations.
  12871. While prompting, a calendar is popped up - you can also select the
  12872. date with the mouse (button 1). The calendar shows a period of three
  12873. months. To scroll it to other months, use the keys `>' and `<'.
  12874. If you don't like the calendar, turn it off with
  12875. (setq org-read-date-popup-calendar nil)
  12876. With optional argument TO-TIME, the date will immediately be converted
  12877. to an internal time.
  12878. With an optional argument WITH-TIME, the prompt will suggest to
  12879. also insert a time. Note that when WITH-TIME is not set, you can
  12880. still enter a time, and this function will inform the calling routine
  12881. about this change. The calling routine may then choose to change the
  12882. format used to insert the time stamp into the buffer to include the time.
  12883. With optional argument FROM-STRING, read from this string instead from
  12884. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12885. the time/date that is used for everything that is not specified by the
  12886. user."
  12887. (require 'parse-time)
  12888. (let* ((org-with-time with-time)
  12889. (org-time-stamp-rounding-minutes
  12890. (if (equal org-with-time '(16))
  12891. '(0 0)
  12892. org-time-stamp-rounding-minutes))
  12893. (org-dcst org-display-custom-times)
  12894. (ct (org-current-time))
  12895. (org-def (or org-overriding-default-time default-time ct))
  12896. (org-defdecode (decode-time org-def))
  12897. (cur-frame (selected-frame))
  12898. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12899. (calendar-setup
  12900. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12901. (calendar-move-hook nil)
  12902. (calendar-view-diary-initially-flag nil)
  12903. (calendar-view-holidays-initially-flag nil)
  12904. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12905. ;; Rationalize `org-def' and `org-defdecode', if required.
  12906. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12907. (setf (nth 2 org-defdecode) -1)
  12908. (setf (nth 1 org-defdecode) 59)
  12909. (setq org-def (apply #'encode-time org-defdecode))
  12910. (setq org-defdecode (decode-time org-def)))
  12911. (let* ((timestr (format-time-string
  12912. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12913. org-def))
  12914. (prompt (concat (if prompt (concat prompt " ") "")
  12915. (format "Date+time [%s]: " timestr))))
  12916. (cond
  12917. (from-string (setq ans from-string))
  12918. (org-read-date-popup-calendar
  12919. (save-excursion
  12920. (save-window-excursion
  12921. (calendar)
  12922. (when (eq calendar-setup 'calendar-only)
  12923. (setq cal-frame
  12924. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12925. (select-frame cal-frame))
  12926. (org-eval-in-calendar '(setq cursor-type nil) t)
  12927. (unwind-protect
  12928. (progn
  12929. (calendar-forward-day (- (time-to-days org-def)
  12930. (calendar-absolute-from-gregorian
  12931. (calendar-current-date))))
  12932. (org-eval-in-calendar nil t)
  12933. (let* ((old-map (current-local-map))
  12934. (map (copy-keymap calendar-mode-map))
  12935. (minibuffer-local-map
  12936. (copy-keymap org-read-date-minibuffer-local-map)))
  12937. (org-defkey map (kbd "RET") 'org-calendar-select)
  12938. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12939. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12940. (unwind-protect
  12941. (progn
  12942. (use-local-map map)
  12943. (setq org-read-date-inactive inactive)
  12944. (add-hook 'post-command-hook 'org-read-date-display)
  12945. (setq org-ans0
  12946. (read-string prompt
  12947. default-input
  12948. 'org-read-date-history
  12949. nil))
  12950. ;; org-ans0: from prompt
  12951. ;; org-ans1: from mouse click
  12952. ;; org-ans2: from calendar motion
  12953. (setq ans
  12954. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12955. (remove-hook 'post-command-hook 'org-read-date-display)
  12956. (use-local-map old-map)
  12957. (when org-read-date-overlay
  12958. (delete-overlay org-read-date-overlay)
  12959. (setq org-read-date-overlay nil)))))
  12960. (bury-buffer "*Calendar*")
  12961. (when cal-frame
  12962. (delete-frame cal-frame)
  12963. (select-frame-set-input-focus cur-frame))))))
  12964. (t ; Naked prompt only
  12965. (unwind-protect
  12966. (setq ans (read-string prompt default-input
  12967. 'org-read-date-history timestr))
  12968. (when org-read-date-overlay
  12969. (delete-overlay org-read-date-overlay)
  12970. (setq org-read-date-overlay nil))))))
  12971. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12972. (when org-read-date-analyze-forced-year
  12973. (message "Year was forced into %s"
  12974. (if org-read-date-force-compatible-dates
  12975. "compatible range (1970-2037)"
  12976. "range representable on this machine"))
  12977. (ding))
  12978. (setq final (apply #'encode-time final))
  12979. (setq org-read-date-final-answer ans)
  12980. (if to-time
  12981. final
  12982. ;; This round-trip gets rid of 34th of August and stuff like that....
  12983. (setq final (decode-time final))
  12984. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12985. (format "%04d-%02d-%02d %02d:%02d"
  12986. (nth 5 final) (nth 4 final) (nth 3 final)
  12987. (nth 2 final) (nth 1 final))
  12988. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12989. (defun org-read-date-display ()
  12990. "Display the current date prompt interpretation in the minibuffer."
  12991. (when org-read-date-display-live
  12992. (when org-read-date-overlay
  12993. (delete-overlay org-read-date-overlay))
  12994. (when (minibufferp (current-buffer))
  12995. (save-excursion
  12996. (end-of-line 1)
  12997. (while (not (equal (buffer-substring
  12998. (max (point-min) (- (point) 4)) (point))
  12999. " "))
  13000. (insert " ")))
  13001. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  13002. " " (or org-ans1 org-ans2)))
  13003. (org-end-time-was-given nil)
  13004. (f (org-read-date-analyze ans org-def org-defdecode))
  13005. (fmts (if org-dcst
  13006. org-time-stamp-custom-formats
  13007. org-time-stamp-formats))
  13008. (fmt (if (or org-with-time
  13009. (and (boundp 'org-time-was-given) org-time-was-given))
  13010. (cdr fmts)
  13011. (car fmts)))
  13012. (txt (format-time-string fmt (apply #'encode-time f)))
  13013. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  13014. (txt (concat "=> " txt)))
  13015. (when (and org-end-time-was-given
  13016. (string-match org-plain-time-of-day-regexp txt))
  13017. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  13018. org-end-time-was-given
  13019. (substring txt (match-end 0)))))
  13020. (when org-read-date-analyze-futurep
  13021. (setq txt (concat txt " (=>F)")))
  13022. (setq org-read-date-overlay
  13023. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  13024. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  13025. (defun org-read-date-analyze (ans def defdecode)
  13026. "Analyze the combined answer of the date prompt."
  13027. ;; FIXME: cleanup and comment
  13028. (let ((org-def def)
  13029. (org-defdecode defdecode)
  13030. (nowdecode (decode-time))
  13031. delta deltan deltaw deltadef year month day
  13032. hour minute second wday pm h2 m2 tl wday1
  13033. iso-year iso-weekday iso-week iso-date futurep kill-year)
  13034. (setq org-read-date-analyze-futurep nil
  13035. org-read-date-analyze-forced-year nil)
  13036. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  13037. (setq ans "+0"))
  13038. (when (setq delta (org-read-date-get-relative ans nil org-def))
  13039. (setq ans (replace-match "" t t ans)
  13040. deltan (car delta)
  13041. deltaw (nth 1 delta)
  13042. deltadef (nth 2 delta)))
  13043. ;; Check if there is an iso week date in there. If yes, store the
  13044. ;; info and postpone interpreting it until the rest of the parsing
  13045. ;; is done.
  13046. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  13047. (setq iso-year (when (match-end 1)
  13048. (org-small-year-to-year
  13049. (string-to-number (match-string 1 ans))))
  13050. iso-weekday (when (match-end 3)
  13051. (string-to-number (match-string 3 ans)))
  13052. iso-week (string-to-number (match-string 2 ans)))
  13053. (setq ans (replace-match "" t t ans)))
  13054. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  13055. (when (string-match
  13056. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  13057. (setq year (if (match-end 2)
  13058. (string-to-number (match-string 2 ans))
  13059. (progn (setq kill-year t)
  13060. (string-to-number (format-time-string "%Y"))))
  13061. month (string-to-number (match-string 3 ans))
  13062. day (string-to-number (match-string 4 ans)))
  13063. (setq year (org-small-year-to-year year))
  13064. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13065. t nil ans)))
  13066. ;; Help matching dotted european dates
  13067. (when (string-match
  13068. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  13069. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  13070. (setq kill-year t)
  13071. (string-to-number (format-time-string "%Y")))
  13072. day (string-to-number (match-string 1 ans))
  13073. month (string-to-number (match-string 2 ans))
  13074. ans (replace-match (format "%04d-%02d-%02d" year month day)
  13075. t nil ans)))
  13076. ;; Help matching american dates, like 5/30 or 5/30/7
  13077. (when (string-match
  13078. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  13079. (setq year (if (match-end 4)
  13080. (string-to-number (match-string 4 ans))
  13081. (progn (setq kill-year t)
  13082. (string-to-number (format-time-string "%Y"))))
  13083. month (string-to-number (match-string 1 ans))
  13084. day (string-to-number (match-string 2 ans)))
  13085. (setq year (org-small-year-to-year year))
  13086. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13087. t nil ans)))
  13088. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  13089. ;; If there is a time with am/pm, and *no* time without it, we convert
  13090. ;; so that matching will be successful.
  13091. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  13092. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  13093. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  13094. (setq hour (string-to-number (match-string 1 ans))
  13095. minute (if (match-end 3)
  13096. (string-to-number (match-string 3 ans))
  13097. 0)
  13098. pm (equal ?p
  13099. (string-to-char (downcase (match-string 4 ans)))))
  13100. (if (and (= hour 12) (not pm))
  13101. (setq hour 0)
  13102. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  13103. (setq ans (replace-match (format "%02d:%02d" hour minute)
  13104. t t ans))))
  13105. ;; Check if a time range is given as a duration
  13106. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  13107. (setq hour (string-to-number (match-string 1 ans))
  13108. h2 (+ hour (string-to-number (match-string 3 ans)))
  13109. minute (string-to-number (match-string 2 ans))
  13110. m2 (+ minute (if (match-end 5) (string-to-number
  13111. (match-string 5 ans))0)))
  13112. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  13113. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  13114. t t ans)))
  13115. ;; Check if there is a time range
  13116. (when (boundp 'org-end-time-was-given)
  13117. (setq org-time-was-given nil)
  13118. (when (and (string-match org-plain-time-of-day-regexp ans)
  13119. (match-end 8))
  13120. (setq org-end-time-was-given (match-string 8 ans))
  13121. (setq ans (concat (substring ans 0 (match-beginning 7))
  13122. (substring ans (match-end 7))))))
  13123. (setq tl (parse-time-string ans)
  13124. day (or (nth 3 tl) (nth 3 org-defdecode))
  13125. month
  13126. (cond ((nth 4 tl))
  13127. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  13128. ;; Day was specified. Make sure DAY+MONTH
  13129. ;; combination happens in the future.
  13130. ((nth 3 tl)
  13131. (setq futurep t)
  13132. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  13133. (nth 4 nowdecode)))
  13134. (t (nth 4 org-defdecode)))
  13135. year
  13136. (cond ((and (not kill-year) (nth 5 tl)))
  13137. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  13138. ;; Month was guessed in the future and is at least
  13139. ;; equal to NOWDECODE's. Fix year accordingly.
  13140. (futurep
  13141. (if (or (> month (nth 4 nowdecode))
  13142. (>= day (nth 3 nowdecode)))
  13143. (nth 5 nowdecode)
  13144. (1+ (nth 5 nowdecode))))
  13145. ;; Month was specified. Make sure MONTH+YEAR
  13146. ;; combination happens in the future.
  13147. ((nth 4 tl)
  13148. (setq futurep t)
  13149. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  13150. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  13151. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  13152. (t (nth 5 nowdecode))))
  13153. (t (nth 5 org-defdecode)))
  13154. hour (or (nth 2 tl) (nth 2 org-defdecode))
  13155. minute (or (nth 1 tl) (nth 1 org-defdecode))
  13156. second (or (nth 0 tl) 0)
  13157. wday (nth 6 tl))
  13158. (when (and (eq org-read-date-prefer-future 'time)
  13159. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  13160. (equal day (nth 3 nowdecode))
  13161. (equal month (nth 4 nowdecode))
  13162. (equal year (nth 5 nowdecode))
  13163. (nth 2 tl)
  13164. (or (< (nth 2 tl) (nth 2 nowdecode))
  13165. (and (= (nth 2 tl) (nth 2 nowdecode))
  13166. (nth 1 tl)
  13167. (< (nth 1 tl) (nth 1 nowdecode)))))
  13168. (setq day (1+ day)
  13169. futurep t))
  13170. ;; Special date definitions below
  13171. (cond
  13172. (iso-week
  13173. ;; There was an iso week
  13174. (require 'cal-iso)
  13175. (setq futurep nil)
  13176. (setq year (or iso-year year)
  13177. day (or iso-weekday wday 1)
  13178. wday nil ; to make sure that the trigger below does not match
  13179. iso-date (calendar-gregorian-from-absolute
  13180. (calendar-iso-to-absolute
  13181. (list iso-week day year))))
  13182. ; FIXME: Should we also push ISO weeks into the future?
  13183. ; (when (and org-read-date-prefer-future
  13184. ; (not iso-year)
  13185. ; (< (calendar-absolute-from-gregorian iso-date)
  13186. ; (time-to-days nil)))
  13187. ; (setq year (1+ year)
  13188. ; iso-date (calendar-gregorian-from-absolute
  13189. ; (calendar-iso-to-absolute
  13190. ; (list iso-week day year)))))
  13191. (setq month (car iso-date)
  13192. year (nth 2 iso-date)
  13193. day (nth 1 iso-date)))
  13194. (deltan
  13195. (setq futurep nil)
  13196. (unless deltadef
  13197. (let ((now (decode-time)))
  13198. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  13199. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  13200. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  13201. ((equal deltaw "m") (setq month (+ month deltan)))
  13202. ((equal deltaw "y") (setq year (+ year deltan)))))
  13203. ((and wday (not (nth 3 tl)))
  13204. ;; Weekday was given, but no day, so pick that day in the week
  13205. ;; on or after the derived date.
  13206. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  13207. (unless (equal wday wday1)
  13208. (setq day (+ day (% (- wday wday1 -7) 7))))))
  13209. (when (and (boundp 'org-time-was-given)
  13210. (nth 2 tl))
  13211. (setq org-time-was-given t))
  13212. (when (< year 100) (setq year (+ 2000 year)))
  13213. ;; Check of the date is representable
  13214. (if org-read-date-force-compatible-dates
  13215. (progn
  13216. (when (< year 1970)
  13217. (setq year 1970 org-read-date-analyze-forced-year t))
  13218. (when (> year 2037)
  13219. (setq year 2037 org-read-date-analyze-forced-year t)))
  13220. (condition-case nil
  13221. (ignore (encode-time second minute hour day month year))
  13222. (error
  13223. (setq year (nth 5 org-defdecode))
  13224. (setq org-read-date-analyze-forced-year t))))
  13225. (setq org-read-date-analyze-futurep futurep)
  13226. (list second minute hour day month year)))
  13227. (defvar parse-time-weekdays)
  13228. (defun org-read-date-get-relative (s today default)
  13229. "Check string S for special relative date string.
  13230. TODAY and DEFAULT are internal times, for today and for a default.
  13231. Return shift list (N what def-flag)
  13232. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  13233. N is the number of WHATs to shift.
  13234. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  13235. the DEFAULT date rather than TODAY."
  13236. (require 'parse-time)
  13237. (when (and
  13238. (string-match
  13239. (concat
  13240. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  13241. "\\([0-9]+\\)?"
  13242. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  13243. "\\([ \t]\\|$\\)") s)
  13244. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  13245. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  13246. (string-to-char (substring (match-string 1 s) -1))
  13247. ?+))
  13248. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  13249. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  13250. (what (if (match-end 3) (match-string 3 s) "d"))
  13251. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  13252. (date (if rel default today))
  13253. (wday (nth 6 (decode-time date)))
  13254. delta)
  13255. (if wday1
  13256. (progn
  13257. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  13258. (when (= delta 0) (setq delta 7))
  13259. (when (= dir ?-)
  13260. (setq delta (- delta 7))
  13261. (when (= delta 0) (setq delta -7)))
  13262. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  13263. (list delta "d" rel))
  13264. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  13265. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  13266. "Turn a user-specified date into the internal representation.
  13267. The internal representation needed by the calendar is (month day year).
  13268. This is a wrapper to handle the brain-dead convention in calendar that
  13269. user function argument order change dependent on argument order."
  13270. (pcase calendar-date-style
  13271. (`american (list arg1 arg2 arg3))
  13272. (`european (list arg2 arg1 arg3))
  13273. (`iso (list arg2 arg3 arg1))))
  13274. (defun org-eval-in-calendar (form &optional keepdate)
  13275. "Eval FORM in the calendar window and return to current window.
  13276. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  13277. (let ((sf (selected-frame))
  13278. (sw (selected-window)))
  13279. (select-window (get-buffer-window "*Calendar*" t))
  13280. (eval form)
  13281. (when (and (not keepdate) (calendar-cursor-to-date))
  13282. (let* ((date (calendar-cursor-to-date))
  13283. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13284. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  13285. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  13286. (select-window sw)
  13287. (select-frame-set-input-focus sf)))
  13288. (defun org-calendar-select ()
  13289. "Return to `org-read-date' with the date currently selected.
  13290. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13291. (interactive)
  13292. (when (calendar-cursor-to-date)
  13293. (let* ((date (calendar-cursor-to-date))
  13294. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13295. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13296. (when (active-minibuffer-window) (exit-minibuffer))))
  13297. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  13298. "Insert a date stamp for the date given by the internal TIME.
  13299. See `format-time-string' for the format of TIME.
  13300. WITH-HM means use the stamp format that includes the time of the day.
  13301. INACTIVE means use square brackets instead of angular ones, so that the
  13302. stamp will not contribute to the agenda.
  13303. PRE and POST are optional strings to be inserted before and after the
  13304. stamp.
  13305. The command returns the inserted time stamp."
  13306. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  13307. stamp)
  13308. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  13309. (insert-before-markers (or pre ""))
  13310. (when (listp extra)
  13311. (setq extra (car extra))
  13312. (if (and (stringp extra)
  13313. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  13314. (setq extra (format "-%02d:%02d"
  13315. (string-to-number (match-string 1 extra))
  13316. (string-to-number (match-string 2 extra))))
  13317. (setq extra nil)))
  13318. (when extra
  13319. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  13320. (insert-before-markers (setq stamp (format-time-string fmt time)))
  13321. (insert-before-markers (or post ""))
  13322. (setq org-last-inserted-timestamp stamp)))
  13323. (defun org-toggle-time-stamp-overlays ()
  13324. "Toggle the use of custom time stamp formats."
  13325. (interactive)
  13326. (setq org-display-custom-times (not org-display-custom-times))
  13327. (unless org-display-custom-times
  13328. (let ((p (point-min)) (bmp (buffer-modified-p)))
  13329. (while (setq p (next-single-property-change p 'display))
  13330. (when (and (get-text-property p 'display)
  13331. (eq (get-text-property p 'face) 'org-date))
  13332. (remove-text-properties
  13333. p (setq p (next-single-property-change p 'display))
  13334. '(display t))))
  13335. (set-buffer-modified-p bmp)))
  13336. (org-restart-font-lock)
  13337. (setq org-table-may-need-update t)
  13338. (if org-display-custom-times
  13339. (message "Time stamps are overlaid with custom format")
  13340. (message "Time stamp overlays removed")))
  13341. (defun org-display-custom-time (beg end)
  13342. "Overlay modified time stamp format over timestamp between BEG and END."
  13343. (let* ((ts (buffer-substring beg end))
  13344. t1 with-hm tf time str (off 0))
  13345. (save-match-data
  13346. (setq t1 (org-parse-time-string ts t))
  13347. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  13348. (setq off (- (match-end 0) (match-beginning 0)))))
  13349. (setq end (- end off))
  13350. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  13351. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  13352. time (org-fix-decoded-time t1)
  13353. str (org-add-props
  13354. (format-time-string
  13355. (substring tf 1 -1) (apply 'encode-time time))
  13356. nil 'mouse-face 'highlight))
  13357. (put-text-property beg end 'display str)))
  13358. (defun org-fix-decoded-time (time)
  13359. "Set 0 instead of nil for the first 6 elements of time.
  13360. Don't touch the rest."
  13361. (let ((n 0))
  13362. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  13363. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  13364. "Difference between TIMESTAMP-STRING and now in days.
  13365. If SECONDS is non-nil, return the difference in seconds."
  13366. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  13367. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  13368. (funcall fdiff nil))))
  13369. (defun org-deadline-close-p (timestamp-string &optional ndays)
  13370. "Is the time in TIMESTAMP-STRING close to the current date?"
  13371. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  13372. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  13373. (not (org-entry-is-done-p))))
  13374. (defun org-get-wdays (ts &optional delay zero-delay)
  13375. "Get the deadline lead time appropriate for timestring TS.
  13376. When DELAY is non-nil, get the delay time for scheduled items
  13377. instead of the deadline lead time. When ZERO-DELAY is non-nil
  13378. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  13379. don't try to find the delay cookie in the scheduled timestamp."
  13380. (let ((tv (if delay org-scheduled-delay-days
  13381. org-deadline-warning-days)))
  13382. (cond
  13383. ((or (and delay (< tv 0))
  13384. (and delay zero-delay (<= tv 0))
  13385. (and (not delay) (<= tv 0)))
  13386. ;; Enforce this value no matter what
  13387. (- tv))
  13388. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  13389. ;; lead time is specified.
  13390. (floor (* (string-to-number (match-string 1 ts))
  13391. (cdr (assoc (match-string 2 ts)
  13392. '(("d" . 1) ("w" . 7)
  13393. ("m" . 30.4) ("y" . 365.25)
  13394. ("h" . 0.041667)))))))
  13395. ;; go for the default.
  13396. (t tv))))
  13397. (defun org-calendar-select-mouse (ev)
  13398. "Return to `org-read-date' with the date currently selected.
  13399. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13400. (interactive "e")
  13401. (mouse-set-point ev)
  13402. (when (calendar-cursor-to-date)
  13403. (let* ((date (calendar-cursor-to-date))
  13404. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13405. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13406. (when (active-minibuffer-window) (exit-minibuffer))))
  13407. (defun org-check-deadlines (ndays)
  13408. "Check if there are any deadlines due or past due.
  13409. A deadline is considered due if it happens within `org-deadline-warning-days'
  13410. days from today's date. If the deadline appears in an entry marked DONE,
  13411. it is not shown. A numeric prefix argument NDAYS can be used to test that
  13412. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  13413. are shown."
  13414. (interactive "P")
  13415. (let* ((org-warn-days
  13416. (cond
  13417. ((equal ndays '(4)) 100000)
  13418. (ndays (prefix-numeric-value ndays))
  13419. (t (abs org-deadline-warning-days))))
  13420. (case-fold-search nil)
  13421. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  13422. (callback
  13423. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  13424. (message "%d deadlines past-due or due within %d days"
  13425. (org-occur regexp nil callback)
  13426. org-warn-days)))
  13427. (defsubst org-re-timestamp (type)
  13428. "Return a regexp for timestamp TYPE.
  13429. Allowed values for TYPE are:
  13430. all: all timestamps
  13431. active: only active timestamps (<...>)
  13432. inactive: only inactive timestamps ([...])
  13433. scheduled: only scheduled timestamps
  13434. deadline: only deadline timestamps
  13435. closed: only closed time-stamps
  13436. When TYPE is nil, fall back on returning a regexp that matches
  13437. both scheduled and deadline timestamps."
  13438. (cl-case type
  13439. (all org-ts-regexp-both)
  13440. (active org-ts-regexp)
  13441. (inactive org-ts-regexp-inactive)
  13442. (scheduled org-scheduled-time-regexp)
  13443. (deadline org-deadline-time-regexp)
  13444. (closed org-closed-time-regexp)
  13445. (otherwise
  13446. (concat "\\<"
  13447. (regexp-opt (list org-deadline-string org-scheduled-string))
  13448. " *<\\([^>]+\\)>"))))
  13449. (defun org-check-before-date (d)
  13450. "Check if there are deadlines or scheduled entries before date D."
  13451. (interactive (list (org-read-date)))
  13452. (let* ((case-fold-search nil)
  13453. (regexp (org-re-timestamp org-ts-type))
  13454. (ts-type org-ts-type)
  13455. (callback
  13456. (lambda ()
  13457. (let ((match (match-string 1)))
  13458. (and (if (memq ts-type '(active inactive all))
  13459. (eq (org-element-type (save-excursion
  13460. (backward-char)
  13461. (org-element-context)))
  13462. 'timestamp)
  13463. (org-at-planning-p))
  13464. (time-less-p
  13465. (org-time-string-to-time match)
  13466. (org-time-string-to-time d)))))))
  13467. (message "%d entries before %s"
  13468. (org-occur regexp nil callback)
  13469. d)))
  13470. (defun org-check-after-date (d)
  13471. "Check if there are deadlines or scheduled entries after date D."
  13472. (interactive (list (org-read-date)))
  13473. (let* ((case-fold-search nil)
  13474. (regexp (org-re-timestamp org-ts-type))
  13475. (ts-type org-ts-type)
  13476. (callback
  13477. (lambda ()
  13478. (let ((match (match-string 1)))
  13479. (and (if (memq ts-type '(active inactive all))
  13480. (eq (org-element-type (save-excursion
  13481. (backward-char)
  13482. (org-element-context)))
  13483. 'timestamp)
  13484. (org-at-planning-p))
  13485. (not (time-less-p
  13486. (org-time-string-to-time match)
  13487. (org-time-string-to-time d))))))))
  13488. (message "%d entries after %s"
  13489. (org-occur regexp nil callback)
  13490. d)))
  13491. (defun org-check-dates-range (start-date end-date)
  13492. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13493. (interactive (list (org-read-date nil nil nil "Range starts")
  13494. (org-read-date nil nil nil "Range end")))
  13495. (let ((case-fold-search nil)
  13496. (regexp (org-re-timestamp org-ts-type))
  13497. (callback
  13498. (let ((type org-ts-type))
  13499. (lambda ()
  13500. (let ((match (match-string 1)))
  13501. (and
  13502. (if (memq type '(active inactive all))
  13503. (eq (org-element-type (save-excursion
  13504. (backward-char)
  13505. (org-element-context)))
  13506. 'timestamp)
  13507. (org-at-planning-p))
  13508. (not (time-less-p
  13509. (org-time-string-to-time match)
  13510. (org-time-string-to-time start-date)))
  13511. (time-less-p
  13512. (org-time-string-to-time match)
  13513. (org-time-string-to-time end-date))))))))
  13514. (message "%d entries between %s and %s"
  13515. (org-occur regexp nil callback) start-date end-date)))
  13516. (defun org-evaluate-time-range (&optional to-buffer)
  13517. "Evaluate a time range by computing the difference between start and end.
  13518. Normally the result is just printed in the echo area, but with prefix arg
  13519. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13520. If the time range is actually in a table, the result is inserted into the
  13521. next column.
  13522. For time difference computation, a year is assumed to be exactly 365
  13523. days in order to avoid rounding problems."
  13524. (interactive "P")
  13525. (or
  13526. (org-clock-update-time-maybe)
  13527. (save-excursion
  13528. (unless (org-at-date-range-p t)
  13529. (goto-char (point-at-bol))
  13530. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13531. (unless (org-at-date-range-p t)
  13532. (user-error "Not at a time-stamp range, and none found in current line")))
  13533. (let* ((ts1 (match-string 1))
  13534. (ts2 (match-string 2))
  13535. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13536. (match-end (match-end 0))
  13537. (time1 (org-time-string-to-time ts1))
  13538. (time2 (org-time-string-to-time ts2))
  13539. (diff (abs (float-time (time-subtract time2 time1))))
  13540. (negative (time-less-p time2 time1))
  13541. ;; (ys (floor (* 365 24 60 60)))
  13542. (ds (* 24 60 60))
  13543. (hs (* 60 60))
  13544. (fy "%dy %dd %02d:%02d")
  13545. (fy1 "%dy %dd")
  13546. (fd "%dd %02d:%02d")
  13547. (fd1 "%dd")
  13548. (fh "%02d:%02d")
  13549. y d h m align)
  13550. (if havetime
  13551. (setq ; y (floor diff ys) diff (mod diff ys)
  13552. y 0
  13553. d (floor diff ds) diff (mod diff ds)
  13554. h (floor diff hs) diff (mod diff hs)
  13555. m (floor diff 60))
  13556. (setq ; y (floor diff ys) diff (mod diff ys)
  13557. y 0
  13558. d (round diff ds)
  13559. h 0 m 0))
  13560. (if (not to-buffer)
  13561. (message "%s" (org-make-tdiff-string y d h m))
  13562. (if (org-at-table-p)
  13563. (progn
  13564. (goto-char match-end)
  13565. (setq align t)
  13566. (and (looking-at " *|") (goto-char (match-end 0))))
  13567. (goto-char match-end))
  13568. (when (looking-at
  13569. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13570. (replace-match ""))
  13571. (when negative (insert " -"))
  13572. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13573. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13574. (insert " " (format fh h m))))
  13575. (when align (org-table-align))
  13576. (message "Time difference inserted")))))
  13577. (defun org-make-tdiff-string (y d h m)
  13578. (let ((fmt "")
  13579. (l nil))
  13580. (when (> y 0)
  13581. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13582. (push y l))
  13583. (when (> d 0)
  13584. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13585. (push d l))
  13586. (when (> h 0)
  13587. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13588. (push h l))
  13589. (when (> m 0)
  13590. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13591. (push m l))
  13592. (apply 'format fmt (nreverse l))))
  13593. (defun org-time-string-to-time (s)
  13594. "Convert timestamp string S into internal time."
  13595. (apply #'encode-time (org-parse-time-string s)))
  13596. (defun org-time-string-to-seconds (s)
  13597. "Convert a timestamp string S into a number of seconds."
  13598. (float-time (org-time-string-to-time s)))
  13599. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13600. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13601. "Convert time stamp S to an absolute day number.
  13602. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13603. stamp, get the closest date to DAYNR. If PREFER is
  13604. `past' (respectively `future') return a date past (respectively
  13605. after) or equal to DAYNR.
  13606. POS is the location of time stamp S, as a buffer position in
  13607. BUFFER.
  13608. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13609. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13610. signaled."
  13611. (cond
  13612. ((string-match "\\`%%\\((.*)\\)" s)
  13613. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13614. ;; only able to match individual dates. If it fails, raise an
  13615. ;; error.
  13616. (if (and daynr
  13617. (org-diary-sexp-entry
  13618. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13619. daynr
  13620. (signal 'org-diary-sexp-no-match (list s))))
  13621. (daynr (org-closest-date s daynr prefer))
  13622. (t (time-to-days
  13623. (condition-case errdata
  13624. (org-time-string-to-time s)
  13625. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13626. s
  13627. (if (not (and buffer pos)) ""
  13628. (format-message " at %d in buffer `%s'" pos buffer))
  13629. (cdr errdata))))))))
  13630. (defun org-days-to-iso-week (days)
  13631. "Return the iso week number."
  13632. (require 'cal-iso)
  13633. (car (calendar-iso-from-absolute days)))
  13634. (defun org-small-year-to-year (year)
  13635. "Convert 2-digit years into 4-digit years.
  13636. YEAR is expanded into one of the 30 next years, if possible, or
  13637. into a past one. Any year larger than 99 is returned unchanged."
  13638. (if (>= year 100) year
  13639. (let* ((current (string-to-number (format-time-string "%Y")))
  13640. (century (/ current 100))
  13641. (offset (- year (% current 100))))
  13642. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13643. ((> offset -70) (+ (* century 100) year))
  13644. (t (+ (* (1+ century) 100) year))))))
  13645. (defun org-time-from-absolute (d)
  13646. "Return the time corresponding to date D.
  13647. D may be an absolute day number, or a calendar-type list (month day year)."
  13648. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13649. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13650. (defvar org-agenda-current-date)
  13651. (defun org-calendar-holiday ()
  13652. "List of holidays, for Diary display in Org mode."
  13653. (require 'holidays)
  13654. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13655. (and hl (mapconcat #'identity hl "; "))))
  13656. (defun org-diary-sexp-entry (sexp entry d)
  13657. "Process a SEXP diary ENTRY for date D."
  13658. (require 'diary-lib)
  13659. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13660. ;; dynamically.
  13661. (let* ((sexp `(let ((entry ,entry)
  13662. (date ',d))
  13663. ,(car (read-from-string sexp))))
  13664. (result (if calendar-debug-sexp (eval sexp)
  13665. (condition-case nil
  13666. (eval sexp)
  13667. (error
  13668. (beep)
  13669. (message "Bad sexp at line %d in %s: %s"
  13670. (org-current-line)
  13671. (buffer-file-name) sexp)
  13672. (sleep-for 2))))))
  13673. (cond ((stringp result) (split-string result "; "))
  13674. ((and (consp result)
  13675. (not (consp (cdr result)))
  13676. (stringp (cdr result))) (cdr result))
  13677. ((and (consp result)
  13678. (stringp (car result))) result)
  13679. (result entry))))
  13680. (defun org-diary-to-ical-string (frombuf)
  13681. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13682. This uses the icalendar.el library."
  13683. (let* ((tmpdir temporary-file-directory)
  13684. (tmpfile (make-temp-name
  13685. (expand-file-name "orgics" tmpdir)))
  13686. buf rtn b e)
  13687. (with-current-buffer frombuf
  13688. (icalendar-export-region (point-min) (point-max) tmpfile)
  13689. (setq buf (find-buffer-visiting tmpfile))
  13690. (set-buffer buf)
  13691. (goto-char (point-min))
  13692. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13693. (setq b (match-beginning 0)))
  13694. (goto-char (point-max))
  13695. (when (re-search-backward "^END:VEVENT" nil t)
  13696. (setq e (match-end 0)))
  13697. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13698. (kill-buffer buf)
  13699. (delete-file tmpfile)
  13700. rtn))
  13701. (defun org-closest-date (start current prefer)
  13702. "Return closest date to CURRENT starting from START.
  13703. CURRENT and START are both time stamps.
  13704. When PREFER is `past', return a date that is either CURRENT or
  13705. past. When PREFER is `future', return a date that is either
  13706. CURRENT or future.
  13707. Only time stamps with a repeater are modified. Any other time
  13708. stamp stay unchanged. In any case, return value is an absolute
  13709. day number."
  13710. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13711. ;; No repeater. Do not shift time stamp.
  13712. (time-to-days (org-time-string-to-time start))
  13713. (let ((value (string-to-number (match-string 1 start)))
  13714. (type (match-string 2 start)))
  13715. (if (= 0 value)
  13716. ;; Repeater with a 0-value is considered as void.
  13717. (time-to-days (org-time-string-to-time start))
  13718. (let* ((base (org-date-to-gregorian start))
  13719. (target (org-date-to-gregorian current))
  13720. (sday (calendar-absolute-from-gregorian base))
  13721. (cday (calendar-absolute-from-gregorian target))
  13722. n1 n2)
  13723. ;; If START is already past CURRENT, just return START.
  13724. (if (<= cday sday) sday
  13725. ;; Compute closest date before (N1) and closest date past
  13726. ;; (N2) CURRENT.
  13727. (pcase type
  13728. ("h"
  13729. (let ((missing-hours
  13730. (mod (+ (- (* 24 (- cday sday))
  13731. (nth 2 (org-parse-time-string start)))
  13732. org-extend-today-until)
  13733. value)))
  13734. (setf n1 (if (= missing-hours 0) cday
  13735. (- cday (1+ (/ missing-hours 24)))))
  13736. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13737. ((or "d" "w")
  13738. (let ((value (if (equal type "w") (* 7 value) value)))
  13739. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13740. (setf n2 (+ n1 value))))
  13741. ("m"
  13742. (let* ((add-months
  13743. (lambda (d n)
  13744. ;; Add N months to gregorian date D, i.e.,
  13745. ;; a list (MONTH DAY YEAR). Return a valid
  13746. ;; gregorian date.
  13747. (let ((m (+ (nth 0 d) n)))
  13748. (list (mod m 12)
  13749. (nth 1 d)
  13750. (+ (/ m 12) (nth 2 d))))))
  13751. (months ; Complete months to TARGET.
  13752. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13753. (- (nth 0 target) (nth 0 base))
  13754. ;; If START's day is greater than
  13755. ;; TARGET's, remove incomplete month.
  13756. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13757. value)
  13758. value))
  13759. (before (funcall add-months base months)))
  13760. (setf n1 (calendar-absolute-from-gregorian before))
  13761. (setf n2
  13762. (calendar-absolute-from-gregorian
  13763. (funcall add-months before value)))))
  13764. (_
  13765. (let* ((d (nth 1 base))
  13766. (m (nth 0 base))
  13767. (y (nth 2 base))
  13768. (years ; Complete years to TARGET.
  13769. (* (/ (- (nth 2 target)
  13770. y
  13771. ;; If START's month and day are
  13772. ;; greater than TARGET's, remove
  13773. ;; incomplete year.
  13774. (if (or (> (nth 0 target) m)
  13775. (and (= (nth 0 target) m)
  13776. (> (nth 1 target) d)))
  13777. 0
  13778. 1))
  13779. value)
  13780. value))
  13781. (before (list m d (+ y years))))
  13782. (setf n1 (calendar-absolute-from-gregorian before))
  13783. (setf n2 (calendar-absolute-from-gregorian
  13784. (list m d (+ (nth 2 before) value)))))))
  13785. ;; Handle PREFER parameter, if any.
  13786. (cond
  13787. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13788. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13789. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13790. (defun org-date-to-gregorian (d)
  13791. "Turn any specification of date D into a Gregorian date for the calendar."
  13792. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13793. ((and (listp d) (= (length d) 3)) d)
  13794. ((stringp d)
  13795. (let ((d (org-parse-time-string d)))
  13796. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13797. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13798. (defun org-timestamp-up (&optional arg)
  13799. "Increase the date item at the cursor by one.
  13800. If the cursor is on the year, change the year. If it is on the month,
  13801. the day or the time, change that. If the cursor is on the enclosing
  13802. bracket, change the timestamp type.
  13803. With prefix ARG, change by that many units."
  13804. (interactive "p")
  13805. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13806. (defun org-timestamp-down (&optional arg)
  13807. "Decrease the date item at the cursor by one.
  13808. If the cursor is on the year, change the year. If it is on the month,
  13809. the day or the time, change that. If the cursor is on the enclosing
  13810. bracket, change the timestamp type.
  13811. With prefix ARG, change by that many units."
  13812. (interactive "p")
  13813. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13814. (defun org-timestamp-up-day (&optional arg)
  13815. "Increase the date in the time stamp by one day.
  13816. With prefix ARG, change that many days."
  13817. (interactive "p")
  13818. (if (and (not (org-at-timestamp-p 'lax))
  13819. (org-at-heading-p))
  13820. (org-todo 'up)
  13821. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13822. (defun org-timestamp-down-day (&optional arg)
  13823. "Decrease the date in the time stamp by one day.
  13824. With prefix ARG, change that many days."
  13825. (interactive "p")
  13826. (if (and (not (org-at-timestamp-p 'lax))
  13827. (org-at-heading-p))
  13828. (org-todo 'down)
  13829. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13830. (defun org-at-timestamp-p (&optional extended)
  13831. "Non-nil if point is inside a timestamp.
  13832. By default, the function only consider syntactically valid active
  13833. timestamps. However, the caller may have a broader definition
  13834. for timestamps. As a consequence, optional argument EXTENDED can
  13835. be set to the following values
  13836. `inactive'
  13837. Include also syntactically valid inactive timestamps.
  13838. `agenda'
  13839. Include timestamps allowed in Agenda, i.e., those in
  13840. properties drawers, planning lines and clock lines.
  13841. `lax'
  13842. Ignore context. The function matches any part of the
  13843. document looking like a timestamp. This includes comments,
  13844. example blocks...
  13845. For backward-compatibility with Org 9.0, every other non-nil
  13846. value is equivalent to `inactive'.
  13847. When at a timestamp, return the position of the point as a symbol
  13848. among `bracket', `after', `year', `month', `hour', `minute',
  13849. `day' or a number of character from the last know part of the
  13850. time stamp.
  13851. When matching, the match groups are the following:
  13852. group 1: year
  13853. group 2: month
  13854. group 3: day number
  13855. group 4: day name
  13856. group 5: hours, if any
  13857. group 6: minutes, if any"
  13858. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13859. (pos (point))
  13860. (match?
  13861. (let ((boundaries (org-in-regexp regexp)))
  13862. (save-match-data
  13863. (cond ((null boundaries) nil)
  13864. ((eq extended 'lax) t)
  13865. (t
  13866. (or (and (eq extended 'agenda)
  13867. (or (org-at-planning-p)
  13868. (org-at-property-p)
  13869. (and (bound-and-true-p
  13870. org-agenda-include-inactive-timestamps)
  13871. (org-at-clock-log-p))))
  13872. (eq 'timestamp
  13873. (save-excursion
  13874. (when (= pos (cdr boundaries)) (forward-char -1))
  13875. (org-element-type (org-element-context)))))))))))
  13876. (cond
  13877. ((not match?) nil)
  13878. ((= pos (match-beginning 0)) 'bracket)
  13879. ;; Distinguish location right before the closing bracket from
  13880. ;; right after it.
  13881. ((= pos (1- (match-end 0))) 'bracket)
  13882. ((= pos (match-end 0)) 'after)
  13883. ((org-pos-in-match-range pos 2) 'year)
  13884. ((org-pos-in-match-range pos 3) 'month)
  13885. ((org-pos-in-match-range pos 7) 'hour)
  13886. ((org-pos-in-match-range pos 8) 'minute)
  13887. ((or (org-pos-in-match-range pos 4)
  13888. (org-pos-in-match-range pos 5)) 'day)
  13889. ((and (> pos (or (match-end 8) (match-end 5)))
  13890. (< pos (match-end 0)))
  13891. (- pos (or (match-end 8) (match-end 5))))
  13892. (t 'day))))
  13893. (defun org-toggle-timestamp-type ()
  13894. "Toggle the type (<active> or [inactive]) of a time stamp."
  13895. (interactive)
  13896. (when (org-at-timestamp-p 'lax)
  13897. (let ((beg (match-beginning 0)) (end (match-end 0))
  13898. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13899. (save-excursion
  13900. (goto-char beg)
  13901. (while (re-search-forward "[][<>]" end t)
  13902. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13903. t t)))
  13904. (message "Timestamp is now %sactive"
  13905. (if (equal (char-after beg) ?<) "" "in")))))
  13906. (defun org-at-clock-log-p ()
  13907. "Non-nil if point is on a clock log line."
  13908. (and (org-match-line org-clock-line-re)
  13909. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13910. (defvar org-clock-history) ; defined in org-clock.el
  13911. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13912. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13913. "Change the date in the time stamp at point.
  13914. The date is changed by N times WHAT. WHAT can be `day', `month',
  13915. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13916. position in the timestamp determines what is changed.
  13917. When optional argument UPDOWN is non-nil, minutes are rounded
  13918. according to `org-time-stamp-rounding-minutes'.
  13919. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13920. \"--2d\"."
  13921. (let ((origin (point))
  13922. (timestamp? (org-at-timestamp-p 'lax))
  13923. origin-cat
  13924. with-hm inactive
  13925. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13926. extra rem
  13927. ts time time0 fixnext clrgx)
  13928. (unless timestamp? (user-error "Not at a timestamp"))
  13929. (if (and (not what) (eq timestamp? 'bracket))
  13930. (org-toggle-timestamp-type)
  13931. ;; Point isn't on brackets. Remember the part of the time-stamp
  13932. ;; the point was in. Indeed, size of time-stamps may change,
  13933. ;; but point must be kept in the same category nonetheless.
  13934. (setq origin-cat timestamp?)
  13935. (when (and (not what) (not (eq timestamp? 'day))
  13936. org-display-custom-times
  13937. (get-text-property (point) 'display)
  13938. (not (get-text-property (1- (point)) 'display)))
  13939. (setq timestamp? 'day))
  13940. (setq timestamp? (or what timestamp?)
  13941. inactive (= (char-after (match-beginning 0)) ?\[)
  13942. ts (match-string 0))
  13943. (replace-match "")
  13944. (when (string-match
  13945. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13946. ts)
  13947. (setq extra (match-string 1 ts))
  13948. (when suppress-tmp-delay
  13949. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13950. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13951. (setq with-hm t))
  13952. (setq time0 (org-parse-time-string ts))
  13953. (when (and updown
  13954. (eq timestamp? 'minute)
  13955. (not current-prefix-arg))
  13956. ;; This looks like s-up and s-down. Change by one rounding step.
  13957. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13958. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13959. (setcar (cdr time0) (+ (nth 1 time0)
  13960. (if (> n 0) (- rem) (- dm rem))))))
  13961. (setq time
  13962. (apply #'encode-time
  13963. (or (car time0) 0)
  13964. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13965. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13966. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13967. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13968. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13969. (nthcdr 6 time0)))
  13970. (when (and (memq timestamp? '(hour minute))
  13971. extra
  13972. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13973. (setq extra (org-modify-ts-extra
  13974. extra
  13975. (if (eq timestamp? 'hour) 2 5)
  13976. n dm)))
  13977. (when (integerp timestamp?)
  13978. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13979. (when (eq what 'calendar)
  13980. (let ((cal-date (org-get-date-from-calendar)))
  13981. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13982. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13983. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13984. (setcar time0 (or (car time0) 0))
  13985. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13986. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13987. (setq time (apply 'encode-time time0))))
  13988. ;; Insert the new time-stamp, and ensure point stays in the same
  13989. ;; category as before (i.e. not after the last position in that
  13990. ;; category).
  13991. (let ((pos (point)))
  13992. ;; Stay before inserted string. `save-excursion' is of no use.
  13993. (setq org-last-changed-timestamp
  13994. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13995. (goto-char pos))
  13996. (save-match-data
  13997. (looking-at org-ts-regexp3)
  13998. (goto-char
  13999. (pcase origin-cat
  14000. ;; `day' category ends before `hour' if any, or at the end
  14001. ;; of the day name.
  14002. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  14003. (`hour (min (match-end 7) origin))
  14004. (`minute (min (1- (match-end 8)) origin))
  14005. ((pred integerp) (min (1- (match-end 0)) origin))
  14006. ;; Point was right after the time-stamp. However, the
  14007. ;; time-stamp length might have changed, so refer to
  14008. ;; (match-end 0) instead.
  14009. (`after (match-end 0))
  14010. ;; `year' and `month' have both fixed size: point couldn't
  14011. ;; have moved into another part.
  14012. (_ origin))))
  14013. ;; Update clock if on a CLOCK line.
  14014. (org-clock-update-time-maybe)
  14015. ;; Maybe adjust the closest clock in `org-clock-history'
  14016. (when org-clock-adjust-closest
  14017. (if (not (and (org-at-clock-log-p)
  14018. (< 1 (length (delq nil (mapcar 'marker-position
  14019. org-clock-history))))))
  14020. (message "No clock to adjust")
  14021. (cond ((save-excursion ; fix previous clock?
  14022. (re-search-backward org-ts-regexp0 nil t)
  14023. (looking-back (concat org-clock-string " \\[")
  14024. (line-beginning-position)))
  14025. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  14026. ((save-excursion ; fix next clock?
  14027. (re-search-backward org-ts-regexp0 nil t)
  14028. (looking-at (concat org-ts-regexp0 "\\] =>")))
  14029. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  14030. (save-window-excursion
  14031. ;; Find closest clock to point, adjust the previous/next one in history
  14032. (let* ((p (save-excursion (org-back-to-heading t)))
  14033. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  14034. (clfixnth
  14035. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  14036. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  14037. (if (not clfixpos)
  14038. (message "No clock to adjust")
  14039. (save-excursion
  14040. (org-goto-marker-or-bmk clfixpos)
  14041. (org-show-subtree)
  14042. (when (re-search-forward clrgx nil t)
  14043. (goto-char (match-beginning 1))
  14044. (let (org-clock-adjust-closest)
  14045. (org-timestamp-change n timestamp? updown))
  14046. (message "Clock adjusted in %s for heading: %s"
  14047. (file-name-nondirectory (buffer-file-name))
  14048. (org-get-heading t t)))))))))
  14049. ;; Try to recenter the calendar window, if any.
  14050. (when (and org-calendar-follow-timestamp-change
  14051. (get-buffer-window "*Calendar*" t)
  14052. (memq timestamp? '(day month year)))
  14053. (org-recenter-calendar (time-to-days time))))))
  14054. (defun org-modify-ts-extra (s pos n dm)
  14055. "Change the different parts of the lead-time and repeat fields in timestamp."
  14056. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  14057. ng h m new rem)
  14058. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  14059. (cond
  14060. ((or (org-pos-in-match-range pos 2)
  14061. (org-pos-in-match-range pos 3))
  14062. (setq m (string-to-number (match-string 3 s))
  14063. h (string-to-number (match-string 2 s)))
  14064. (if (org-pos-in-match-range pos 2)
  14065. (setq h (+ h n))
  14066. (setq n (* dm (with-no-warnings (cl-signum n))))
  14067. (unless (= 0 (setq rem (% m dm)))
  14068. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  14069. (setq m (+ m n)))
  14070. (when (< m 0) (setq m (+ m 60) h (1- h)))
  14071. (when (> m 59) (setq m (- m 60) h (1+ h)))
  14072. (setq h (mod h 24))
  14073. (setq ng 1 new (format "-%02d:%02d" h m)))
  14074. ((org-pos-in-match-range pos 6)
  14075. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  14076. ((org-pos-in-match-range pos 5)
  14077. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  14078. ((org-pos-in-match-range pos 9)
  14079. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  14080. ((org-pos-in-match-range pos 8)
  14081. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  14082. (when ng
  14083. (setq s (concat
  14084. (substring s 0 (match-beginning ng))
  14085. new
  14086. (substring s (match-end ng))))))
  14087. s))
  14088. (defun org-recenter-calendar (d)
  14089. "If the calendar is visible, recenter it to date D."
  14090. (let ((cwin (get-buffer-window "*Calendar*" t)))
  14091. (when cwin
  14092. (let ((calendar-move-hook nil))
  14093. (with-selected-window cwin
  14094. (calendar-goto-date
  14095. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  14096. (defun org-goto-calendar (&optional arg)
  14097. "Go to the Emacs calendar at the current date.
  14098. If there is a time stamp in the current line, go to that date.
  14099. A prefix ARG can be used to force the current date."
  14100. (interactive "P")
  14101. (let ((calendar-move-hook nil)
  14102. (calendar-view-holidays-initially-flag nil)
  14103. (calendar-view-diary-initially-flag nil)
  14104. diff)
  14105. (when (or (org-at-timestamp-p 'lax)
  14106. (org-match-line (concat ".*" org-ts-regexp)))
  14107. (let ((d1 (time-to-days nil))
  14108. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  14109. (setq diff (- d2 d1))))
  14110. (calendar)
  14111. (calendar-goto-today)
  14112. (when (and diff (not arg)) (calendar-forward-day diff))))
  14113. (defun org-get-date-from-calendar ()
  14114. "Return a list (month day year) of date at point in calendar."
  14115. (with-current-buffer "*Calendar*"
  14116. (save-match-data
  14117. (calendar-cursor-to-date))))
  14118. (defun org-date-from-calendar ()
  14119. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  14120. If there is already a time stamp at the cursor position, update it."
  14121. (interactive)
  14122. (if (org-at-timestamp-p 'lax)
  14123. (org-timestamp-change 0 'calendar)
  14124. (let ((cal-date (org-get-date-from-calendar)))
  14125. (org-insert-time-stamp
  14126. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  14127. (defcustom org-image-actual-width t
  14128. "When non-nil, use the actual width of images when inlining them.
  14129. When set to a number, use imagemagick (when available) to set the
  14130. image's width to this value.
  14131. When set to a number in a list, try to get the width from any
  14132. #+ATTR.* keyword if it matches a width specification like
  14133. #+ATTR_HTML: :width 300px
  14134. and fall back on that number if none is found.
  14135. When set to nil, try to get the width from an #+ATTR.* keyword
  14136. and fall back on the original width if none is found.
  14137. When set to any other non-nil value, always use the image width.
  14138. This requires Emacs >= 24.1, built with imagemagick support."
  14139. :group 'org-appearance
  14140. :version "24.4"
  14141. :package-version '(Org . "8.0")
  14142. :type '(choice
  14143. (const :tag "Use the image width" t)
  14144. (integer :tag "Use a number of pixels")
  14145. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  14146. (const :tag "Use #+ATTR* or don't resize" nil)))
  14147. (defcustom org-agenda-inhibit-startup nil
  14148. "Inhibit startup when preparing agenda buffers.
  14149. When this variable is t, the initialization of the Org agenda
  14150. buffers is inhibited: e.g. the visibility state is not set, the
  14151. tables are not re-aligned, etc."
  14152. :type 'boolean
  14153. :version "24.3"
  14154. :group 'org-agenda)
  14155. (defcustom org-agenda-ignore-properties nil
  14156. "Avoid updating text properties when building the agenda.
  14157. Properties are used to prepare buffers for effort estimates,
  14158. appointments, statistics and subtree-local categories.
  14159. If you don't use these in the agenda, you can add them to this
  14160. list and agenda building will be a bit faster.
  14161. The value is a list, with zero or more of the symbols `effort', `appt',
  14162. `stats' or `category'."
  14163. :type '(set :greedy t
  14164. (const effort)
  14165. (const appt)
  14166. (const stats)
  14167. (const category))
  14168. :version "26.1"
  14169. :package-version '(Org . "8.3")
  14170. :group 'org-agenda)
  14171. ;;;; Files
  14172. (defun org-save-all-org-buffers ()
  14173. "Save all Org buffers without user confirmation."
  14174. (interactive)
  14175. (message "Saving all Org buffers...")
  14176. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  14177. (when (featurep 'org-id) (org-id-locations-save))
  14178. (message "Saving all Org buffers... done"))
  14179. (defun org-revert-all-org-buffers ()
  14180. "Revert all Org buffers.
  14181. Prompt for confirmation when there are unsaved changes.
  14182. Be sure you know what you are doing before letting this function
  14183. overwrite your changes.
  14184. This function is useful in a setup where one tracks Org files
  14185. with a version control system, to revert on one machine after pulling
  14186. changes from another. I believe the procedure must be like this:
  14187. 1. M-x org-save-all-org-buffers
  14188. 2. Pull changes from the other machine, resolve conflicts
  14189. 3. M-x org-revert-all-org-buffers"
  14190. (interactive)
  14191. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  14192. (user-error "Abort"))
  14193. (save-excursion
  14194. (save-window-excursion
  14195. (dolist (b (buffer-list))
  14196. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  14197. (with-current-buffer b buffer-file-name))
  14198. (pop-to-buffer-same-window b)
  14199. (revert-buffer t 'no-confirm)))
  14200. (when (and (featurep 'org-id) org-id-track-globally)
  14201. (org-id-locations-load)))))
  14202. ;;;; Agenda files
  14203. ;;;###autoload
  14204. (defun org-switchb (&optional arg)
  14205. "Switch between Org buffers.
  14206. With `\\[universal-argument]' prefix, restrict available buffers to files.
  14207. With `\\[universal-argument] \\[universal-argument]' \
  14208. prefix, restrict available buffers to agenda files."
  14209. (interactive "P")
  14210. (let ((blist (org-buffer-list
  14211. (cond ((equal arg '(4)) 'files)
  14212. ((equal arg '(16)) 'agenda)))))
  14213. (pop-to-buffer-same-window
  14214. (completing-read "Org buffer: "
  14215. (mapcar #'list (mapcar #'buffer-name blist))
  14216. nil t))))
  14217. (defun org-buffer-list (&optional predicate exclude-tmp)
  14218. "Return a list of Org buffers.
  14219. PREDICATE can be `export', `files' or `agenda'.
  14220. export restrict the list to Export buffers.
  14221. files restrict the list to buffers visiting Org files.
  14222. agenda restrict the list to buffers visiting agenda files.
  14223. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  14224. (let* ((bfn nil)
  14225. (agenda-files (and (eq predicate 'agenda)
  14226. (mapcar 'file-truename (org-agenda-files t))))
  14227. (filter
  14228. (cond
  14229. ((eq predicate 'files)
  14230. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  14231. ((eq predicate 'export)
  14232. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  14233. ((eq predicate 'agenda)
  14234. (lambda (b)
  14235. (with-current-buffer b
  14236. (and (derived-mode-p 'org-mode)
  14237. (setq bfn (buffer-file-name b))
  14238. (member (file-truename bfn) agenda-files)))))
  14239. (t (lambda (b) (with-current-buffer b
  14240. (or (derived-mode-p 'org-mode)
  14241. (string-match "\\*Org .*Export"
  14242. (buffer-name b)))))))))
  14243. (delq nil
  14244. (mapcar
  14245. (lambda(b)
  14246. (if (and (funcall filter b)
  14247. (or (not exclude-tmp)
  14248. (not (string-match "tmp" (buffer-name b)))))
  14249. b
  14250. nil))
  14251. (buffer-list)))))
  14252. (defun org-agenda-files (&optional unrestricted archives)
  14253. "Get the list of agenda files.
  14254. Optional UNRESTRICTED means return the full list even if a restriction
  14255. is currently in place.
  14256. When ARCHIVES is t, include all archive files that are really being
  14257. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  14258. `org-agenda-archives-mode' is t."
  14259. (let ((files
  14260. (cond
  14261. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  14262. ((stringp org-agenda-files) (org-read-agenda-file-list))
  14263. ((listp org-agenda-files) org-agenda-files)
  14264. (t (error "Invalid value of `org-agenda-files'")))))
  14265. (setq files (apply 'append
  14266. (mapcar (lambda (f)
  14267. (if (file-directory-p f)
  14268. (directory-files
  14269. f t org-agenda-file-regexp)
  14270. (list f)))
  14271. files)))
  14272. (when org-agenda-skip-unavailable-files
  14273. (setq files (delq nil
  14274. (mapcar (function
  14275. (lambda (file)
  14276. (and (file-readable-p file) file)))
  14277. files))))
  14278. (when (or (eq archives t)
  14279. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  14280. (setq files (org-add-archive-files files)))
  14281. files))
  14282. (defun org-agenda-file-p (&optional file)
  14283. "Return non-nil, if FILE is an agenda file.
  14284. If FILE is omitted, use the file associated with the current
  14285. buffer."
  14286. (let ((fname (or file (buffer-file-name))))
  14287. (and fname
  14288. (member (file-truename fname)
  14289. (mapcar #'file-truename (org-agenda-files t))))))
  14290. (defun org-edit-agenda-file-list ()
  14291. "Edit the list of agenda files.
  14292. Depending on setup, this either uses customize to edit the variable
  14293. `org-agenda-files', or it visits the file that is holding the list. In the
  14294. latter case, the buffer is set up in a way that saving it automatically kills
  14295. the buffer and restores the previous window configuration."
  14296. (interactive)
  14297. (if (stringp org-agenda-files)
  14298. (let ((cw (current-window-configuration)))
  14299. (find-file org-agenda-files)
  14300. (setq-local org-window-configuration cw)
  14301. (add-hook 'after-save-hook
  14302. (lambda ()
  14303. (set-window-configuration
  14304. (prog1 org-window-configuration
  14305. (kill-buffer (current-buffer))))
  14306. (org-install-agenda-files-menu)
  14307. (message "New agenda file list installed"))
  14308. nil 'local)
  14309. (message "%s" (substitute-command-keys
  14310. "Edit list and finish with \\[save-buffer]")))
  14311. (customize-variable 'org-agenda-files)))
  14312. (defun org-store-new-agenda-file-list (list)
  14313. "Set new value for the agenda file list and save it correctly."
  14314. (if (stringp org-agenda-files)
  14315. (let ((fe (org-read-agenda-file-list t)) b u)
  14316. (while (setq b (find-buffer-visiting org-agenda-files))
  14317. (kill-buffer b))
  14318. (with-temp-file org-agenda-files
  14319. (insert
  14320. (mapconcat
  14321. (lambda (f) ;; Keep un-expanded entries.
  14322. (if (setq u (assoc f fe))
  14323. (cdr u)
  14324. f))
  14325. list "\n")
  14326. "\n")))
  14327. (let ((org-mode-hook nil) (org-inhibit-startup t)
  14328. (org-insert-mode-line-in-empty-file nil))
  14329. (setq org-agenda-files list)
  14330. (customize-save-variable 'org-agenda-files org-agenda-files))))
  14331. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  14332. "Read the list of agenda files from a file.
  14333. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  14334. filenames, used by `org-store-new-agenda-file-list' to write back
  14335. un-expanded file names."
  14336. (when (file-directory-p org-agenda-files)
  14337. (error "`org-agenda-files' cannot be a single directory"))
  14338. (when (stringp org-agenda-files)
  14339. (with-temp-buffer
  14340. (insert-file-contents org-agenda-files)
  14341. (mapcar
  14342. (lambda (f)
  14343. (let ((e (expand-file-name (substitute-in-file-name f)
  14344. org-directory)))
  14345. (if pair-with-expansion
  14346. (cons e f)
  14347. e)))
  14348. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  14349. ;;;###autoload
  14350. (defun org-cycle-agenda-files ()
  14351. "Cycle through the files in `org-agenda-files'.
  14352. If the current buffer visits an agenda file, find the next one in the list.
  14353. If the current buffer does not, find the first agenda file."
  14354. (interactive)
  14355. (let* ((fs (or (org-agenda-files t)
  14356. (user-error "No agenda files")))
  14357. (files (copy-sequence fs))
  14358. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  14359. file)
  14360. (when tcf
  14361. (while (and (setq file (pop files))
  14362. (not (equal (file-truename file) tcf)))))
  14363. (find-file (car (or files fs)))
  14364. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  14365. (defun org-agenda-file-to-front (&optional to-end)
  14366. "Move/add the current file to the top of the agenda file list.
  14367. If the file is not present in the list, it is added to the front. If it is
  14368. present, it is moved there. With optional argument TO-END, add/move to the
  14369. end of the list."
  14370. (interactive "P")
  14371. (let ((org-agenda-skip-unavailable-files nil)
  14372. (file-alist (mapcar (lambda (x)
  14373. (cons (file-truename x) x))
  14374. (org-agenda-files t)))
  14375. (ctf (file-truename
  14376. (or buffer-file-name
  14377. (user-error "Please save the current buffer to a file"))))
  14378. x had)
  14379. (setq x (assoc ctf file-alist) had x)
  14380. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  14381. (if to-end
  14382. (setq file-alist (append (delq x file-alist) (list x)))
  14383. (setq file-alist (cons x (delq x file-alist))))
  14384. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  14385. (org-install-agenda-files-menu)
  14386. (message "File %s to %s of agenda file list"
  14387. (if had "moved" "added") (if to-end "end" "front"))))
  14388. (defun org-remove-file (&optional file)
  14389. "Remove current file from the list of files in variable `org-agenda-files'.
  14390. These are the files which are being checked for agenda entries.
  14391. Optional argument FILE means use this file instead of the current."
  14392. (interactive)
  14393. (let* ((org-agenda-skip-unavailable-files nil)
  14394. (file (or file buffer-file-name
  14395. (user-error "Current buffer does not visit a file")))
  14396. (true-file (file-truename file))
  14397. (afile (abbreviate-file-name file))
  14398. (files (delq nil (mapcar
  14399. (lambda (x)
  14400. (unless (equal true-file
  14401. (file-truename x))
  14402. x))
  14403. (org-agenda-files t)))))
  14404. (if (not (= (length files) (length (org-agenda-files t))))
  14405. (progn
  14406. (org-store-new-agenda-file-list files)
  14407. (org-install-agenda-files-menu)
  14408. (message "Removed from Org Agenda list: %s" afile))
  14409. (message "File was not in list: %s (not removed)" afile))))
  14410. (defun org-file-menu-entry (file)
  14411. (vector file (list 'find-file file) t))
  14412. (defun org-check-agenda-file (file)
  14413. "Make sure FILE exists. If not, ask user what to do."
  14414. (unless (file-exists-p file)
  14415. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  14416. (abbreviate-file-name file))
  14417. (let ((r (downcase (read-char-exclusive))))
  14418. (cond
  14419. ((equal r ?r)
  14420. (org-remove-file file)
  14421. (throw 'nextfile t))
  14422. (t (user-error "Abort"))))))
  14423. (defun org-get-agenda-file-buffer (file)
  14424. "Get an agenda buffer visiting FILE.
  14425. If the buffer needs to be created, add it to the list of buffers
  14426. which might be released later."
  14427. (let ((buf (org-find-base-buffer-visiting file)))
  14428. (if buf
  14429. buf ; just return it
  14430. ;; Make a new buffer and remember it
  14431. (setq buf (find-file-noselect file))
  14432. (when buf (push buf org-agenda-new-buffers))
  14433. buf)))
  14434. (defun org-release-buffers (blist)
  14435. "Release all buffers in list, asking the user for confirmation when needed.
  14436. When a buffer is unmodified, it is just killed. When modified, it is saved
  14437. \(if the user agrees) and then killed."
  14438. (let (file)
  14439. (dolist (buf blist)
  14440. (setq file (buffer-file-name buf))
  14441. (when (and (buffer-modified-p buf)
  14442. file
  14443. (y-or-n-p (format "Save file %s? " file)))
  14444. (with-current-buffer buf (save-buffer)))
  14445. (kill-buffer buf))))
  14446. (defun org-agenda-prepare-buffers (files)
  14447. "Create buffers for all agenda files, protect archived trees and comments."
  14448. (interactive)
  14449. (let ((pa '(:org-archived t))
  14450. (pc '(:org-comment t))
  14451. (pall '(:org-archived t :org-comment t))
  14452. (inhibit-read-only t)
  14453. (org-inhibit-startup org-agenda-inhibit-startup)
  14454. (rea (org-make-tag-string (list org-archive-tag)))
  14455. re pos)
  14456. (setq org-tag-alist-for-agenda nil
  14457. org-tag-groups-alist-for-agenda nil)
  14458. (save-excursion
  14459. (save-restriction
  14460. (dolist (file files)
  14461. (catch 'nextfile
  14462. (if (bufferp file)
  14463. (set-buffer file)
  14464. (org-check-agenda-file file)
  14465. (set-buffer (org-get-agenda-file-buffer file)))
  14466. (widen)
  14467. (org-set-regexps-and-options 'tags-only)
  14468. (setq pos (point))
  14469. (or (memq 'category org-agenda-ignore-properties)
  14470. (org-refresh-category-properties))
  14471. (or (memq 'stats org-agenda-ignore-properties)
  14472. (org-refresh-stats-properties))
  14473. (or (memq 'effort org-agenda-ignore-properties)
  14474. (org-refresh-effort-properties))
  14475. (or (memq 'appt org-agenda-ignore-properties)
  14476. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14477. (setq org-todo-keywords-for-agenda
  14478. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14479. (setq org-done-keywords-for-agenda
  14480. (append org-done-keywords-for-agenda org-done-keywords))
  14481. (setq org-todo-keyword-alist-for-agenda
  14482. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14483. (setq org-tag-alist-for-agenda
  14484. (org--tag-add-to-alist
  14485. org-tag-alist-for-agenda
  14486. org-current-tag-alist))
  14487. ;; Merge current file's tag groups into global
  14488. ;; `org-tag-groups-alist-for-agenda'.
  14489. (when org-group-tags
  14490. (dolist (alist org-tag-groups-alist)
  14491. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14492. (if old
  14493. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14494. (push alist org-tag-groups-alist-for-agenda)))))
  14495. (with-silent-modifications
  14496. (save-excursion
  14497. (remove-text-properties (point-min) (point-max) pall)
  14498. (when org-agenda-skip-archived-trees
  14499. (goto-char (point-min))
  14500. (while (re-search-forward rea nil t)
  14501. (when (org-at-heading-p t)
  14502. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  14503. (goto-char (point-min))
  14504. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  14505. (while (re-search-forward re nil t)
  14506. (when (save-match-data (org-in-commented-heading-p t))
  14507. (add-text-properties
  14508. (match-beginning 0) (org-end-of-subtree t) pc)))))
  14509. (goto-char pos)))))
  14510. (setq org-todo-keywords-for-agenda
  14511. (org-uniquify org-todo-keywords-for-agenda))
  14512. (setq org-todo-keyword-alist-for-agenda
  14513. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14514. ;;;; CDLaTeX minor mode
  14515. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14516. "Keymap for the minor `org-cdlatex-mode'.")
  14517. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14518. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14519. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14520. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14521. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14522. (defvar org-cdlatex-texmathp-advice-is-done nil
  14523. "Flag remembering if we have applied the advice to texmathp already.")
  14524. (define-minor-mode org-cdlatex-mode
  14525. "Toggle the minor `org-cdlatex-mode'.
  14526. This mode supports entering LaTeX environment and math in LaTeX fragments
  14527. in Org mode.
  14528. \\{org-cdlatex-mode-map}"
  14529. nil " OCDL" nil
  14530. (when org-cdlatex-mode
  14531. (require 'cdlatex)
  14532. (run-hooks 'cdlatex-mode-hook)
  14533. (cdlatex-compute-tables))
  14534. (unless org-cdlatex-texmathp-advice-is-done
  14535. (setq org-cdlatex-texmathp-advice-is-done t)
  14536. (defadvice texmathp (around org-math-always-on activate)
  14537. "Always return t in Org buffers.
  14538. This is because we want to insert math symbols without dollars even outside
  14539. the LaTeX math segments. If Org mode thinks that point is actually inside
  14540. an embedded LaTeX fragment, let `texmathp' do its job.
  14541. `\\[org-cdlatex-mode-map]'"
  14542. (interactive)
  14543. (let (p)
  14544. (cond
  14545. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14546. ((eq this-command 'cdlatex-math-symbol)
  14547. (setq ad-return-value t
  14548. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14549. (t
  14550. (let ((p (org-inside-LaTeX-fragment-p)))
  14551. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14552. (setq ad-return-value t
  14553. texmathp-why '("Org mode embedded math" . 0))
  14554. (when p ad-do-it)))))))))
  14555. (defun turn-on-org-cdlatex ()
  14556. "Unconditionally turn on `org-cdlatex-mode'."
  14557. (org-cdlatex-mode 1))
  14558. (defun org-try-cdlatex-tab ()
  14559. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14560. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14561. - inside a LaTeX fragment, or
  14562. - after the first word in a line, where an abbreviation expansion could
  14563. insert a LaTeX environment."
  14564. (when org-cdlatex-mode
  14565. (cond
  14566. ;; Before any word on the line: No expansion possible.
  14567. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14568. ;; Just after first word on the line: Expand it. Make sure it
  14569. ;; cannot happen on headlines, though.
  14570. ((save-excursion
  14571. (skip-chars-backward "a-zA-Z0-9*")
  14572. (skip-chars-backward " \t")
  14573. (and (bolp) (not (org-at-heading-p))))
  14574. (cdlatex-tab) t)
  14575. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14576. (defun org-cdlatex-underscore-caret (&optional _arg)
  14577. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14578. Revert to the normal definition outside of these fragments."
  14579. (interactive "P")
  14580. (if (org-inside-LaTeX-fragment-p)
  14581. (call-interactively 'cdlatex-sub-superscript)
  14582. (let (org-cdlatex-mode)
  14583. (call-interactively (key-binding (vector last-input-event))))))
  14584. (defun org-cdlatex-math-modify (&optional _arg)
  14585. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14586. Revert to the normal definition outside of these fragments."
  14587. (interactive "P")
  14588. (if (org-inside-LaTeX-fragment-p)
  14589. (call-interactively 'cdlatex-math-modify)
  14590. (let (org-cdlatex-mode)
  14591. (call-interactively (key-binding (vector last-input-event))))))
  14592. (defun org-cdlatex-environment-indent (&optional environment item)
  14593. "Execute `cdlatex-environment' and indent the inserted environment.
  14594. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14595. The inserted environment is indented to current indentation
  14596. unless point is at the beginning of the line, in which the
  14597. environment remains unintended."
  14598. (interactive)
  14599. ;; cdlatex-environment always return nil. Therefore, capture output
  14600. ;; first and determine if an environment was selected.
  14601. (let* ((beg (point-marker))
  14602. (end (copy-marker (point) t))
  14603. (inserted (progn
  14604. (ignore-errors (cdlatex-environment environment item))
  14605. (< beg end)))
  14606. ;; Figure out how many lines to move forward after the
  14607. ;; environment has been inserted.
  14608. (lines (when inserted
  14609. (save-excursion
  14610. (- (cl-loop while (< beg (point))
  14611. with x = 0
  14612. do (forward-line -1)
  14613. (cl-incf x)
  14614. finally return x)
  14615. (if (progn (goto-char beg)
  14616. (and (progn (skip-chars-forward " \t") (eolp))
  14617. (progn (skip-chars-backward " \t") (bolp))))
  14618. 1 0)))))
  14619. (env (org-trim (delete-and-extract-region beg end))))
  14620. (when inserted
  14621. ;; Get indentation of next line unless at column 0.
  14622. (let ((ind (if (bolp) 0
  14623. (save-excursion
  14624. (org-return-indent)
  14625. (prog1 (current-indentation)
  14626. (when (progn (skip-chars-forward " \t") (eolp))
  14627. (delete-region beg (point)))))))
  14628. (bol (progn (skip-chars-backward " \t") (bolp))))
  14629. ;; Insert a newline before environment unless at column zero
  14630. ;; to "escape" the current line. Insert a newline if
  14631. ;; something is one the same line as \end{ENVIRONMENT}.
  14632. (insert
  14633. (concat (unless bol "\n") env
  14634. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14635. (unless (zerop ind)
  14636. (save-excursion
  14637. (goto-char beg)
  14638. (while (< (point) end)
  14639. (unless (eolp) (indent-line-to ind))
  14640. (forward-line))))
  14641. (goto-char beg)
  14642. (forward-line lines)
  14643. (indent-line-to ind)))
  14644. (set-marker beg nil)
  14645. (set-marker end nil)))
  14646. ;;;; LaTeX fragments
  14647. (defun org-inside-LaTeX-fragment-p ()
  14648. "Test if point is inside a LaTeX fragment.
  14649. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14650. sequence appearing also before point.
  14651. Even though the matchers for math are configurable, this function assumes
  14652. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14653. delimiters are skipped when they have been removed by customization.
  14654. The return value is nil, or a cons cell with the delimiter and the
  14655. position of this delimiter.
  14656. This function does a reasonably good job, but can locally be fooled by
  14657. for example currency specifications. For example it will assume being in
  14658. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14659. fragments that are properly closed, but during editing, we have to live
  14660. with the uncertainty caused by missing closing delimiters. This function
  14661. looks only before point, not after."
  14662. (catch 'exit
  14663. (let ((pos (point))
  14664. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14665. (lim (save-excursion (org-backward-paragraph) (point)))
  14666. dd-on str (start 0) m re)
  14667. (goto-char pos)
  14668. (when dodollar
  14669. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14670. re (nth 1 (assoc "$" org-latex-regexps)))
  14671. (while (string-match re str start)
  14672. (cond
  14673. ((= (match-end 0) (length str))
  14674. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14675. ((= (match-end 0) (- (length str) 5))
  14676. (throw 'exit nil))
  14677. (t (setq start (match-end 0))))))
  14678. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14679. (goto-char pos)
  14680. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14681. (and (match-beginning 2) (throw 'exit nil))
  14682. ;; count $$
  14683. (while (re-search-backward "\\$\\$" lim t)
  14684. (setq dd-on (not dd-on)))
  14685. (goto-char pos)
  14686. (when dd-on (cons "$$" m))))))
  14687. (defun org-inside-latex-macro-p ()
  14688. "Is point inside a LaTeX macro or its arguments?"
  14689. (save-match-data
  14690. (org-in-regexp
  14691. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14692. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14693. "Build an overlay between BEG and END using IMAGE file.
  14694. Argument IMAGETYPE is the extension of the displayed image,
  14695. as a string. It defaults to \"png\"."
  14696. (let ((ov (make-overlay beg end))
  14697. (imagetype (or (intern imagetype) 'png)))
  14698. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14699. (overlay-put ov 'evaporate t)
  14700. (overlay-put ov
  14701. 'modification-hooks
  14702. (list (lambda (o _flag _beg _end &optional _l)
  14703. (delete-overlay o))))
  14704. (overlay-put ov
  14705. 'display
  14706. (list 'image :type imagetype :file image :ascent 'center))))
  14707. (defun org-clear-latex-preview (&optional beg end)
  14708. "Remove all overlays with LaTeX fragment images in current buffer.
  14709. When optional arguments BEG and END are non-nil, remove all
  14710. overlays between them instead. Return a non-nil value when some
  14711. overlays were removed, nil otherwise."
  14712. (let ((overlays
  14713. (cl-remove-if-not
  14714. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14715. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14716. (mapc #'delete-overlay overlays)
  14717. overlays))
  14718. (defun org--latex-preview-region (beg end)
  14719. "Preview LaTeX fragments between BEG and END.
  14720. BEG and END are buffer positions."
  14721. (let ((file (buffer-file-name (buffer-base-buffer))))
  14722. (save-excursion
  14723. (org-format-latex
  14724. (concat org-preview-latex-image-directory "org-ltximg")
  14725. beg end
  14726. ;; Emacs cannot overlay images from remote hosts. Create it in
  14727. ;; `temporary-file-directory' instead.
  14728. (if (or (not file) (file-remote-p file))
  14729. temporary-file-directory
  14730. default-directory)
  14731. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14732. (defun org-latex-preview (&optional arg)
  14733. "Toggle preview of the LaTeX fragment at point.
  14734. If the cursor is on a LaTeX fragment, create the image and
  14735. overlay it over the source code, if there is none. Remove it
  14736. otherwise. If there is no fragment at point, display images for
  14737. all fragments in the current section.
  14738. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14739. for all fragments
  14740. in the current section.
  14741. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14742. argument ARG, display image for all
  14743. fragments in the buffer.
  14744. With a `\\[universal-argument] \\[universal-argument] \
  14745. \\[universal-argument]' prefix argument ARG, clear image for all
  14746. fragments in the buffer."
  14747. (interactive "P")
  14748. (cond
  14749. ((not (display-graphic-p)) nil)
  14750. ;; Clear whole buffer.
  14751. ((equal arg '(64))
  14752. (org-clear-latex-preview (point-min) (point-max))
  14753. (message "LaTeX previews removed from buffer"))
  14754. ;; Preview whole buffer.
  14755. ((equal arg '(16))
  14756. (message "Creating LaTeX previews in buffer...")
  14757. (org--latex-preview-region (point-min) (point-max))
  14758. (message "Creating LaTeX previews in buffer... done."))
  14759. ;; Clear current section.
  14760. ((equal arg '(4))
  14761. (org-clear-latex-preview
  14762. (if (org-before-first-heading-p) (point-min)
  14763. (save-excursion
  14764. (org-with-limited-levels (org-back-to-heading t) (point))))
  14765. (org-with-limited-levels (org-entry-end-position))))
  14766. ;; Toggle preview on LaTeX code at point.
  14767. ((let ((datum (org-element-context)))
  14768. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14769. (let ((beg (org-element-property :begin datum))
  14770. (end (org-element-property :end datum)))
  14771. (if (org-clear-latex-preview beg end)
  14772. (message "LaTeX preview removed")
  14773. (message "Creating LaTeX preview...")
  14774. (org--latex-preview-region beg end)
  14775. (message "Creating LaTeX preview... done."))
  14776. t))))
  14777. ;; Preview current section.
  14778. (t
  14779. (let ((beg (if (org-before-first-heading-p) (point-min)
  14780. (save-excursion
  14781. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14782. (end (org-with-limited-levels (org-entry-end-position))))
  14783. (message "Creating LaTeX previews in section...")
  14784. (org--latex-preview-region beg end)
  14785. (message "Creating LaTeX previews in section... done.")))))
  14786. (defun org-format-latex
  14787. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14788. "Replace LaTeX fragments with links to an image.
  14789. The function takes care of creating the replacement image.
  14790. Only consider fragments between BEG and END when those are
  14791. provided.
  14792. When optional argument OVERLAYS is non-nil, display the image on
  14793. top of the fragment instead of replacing it.
  14794. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14795. Some of the options can be changed using the variable
  14796. `org-format-latex-options', which see."
  14797. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14798. (unless (eq processing-type 'verbatim)
  14799. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14800. (cnt 0)
  14801. checkdir-flag)
  14802. (goto-char (or beg (point-min)))
  14803. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14804. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14805. (overlay-recenter (or end (point-max))))
  14806. (while (re-search-forward math-regexp end t)
  14807. (unless (and overlays
  14808. (eq (get-char-property (point) 'org-overlay-type)
  14809. 'org-latex-overlay))
  14810. (let* ((context (org-element-context))
  14811. (type (org-element-type context)))
  14812. (when (memq type '(latex-environment latex-fragment))
  14813. (let ((block-type (eq type 'latex-environment))
  14814. (value (org-element-property :value context))
  14815. (beg (org-element-property :begin context))
  14816. (end (save-excursion
  14817. (goto-char (org-element-property :end context))
  14818. (skip-chars-backward " \r\t\n")
  14819. (point))))
  14820. (cond
  14821. ((eq processing-type 'mathjax)
  14822. ;; Prepare for MathJax processing.
  14823. (if (not (string-match "\\`\\$\\$?" value))
  14824. (goto-char end)
  14825. (delete-region beg end)
  14826. (if (string= (match-string 0 value) "$$")
  14827. (insert "\\[" (substring value 2 -2) "\\]")
  14828. (insert "\\(" (substring value 1 -1) "\\)"))))
  14829. ((assq processing-type org-preview-latex-process-alist)
  14830. ;; Process to an image.
  14831. (cl-incf cnt)
  14832. (goto-char beg)
  14833. (let* ((processing-info
  14834. (cdr (assq processing-type org-preview-latex-process-alist)))
  14835. (face (face-at-point))
  14836. ;; Get the colors from the face at point.
  14837. (fg
  14838. (let ((color (plist-get org-format-latex-options
  14839. :foreground)))
  14840. (if (and forbuffer (eq color 'auto))
  14841. (face-attribute face :foreground nil 'default)
  14842. color)))
  14843. (bg
  14844. (let ((color (plist-get org-format-latex-options
  14845. :background)))
  14846. (if (and forbuffer (eq color 'auto))
  14847. (face-attribute face :background nil 'default)
  14848. color)))
  14849. (hash (sha1 (prin1-to-string
  14850. (list org-format-latex-header
  14851. org-latex-default-packages-alist
  14852. org-latex-packages-alist
  14853. org-format-latex-options
  14854. forbuffer value fg bg))))
  14855. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14856. (absprefix (expand-file-name prefix dir))
  14857. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14858. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14859. (sep (and block-type "\n\n"))
  14860. (link (concat sep "[[file:" linkfile "]]" sep))
  14861. (options
  14862. (org-combine-plists
  14863. org-format-latex-options
  14864. `(:foreground ,fg :background ,bg))))
  14865. (when msg (message msg cnt))
  14866. (unless checkdir-flag ; Ensure the directory exists.
  14867. (setq checkdir-flag t)
  14868. (let ((todir (file-name-directory absprefix)))
  14869. (unless (file-directory-p todir)
  14870. (make-directory todir t))))
  14871. (unless (file-exists-p movefile)
  14872. (org-create-formula-image
  14873. value movefile options forbuffer processing-type))
  14874. (if overlays
  14875. (progn
  14876. (dolist (o (overlays-in beg end))
  14877. (when (eq (overlay-get o 'org-overlay-type)
  14878. 'org-latex-overlay)
  14879. (delete-overlay o)))
  14880. (org--make-preview-overlay beg end movefile imagetype)
  14881. (goto-char end))
  14882. (delete-region beg end)
  14883. (insert
  14884. (org-add-props link
  14885. (list 'org-latex-src
  14886. (replace-regexp-in-string "\"" "" value)
  14887. 'org-latex-src-embed-type
  14888. (if block-type 'paragraph 'character)))))))
  14889. ((eq processing-type 'mathml)
  14890. ;; Process to MathML.
  14891. (unless (org-format-latex-mathml-available-p)
  14892. (user-error "LaTeX to MathML converter not configured"))
  14893. (cl-incf cnt)
  14894. (when msg (message msg cnt))
  14895. (goto-char beg)
  14896. (delete-region beg end)
  14897. (insert (org-format-latex-as-mathml
  14898. value block-type prefix dir)))
  14899. (t
  14900. (error "Unknown conversion process %s for LaTeX fragments"
  14901. processing-type)))))))))))
  14902. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14903. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14904. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14905. successful, return the portion between \"<math...> </math>\"
  14906. elements otherwise return nil. When MATHML-FILE is specified,
  14907. write the results in to that file. When invoked as an
  14908. interactive command, prompt for LATEX-FRAG, with initial value
  14909. set to the current active region and echo the results for user
  14910. inspection."
  14911. (interactive (list (let ((frag (when (org-region-active-p)
  14912. (buffer-substring-no-properties
  14913. (region-beginning) (region-end)))))
  14914. (read-string "LaTeX Fragment: " frag nil frag))))
  14915. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14916. (let* ((tmp-in-file
  14917. (let ((file (file-relative-name
  14918. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14919. (write-region latex-frag nil file)
  14920. file))
  14921. (tmp-out-file (file-relative-name
  14922. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14923. (cmd (format-spec
  14924. org-latex-to-mathml-convert-command
  14925. `((?j . ,(and org-latex-to-mathml-jar-file
  14926. (shell-quote-argument
  14927. (expand-file-name
  14928. org-latex-to-mathml-jar-file))))
  14929. (?I . ,(shell-quote-argument tmp-in-file))
  14930. (?i . ,latex-frag)
  14931. (?o . ,(shell-quote-argument tmp-out-file)))))
  14932. mathml shell-command-output)
  14933. (when (called-interactively-p 'any)
  14934. (unless (org-format-latex-mathml-available-p)
  14935. (user-error "LaTeX to MathML converter not configured")))
  14936. (message "Running %s" cmd)
  14937. (setq shell-command-output (shell-command-to-string cmd))
  14938. (setq mathml
  14939. (when (file-readable-p tmp-out-file)
  14940. (with-current-buffer (find-file-noselect tmp-out-file t)
  14941. (goto-char (point-min))
  14942. (when (re-search-forward
  14943. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14944. (regexp-quote
  14945. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14946. nil t)
  14947. (prog1 (match-string 0) (kill-buffer))))))
  14948. (cond
  14949. (mathml
  14950. (setq mathml
  14951. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14952. (when mathml-file
  14953. (write-region mathml nil mathml-file))
  14954. (when (called-interactively-p 'any)
  14955. (message mathml)))
  14956. ((message "LaTeX to MathML conversion failed")
  14957. (message shell-command-output)))
  14958. (delete-file tmp-in-file)
  14959. (when (file-exists-p tmp-out-file)
  14960. (delete-file tmp-out-file))
  14961. mathml))
  14962. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14963. prefix &optional dir)
  14964. "Use `org-create-math-formula' but check local cache first."
  14965. (let* ((absprefix (expand-file-name prefix dir))
  14966. (print-length nil) (print-level nil)
  14967. (formula-id (concat
  14968. "formula-"
  14969. (sha1
  14970. (prin1-to-string
  14971. (list latex-frag
  14972. org-latex-to-mathml-convert-command)))))
  14973. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14974. (formula-cache-dir (file-name-directory formula-cache)))
  14975. (unless (file-directory-p formula-cache-dir)
  14976. (make-directory formula-cache-dir t))
  14977. (unless (file-exists-p formula-cache)
  14978. (org-create-math-formula latex-frag formula-cache))
  14979. (if (file-exists-p formula-cache)
  14980. ;; Successful conversion. Return the link to MathML file.
  14981. (org-add-props
  14982. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14983. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14984. 'org-latex-src-embed-type (if latex-frag-type
  14985. 'paragraph 'character)))
  14986. ;; Failed conversion. Return the LaTeX fragment verbatim
  14987. latex-frag)))
  14988. (defun org--get-display-dpi ()
  14989. "Get the DPI of the display.
  14990. The function assumes that the display has the same pixel width in
  14991. the horizontal and vertical directions."
  14992. (if (display-graphic-p)
  14993. (round (/ (display-pixel-height)
  14994. (/ (display-mm-height) 25.4)))
  14995. (error "Attempt to calculate the dpi of a non-graphic display")))
  14996. (defun org-create-formula-image
  14997. (string tofile options buffer &optional processing-type)
  14998. "Create an image from LaTeX source using external processes.
  14999. The LaTeX STRING is saved to a temporary LaTeX file, then
  15000. converted to an image file by process PROCESSING-TYPE defined in
  15001. `org-preview-latex-process-alist'. A nil value defaults to
  15002. `org-preview-latex-default-process'.
  15003. The generated image file is eventually moved to TOFILE.
  15004. The OPTIONS argument controls the size, foreground color and
  15005. background color of the generated image.
  15006. When BUFFER non-nil, this function is used for LaTeX previewing.
  15007. Otherwise, it is used to deal with LaTeX snippets showed in
  15008. a HTML file."
  15009. (let* ((processing-type (or processing-type
  15010. org-preview-latex-default-process))
  15011. (processing-info
  15012. (cdr (assq processing-type org-preview-latex-process-alist)))
  15013. (programs (plist-get processing-info :programs))
  15014. (error-message (or (plist-get processing-info :message) ""))
  15015. (image-input-type (plist-get processing-info :image-input-type))
  15016. (image-output-type (plist-get processing-info :image-output-type))
  15017. (post-clean (or (plist-get processing-info :post-clean)
  15018. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  15019. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  15020. (latex-header
  15021. (or (plist-get processing-info :latex-header)
  15022. (org-latex-make-preamble
  15023. (org-export-get-environment (org-export-get-backend 'latex))
  15024. org-format-latex-header
  15025. 'snippet)))
  15026. (latex-compiler (plist-get processing-info :latex-compiler))
  15027. (image-converter (plist-get processing-info :image-converter))
  15028. (tmpdir temporary-file-directory)
  15029. (texfilebase (make-temp-name
  15030. (expand-file-name "orgtex" tmpdir)))
  15031. (texfile (concat texfilebase ".tex"))
  15032. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  15033. '(1.0 . 1.0)))
  15034. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  15035. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  15036. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  15037. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  15038. "Black"))
  15039. (bg (or (plist-get options (if buffer :background :html-background))
  15040. "Transparent"))
  15041. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  15042. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  15043. (dolist (program programs)
  15044. (org-check-external-command program error-message))
  15045. (if (eq fg 'default)
  15046. (setq fg (org-latex-color :foreground))
  15047. (setq fg (org-latex-color-format fg)))
  15048. (if (eq bg 'default)
  15049. (setq bg (org-latex-color :background))
  15050. (setq bg (org-latex-color-format
  15051. (if (string= bg "Transparent") "white" bg))))
  15052. ;; Remove TeX \par at end of snippet to avoid trailing space.
  15053. (if (string-suffix-p string "\n")
  15054. (aset string (1- (length string)) ?%)
  15055. (setq string (concat string "%")))
  15056. (with-temp-file texfile
  15057. (insert latex-header)
  15058. (insert "\n\\begin{document}\n"
  15059. "\\definecolor{fg}{rgb}{" fg "}%\n"
  15060. "\\definecolor{bg}{rgb}{" bg "}%\n"
  15061. "\n\\pagecolor{bg}%\n"
  15062. "\n{\\color{fg}\n"
  15063. string
  15064. "\n}\n"
  15065. "\n\\end{document}\n"))
  15066. (let* ((err-msg (format "Please adjust `%s' part of \
  15067. `org-preview-latex-process-alist'."
  15068. processing-type))
  15069. (image-input-file
  15070. (org-compile-file
  15071. texfile latex-compiler image-input-type err-msg log-buf))
  15072. (image-output-file
  15073. (org-compile-file
  15074. image-input-file image-converter image-output-type err-msg log-buf
  15075. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  15076. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  15077. (copy-file image-output-file tofile 'replace)
  15078. (dolist (e post-clean)
  15079. (when (file-exists-p (concat texfilebase e))
  15080. (delete-file (concat texfilebase e))))
  15081. image-output-file)))
  15082. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  15083. "Fill a LaTeX header template TPL.
  15084. In the template, the following place holders will be recognized:
  15085. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  15086. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  15087. [PACKAGES] \\usepackage statements for PKG
  15088. [NO-PACKAGES] do not include PKG
  15089. [EXTRA] the string EXTRA
  15090. [NO-EXTRA] do not include EXTRA
  15091. For backward compatibility, if both the positive and the negative place
  15092. holder is missing, the positive one (without the \"NO-\") will be
  15093. assumed to be present at the end of the template.
  15094. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  15095. EXTRA is a string.
  15096. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  15097. (let (rpl (end ""))
  15098. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  15099. (setq rpl (if (or (match-end 1) (not def-pkg))
  15100. "" (org-latex-packages-to-string def-pkg snippets-p t))
  15101. tpl (replace-match rpl t t tpl))
  15102. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  15103. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  15104. (setq rpl (if (or (match-end 1) (not pkg))
  15105. "" (org-latex-packages-to-string pkg snippets-p t))
  15106. tpl (replace-match rpl t t tpl))
  15107. (when pkg (setq end
  15108. (concat end "\n"
  15109. (org-latex-packages-to-string pkg snippets-p)))))
  15110. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  15111. (setq rpl (if (or (match-end 1) (not extra))
  15112. "" (concat extra "\n"))
  15113. tpl (replace-match rpl t t tpl))
  15114. (when (and extra (string-match "\\S-" extra))
  15115. (setq end (concat end "\n" extra))))
  15116. (if (string-match "\\S-" end)
  15117. (concat tpl "\n" end)
  15118. tpl)))
  15119. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  15120. "Turn an alist of packages into a string with the \\usepackage macros."
  15121. (setq pkg (mapconcat (lambda(p)
  15122. (cond
  15123. ((stringp p) p)
  15124. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  15125. (format "%% Package %s omitted" (cadr p)))
  15126. ((equal "" (car p))
  15127. (format "\\usepackage{%s}" (cadr p)))
  15128. (t
  15129. (format "\\usepackage[%s]{%s}"
  15130. (car p) (cadr p)))))
  15131. pkg
  15132. "\n"))
  15133. (if newline (concat pkg "\n") pkg))
  15134. (defun org-dvipng-color (attr)
  15135. "Return a RGB color specification for dvipng."
  15136. (org-dvipng-color-format (face-attribute 'default attr nil)))
  15137. (defun org-dvipng-color-format (color-name)
  15138. "Convert COLOR-NAME to a RGB color value for dvipng."
  15139. (apply #'format "rgb %s %s %s"
  15140. (mapcar 'org-normalize-color
  15141. (color-values color-name))))
  15142. (defun org-latex-color (attr)
  15143. "Return a RGB color for the LaTeX color package."
  15144. (org-latex-color-format (face-attribute 'default attr nil)))
  15145. (defun org-latex-color-format (color-name)
  15146. "Convert COLOR-NAME to a RGB color value."
  15147. (apply #'format "%s,%s,%s"
  15148. (mapcar 'org-normalize-color
  15149. (color-values color-name))))
  15150. (defun org-normalize-color (value)
  15151. "Return string to be used as color value for an RGB component."
  15152. (format "%g" (/ value 65535.0)))
  15153. ;; Image display
  15154. (defvar-local org-inline-image-overlays nil)
  15155. (defun org-toggle-inline-images (&optional include-linked)
  15156. "Toggle the display of inline images.
  15157. INCLUDE-LINKED is passed to `org-display-inline-images'."
  15158. (interactive "P")
  15159. (if org-inline-image-overlays
  15160. (progn
  15161. (org-remove-inline-images)
  15162. (when (called-interactively-p 'interactive)
  15163. (message "Inline image display turned off")))
  15164. (org-display-inline-images include-linked)
  15165. (when (called-interactively-p 'interactive)
  15166. (message (if org-inline-image-overlays
  15167. (format "%d images displayed inline"
  15168. (length org-inline-image-overlays))
  15169. "No images to display inline")))))
  15170. (defun org-redisplay-inline-images ()
  15171. "Refresh the display of inline images."
  15172. (interactive)
  15173. (if (not org-inline-image-overlays)
  15174. (org-toggle-inline-images)
  15175. (org-toggle-inline-images)
  15176. (org-toggle-inline-images)))
  15177. ;; For without-x builds.
  15178. (declare-function image-refresh "image" (spec &optional frame))
  15179. (defun org-display-inline-images (&optional include-linked refresh beg end)
  15180. "Display inline images.
  15181. An inline image is a link which follows either of these
  15182. conventions:
  15183. 1. Its path is a file with an extension matching return value
  15184. from `image-file-name-regexp' and it has no contents.
  15185. 2. Its description consists in a single link of the previous
  15186. type. In this case, that link must be a well-formed plain
  15187. or angle link, i.e., it must have an explicit \"file\" type.
  15188. Equip each image with the key-map `image-map'.
  15189. When optional argument INCLUDE-LINKED is non-nil, also links with
  15190. a text description part will be inlined. This can be nice for
  15191. a quick look at those images, but it does not reflect what
  15192. exported files will look like.
  15193. When optional argument REFRESH is non-nil, refresh existing
  15194. images between BEG and END. This will create new image displays
  15195. only if necessary.
  15196. BEG and END define the considered part. They default to the
  15197. buffer boundaries with possible narrowing."
  15198. (interactive "P")
  15199. (when (display-graphic-p)
  15200. (unless refresh
  15201. (org-remove-inline-images)
  15202. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  15203. (let ((end (or end (point-max))))
  15204. (org-with-point-at (or beg (point-min))
  15205. (let* ((case-fold-search t)
  15206. (file-extension-re (image-file-name-regexp))
  15207. (link-abbrevs (mapcar #'car
  15208. (append org-link-abbrev-alist-local
  15209. org-link-abbrev-alist)))
  15210. ;; Check absolute, relative file names and explicit
  15211. ;; "file:" links. Also check link abbreviations since
  15212. ;; some might expand to "file" links.
  15213. (file-types-re
  15214. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  15215. (if (not link-abbrevs) ""
  15216. (concat "\\|" (regexp-opt link-abbrevs))))))
  15217. (while (re-search-forward file-types-re end t)
  15218. (let* ((link (org-element-lineage
  15219. (save-match-data (org-element-context))
  15220. '(link) t))
  15221. (linktype (org-element-property :type link))
  15222. (inner-start (match-beginning 1))
  15223. (path
  15224. (cond
  15225. ;; No link at point; no inline image.
  15226. ((not link) nil)
  15227. ;; File link without a description. Also handle
  15228. ;; INCLUDE-LINKED here since it should have
  15229. ;; precedence over the next case. I.e., if link
  15230. ;; contains filenames in both the path and the
  15231. ;; description, prioritize the path only when
  15232. ;; INCLUDE-LINKED is non-nil.
  15233. ((or (not (org-element-property :contents-begin link))
  15234. include-linked)
  15235. (and (or (equal "file" linktype)
  15236. (equal "attachment" linktype))
  15237. (org-element-property :path link)))
  15238. ;; Link with a description. Check if description
  15239. ;; is a filename. Even if Org doesn't have syntax
  15240. ;; for those -- clickable image -- constructs, fake
  15241. ;; them, as in `org-export-insert-image-links'.
  15242. ((not inner-start) nil)
  15243. (t
  15244. (org-with-point-at inner-start
  15245. (and (looking-at
  15246. (if (char-equal ?< (char-after inner-start))
  15247. org-link-angle-re
  15248. org-link-plain-re))
  15249. ;; File name must fill the whole
  15250. ;; description.
  15251. (= (org-element-property :contents-end link)
  15252. (match-end 0))
  15253. (match-string 2)))))))
  15254. (when (and path (string-match-p file-extension-re path))
  15255. (let ((file (if (equal "attachment" linktype)
  15256. (progn
  15257. (require 'org-attach)
  15258. (ignore-errors (org-attach-expand path)))
  15259. (expand-file-name path))))
  15260. (when (and file (file-exists-p file))
  15261. (let ((width
  15262. ;; Apply `org-image-actual-width' specifications.
  15263. (cond
  15264. ((eq org-image-actual-width t) nil)
  15265. ((listp org-image-actual-width)
  15266. (or
  15267. ;; First try to find a width among
  15268. ;; attributes associated to the paragraph
  15269. ;; containing link.
  15270. (pcase (org-element-lineage link '(paragraph))
  15271. (`nil nil)
  15272. (p
  15273. (let* ((case-fold-search t)
  15274. (end (org-element-property :post-affiliated p))
  15275. (re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"))
  15276. (when (org-with-point-at
  15277. (org-element-property :begin p)
  15278. (re-search-forward re end t))
  15279. (string-to-number (match-string 1))))))
  15280. ;; Otherwise, fall-back to provided number.
  15281. (car org-image-actual-width)))
  15282. ((numberp org-image-actual-width)
  15283. org-image-actual-width)
  15284. (t nil)))
  15285. (old (get-char-property-and-overlay
  15286. (org-element-property :begin link)
  15287. 'org-image-overlay)))
  15288. (if (and (car-safe old) refresh)
  15289. (image-refresh (overlay-get (cdr old) 'display))
  15290. (let ((image (create-image file
  15291. (and (image-type-available-p 'imagemagick)
  15292. width 'imagemagick)
  15293. nil
  15294. :width width)))
  15295. (when image
  15296. (let ((ov (make-overlay
  15297. (org-element-property :begin link)
  15298. (progn
  15299. (goto-char
  15300. (org-element-property :end link))
  15301. (skip-chars-backward " \t")
  15302. (point)))))
  15303. (overlay-put ov 'display image)
  15304. (overlay-put ov 'face 'default)
  15305. (overlay-put ov 'org-image-overlay t)
  15306. (overlay-put
  15307. ov 'modification-hooks
  15308. (list 'org-display-inline-remove-overlay))
  15309. (when (<= 26 emacs-major-version)
  15310. (cl-assert (boundp 'image-map))
  15311. (overlay-put ov 'keymap image-map))
  15312. (push ov org-inline-image-overlays))))))))))))))))
  15313. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  15314. "Remove inline-display overlay if a corresponding region is modified."
  15315. (let ((inhibit-modification-hooks t))
  15316. (when (and ov after)
  15317. (delete ov org-inline-image-overlays)
  15318. (delete-overlay ov))))
  15319. (defun org-remove-inline-images ()
  15320. "Remove inline display of images."
  15321. (interactive)
  15322. (mapc #'delete-overlay org-inline-image-overlays)
  15323. (setq org-inline-image-overlays nil))
  15324. (defvar org-self-insert-command-undo-counter 0)
  15325. (defvar org-speed-command nil)
  15326. (defun org-self-insert-command (N)
  15327. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  15328. If the cursor is in a table looking at whitespace, the whitespace is
  15329. overwritten, and the table is not marked as requiring realignment."
  15330. (interactive "p")
  15331. (org-check-before-invisible-edit 'insert)
  15332. (cond
  15333. ((and org-use-speed-commands
  15334. (let ((kv (this-command-keys-vector)))
  15335. (setq org-speed-command
  15336. (run-hook-with-args-until-success
  15337. 'org-speed-command-hook
  15338. (make-string 1 (aref kv (1- (length kv))))))))
  15339. (cond
  15340. ((commandp org-speed-command)
  15341. (setq this-command org-speed-command)
  15342. (call-interactively org-speed-command))
  15343. ((functionp org-speed-command)
  15344. (funcall org-speed-command))
  15345. ((and org-speed-command (listp org-speed-command))
  15346. (eval org-speed-command))
  15347. (t (let (org-use-speed-commands)
  15348. (call-interactively 'org-self-insert-command)))))
  15349. ((and
  15350. (= N 1)
  15351. (not (org-region-active-p))
  15352. (org-at-table-p)
  15353. (progn
  15354. ;; Check if we blank the field, and if that triggers align.
  15355. (and (featurep 'org-table)
  15356. org-table-auto-blank-field
  15357. (memq last-command
  15358. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  15359. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  15360. ;; Got extra space, this field does not determine
  15361. ;; column width.
  15362. (let (org-table-may-need-update) (org-table-blank-field))
  15363. ;; No extra space, this field may determine column
  15364. ;; width.
  15365. (org-table-blank-field)))
  15366. t)
  15367. (looking-at "[^|\n]* |"))
  15368. ;; There is room for insertion without re-aligning the table.
  15369. (self-insert-command N)
  15370. (org-table-with-shrunk-field
  15371. (save-excursion
  15372. (skip-chars-forward "^|")
  15373. ;; Do not delete last space, which is
  15374. ;; `org-table-separator-space', but the regular space before
  15375. ;; it.
  15376. (delete-region (- (point) 2) (1- (point))))))
  15377. (t
  15378. (setq org-table-may-need-update t)
  15379. (self-insert-command N)
  15380. (org-fix-tags-on-the-fly)
  15381. (when org-self-insert-cluster-for-undo
  15382. (if (not (eq last-command 'org-self-insert-command))
  15383. (setq org-self-insert-command-undo-counter 1)
  15384. (if (>= org-self-insert-command-undo-counter 20)
  15385. (setq org-self-insert-command-undo-counter 1)
  15386. (and (> org-self-insert-command-undo-counter 0)
  15387. buffer-undo-list (listp buffer-undo-list)
  15388. (not (cadr buffer-undo-list)) ; remove nil entry
  15389. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15390. (setq org-self-insert-command-undo-counter
  15391. (1+ org-self-insert-command-undo-counter))))))))
  15392. (defun org-check-before-invisible-edit (kind)
  15393. "Check is editing if kind KIND would be dangerous with invisible text around.
  15394. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15395. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15396. (when (and org-catch-invisible-edits
  15397. (or (not (boundp 'visible-mode)) (not visible-mode))
  15398. (or (get-char-property (point) 'invisible)
  15399. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15400. ;; OK, we need to take a closer look. Do not consider
  15401. ;; invisibility obtained through text properties (e.g., link
  15402. ;; fontification), as it cannot be toggled.
  15403. (let* ((invisible-at-point
  15404. (pcase (get-char-property-and-overlay (point) 'invisible)
  15405. (`(,_ . ,(and (pred overlayp) o)) o)))
  15406. ;; Assume that point cannot land in the middle of an
  15407. ;; overlay, or between two overlays.
  15408. (invisible-before-point
  15409. (and (not invisible-at-point)
  15410. (not (bobp))
  15411. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15412. (`(,_ . ,(and (pred overlayp) o)) o))))
  15413. (border-and-ok-direction
  15414. (or
  15415. ;; Check if we are acting predictably before invisible
  15416. ;; text.
  15417. (and invisible-at-point
  15418. (memq kind '(insert delete-backward)))
  15419. ;; Check if we are acting predictably after invisible text
  15420. ;; This works not well, and I have turned it off. It seems
  15421. ;; better to always show and stop after invisible text.
  15422. ;; (and (not invisible-at-point) invisible-before-point
  15423. ;; (memq kind '(insert delete)))
  15424. )))
  15425. (when (or invisible-at-point invisible-before-point)
  15426. (when (eq org-catch-invisible-edits 'error)
  15427. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15428. (if (and org-custom-properties-overlays
  15429. (y-or-n-p "Display invisible properties in this buffer? "))
  15430. (org-toggle-custom-properties-visibility)
  15431. ;; Make the area visible
  15432. (save-excursion
  15433. (when invisible-before-point
  15434. (goto-char
  15435. (previous-single-char-property-change (point) 'invisible)))
  15436. ;; Remove whatever overlay is currently making yet-to-be
  15437. ;; edited text invisible. Also remove nested invisibility
  15438. ;; related overlays.
  15439. (delete-overlay (or invisible-at-point invisible-before-point))
  15440. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15441. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15442. (`(,_ . ,(and (pred overlayp) o))
  15443. (delete-overlay o)
  15444. t)))))
  15445. (cond
  15446. ((eq org-catch-invisible-edits 'show)
  15447. ;; That's it, we do the edit after showing
  15448. (message
  15449. "Unfolding invisible region around point before editing")
  15450. (sit-for 1))
  15451. ((and (eq org-catch-invisible-edits 'smart)
  15452. border-and-ok-direction)
  15453. (message "Unfolding invisible region around point before editing"))
  15454. (t
  15455. ;; Don't do the edit, make the user repeat it in full visibility
  15456. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15457. (defun org-fix-tags-on-the-fly ()
  15458. "Align tags in headline at point.
  15459. Unlike `org-align-tags', this function does nothing if point is
  15460. either not currently on a tagged headline or on a tag."
  15461. (when (and (org-match-line org-tag-line-re)
  15462. (< (point) (match-beginning 1)))
  15463. (org-align-tags)))
  15464. (defun org-delete-backward-char (N)
  15465. "Like `delete-backward-char', insert whitespace at field end in tables.
  15466. When deleting backwards, in tables this function will insert whitespace in
  15467. front of the next \"|\" separator, to keep the table aligned. The table will
  15468. still be marked for re-alignment if the field did fill the entire column,
  15469. because, in this case the deletion might narrow the column."
  15470. (interactive "p")
  15471. (save-match-data
  15472. (org-check-before-invisible-edit 'delete-backward)
  15473. (if (and (= N 1)
  15474. (not overwrite-mode)
  15475. (not (org-region-active-p))
  15476. (not (eq (char-before) ?|))
  15477. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15478. (looking-at-p ".*?|")
  15479. (org-at-table-p))
  15480. (progn (forward-char -1) (org-delete-char 1))
  15481. (backward-delete-char N)
  15482. (org-fix-tags-on-the-fly))))
  15483. (defun org-delete-char (N)
  15484. "Like `delete-char', but insert whitespace at field end in tables.
  15485. When deleting characters, in tables this function will insert whitespace in
  15486. front of the next \"|\" separator, to keep the table aligned. The table will
  15487. still be marked for re-alignment if the field did fill the entire column,
  15488. because, in this case the deletion might narrow the column."
  15489. (interactive "p")
  15490. (save-match-data
  15491. (org-check-before-invisible-edit 'delete)
  15492. (cond
  15493. ((or (/= N 1)
  15494. (eq (char-after) ?|)
  15495. (save-excursion (skip-chars-backward " \t") (bolp))
  15496. (not (org-at-table-p)))
  15497. (delete-char N)
  15498. (org-fix-tags-on-the-fly))
  15499. ((looking-at ".\\(.*?\\)|")
  15500. (let* ((update? org-table-may-need-update)
  15501. (noalign (looking-at-p ".*? |")))
  15502. (delete-char 1)
  15503. (org-table-with-shrunk-field
  15504. (save-excursion
  15505. ;; Last space is `org-table-separator-space', so insert
  15506. ;; a regular one before it instead.
  15507. (goto-char (- (match-end 0) 2))
  15508. (insert " ")))
  15509. ;; If there were two spaces at the end, this field does not
  15510. ;; determine the width of the column.
  15511. (when noalign (setq org-table-may-need-update update?))))
  15512. (t
  15513. (delete-char N)))))
  15514. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15515. (put 'org-self-insert-command 'delete-selection
  15516. (lambda ()
  15517. (not (run-hook-with-args-until-success
  15518. 'self-insert-uses-region-functions))))
  15519. (put 'orgtbl-self-insert-command 'delete-selection
  15520. (lambda ()
  15521. (not (run-hook-with-args-until-success
  15522. 'self-insert-uses-region-functions))))
  15523. (put 'org-delete-char 'delete-selection 'supersede)
  15524. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15525. (put 'org-yank 'delete-selection 'yank)
  15526. ;; Make `flyspell-mode' delay after some commands
  15527. (put 'org-self-insert-command 'flyspell-delayed t)
  15528. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15529. (put 'org-delete-char 'flyspell-delayed t)
  15530. (put 'org-delete-backward-char 'flyspell-delayed t)
  15531. ;; Make pabbrev-mode expand after Org mode commands
  15532. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15533. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15534. (defun org-transpose-words ()
  15535. "Transpose words for Org.
  15536. This uses the `org-mode-transpose-word-syntax-table' syntax
  15537. table, which interprets characters in `org-emphasis-alist' as
  15538. word constituents."
  15539. (interactive)
  15540. (with-syntax-table org-mode-transpose-word-syntax-table
  15541. (call-interactively 'transpose-words)))
  15542. (defvar org-ctrl-c-ctrl-c-hook nil
  15543. "Hook for functions attaching themselves to `C-c C-c'.
  15544. This can be used to add additional functionality to the C-c C-c
  15545. key which executes context-dependent commands. This hook is run
  15546. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15547. run after the last test.
  15548. Each function will be called with no arguments. The function
  15549. must check if the context is appropriate for it to act. If yes,
  15550. it should do its thing and then return a non-nil value. If the
  15551. context is wrong, just do nothing and return nil.")
  15552. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15553. "Hook for functions attaching themselves to `C-c C-c'.
  15554. This can be used to add additional functionality to the C-c C-c
  15555. key which executes context-dependent commands. This hook is run
  15556. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15557. before the first test.
  15558. Each function will be called with no arguments. The function
  15559. must check if the context is appropriate for it to act. If yes,
  15560. it should do its thing and then return a non-nil value. If the
  15561. context is wrong, just do nothing and return nil.")
  15562. (defvar org-tab-first-hook nil
  15563. "Hook for functions to attach themselves to TAB.
  15564. See `org-ctrl-c-ctrl-c-hook' for more information.
  15565. This hook runs as the first action when TAB is pressed, even before
  15566. `org-cycle' messes around with the `outline-regexp' to cater for
  15567. inline tasks and plain list item folding.
  15568. If any function in this hook returns t, any other actions that
  15569. would have been caused by TAB (such as table field motion or visibility
  15570. cycling) will not occur.")
  15571. (defvar org-tab-after-check-for-table-hook nil
  15572. "Hook for functions to attach themselves to TAB.
  15573. See `org-ctrl-c-ctrl-c-hook' for more information.
  15574. This hook runs after it has been established that the cursor is not in a
  15575. table, but before checking if the cursor is in a headline or if global cycling
  15576. should be done.
  15577. If any function in this hook returns t, not other actions like visibility
  15578. cycling will be done.")
  15579. (defvar org-tab-after-check-for-cycling-hook nil
  15580. "Hook for functions to attach themselves to TAB.
  15581. See `org-ctrl-c-ctrl-c-hook' for more information.
  15582. This hook runs after it has been established that not table field motion and
  15583. not visibility should be done because of current context. This is probably
  15584. the place where a package like yasnippets can hook in.")
  15585. (defvar org-tab-before-tab-emulation-hook nil
  15586. "Hook for functions to attach themselves to TAB.
  15587. See `org-ctrl-c-ctrl-c-hook' for more information.
  15588. This hook runs after every other options for TAB have been exhausted, but
  15589. before indentation and \t insertion takes place.")
  15590. (defvar org-metaleft-hook nil
  15591. "Hook for functions attaching themselves to `M-left'.
  15592. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15593. (defvar org-metaright-hook nil
  15594. "Hook for functions attaching themselves to `M-right'.
  15595. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15596. (defvar org-metaup-hook nil
  15597. "Hook for functions attaching themselves to `M-up'.
  15598. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15599. (defvar org-metadown-hook nil
  15600. "Hook for functions attaching themselves to `M-down'.
  15601. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15602. (defvar org-shiftmetaleft-hook nil
  15603. "Hook for functions attaching themselves to `M-S-left'.
  15604. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15605. (defvar org-shiftmetaright-hook nil
  15606. "Hook for functions attaching themselves to `M-S-right'.
  15607. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15608. (defvar org-shiftmetaup-hook nil
  15609. "Hook for functions attaching themselves to `M-S-up'.
  15610. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15611. (defvar org-shiftmetadown-hook nil
  15612. "Hook for functions attaching themselves to `M-S-down'.
  15613. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15614. (defvar org-metareturn-hook nil
  15615. "Hook for functions attaching themselves to `M-RET'.
  15616. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15617. (defvar org-shiftup-hook nil
  15618. "Hook for functions attaching themselves to `S-up'.
  15619. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15620. (defvar org-shiftup-final-hook nil
  15621. "Hook for functions attaching themselves to `S-up'.
  15622. This one runs after all other options except shift-select have been excluded.
  15623. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15624. (defvar org-shiftdown-hook nil
  15625. "Hook for functions attaching themselves to `S-down'.
  15626. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15627. (defvar org-shiftdown-final-hook nil
  15628. "Hook for functions attaching themselves to `S-down'.
  15629. This one runs after all other options except shift-select have been excluded.
  15630. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15631. (defvar org-shiftleft-hook nil
  15632. "Hook for functions attaching themselves to `S-left'.
  15633. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15634. (defvar org-shiftleft-final-hook nil
  15635. "Hook for functions attaching themselves to `S-left'.
  15636. This one runs after all other options except shift-select have been excluded.
  15637. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15638. (defvar org-shiftright-hook nil
  15639. "Hook for functions attaching themselves to `S-right'.
  15640. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15641. (defvar org-shiftright-final-hook nil
  15642. "Hook for functions attaching themselves to `S-right'.
  15643. This one runs after all other options except shift-select have been excluded.
  15644. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15645. (defun org-modifier-cursor-error ()
  15646. "Throw an error, a modified cursor command was applied in wrong context."
  15647. (user-error "This command is active in special context like tables, headlines or items"))
  15648. (defun org-shiftselect-error ()
  15649. "Throw an error because Shift-Cursor command was applied in wrong context."
  15650. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15651. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15652. (user-error "This command works only in special context like headlines or timestamps")))
  15653. (defun org-call-for-shift-select (cmd)
  15654. (let ((this-command-keys-shift-translated t))
  15655. (call-interactively cmd)))
  15656. (defun org-shifttab (&optional arg)
  15657. "Global visibility cycling or move to previous table field.
  15658. Call `org-table-previous-field' within a table.
  15659. When ARG is nil, cycle globally through visibility states.
  15660. When ARG is a numeric prefix, show contents of this level."
  15661. (interactive "P")
  15662. (cond
  15663. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15664. ((integerp arg)
  15665. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15666. (message "Content view to level: %d" arg)
  15667. (org-content (prefix-numeric-value arg2))
  15668. (org-cycle-show-empty-lines t)
  15669. (setq org-cycle-global-status 'overview)))
  15670. (t (call-interactively 'org-global-cycle))))
  15671. (defun org-shiftmetaleft ()
  15672. "Promote subtree or delete table column.
  15673. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15674. `org-table-delete-column', depending on context. See the
  15675. individual commands for more information."
  15676. (interactive)
  15677. (cond
  15678. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15679. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15680. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15681. ((if (not (org-region-active-p)) (org-at-item-p)
  15682. (save-excursion (goto-char (region-beginning))
  15683. (org-at-item-p)))
  15684. (call-interactively 'org-outdent-item-tree))
  15685. (t (org-modifier-cursor-error))))
  15686. (defun org-shiftmetaright ()
  15687. "Demote subtree or insert table column.
  15688. Calls `org-demote-subtree', `org-indent-item-tree', or
  15689. `org-table-insert-column', depending on context. See the
  15690. individual commands for more information."
  15691. (interactive)
  15692. (cond
  15693. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15694. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15695. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15696. ((if (not (org-region-active-p)) (org-at-item-p)
  15697. (save-excursion (goto-char (region-beginning))
  15698. (org-at-item-p)))
  15699. (call-interactively 'org-indent-item-tree))
  15700. (t (org-modifier-cursor-error))))
  15701. (defun org-shiftmetaup (&optional _arg)
  15702. "Drag the line at point up.
  15703. In a table, kill the current row.
  15704. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15705. but also adjust the previous clocked item in the clock history.
  15706. Everywhere else, drag the line at point up."
  15707. (interactive "P")
  15708. (cond
  15709. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15710. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15711. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15712. (call-interactively 'org-timestamp-up)))
  15713. (t (call-interactively 'org-drag-line-backward))))
  15714. (defun org-shiftmetadown (&optional _arg)
  15715. "Drag the line at point down.
  15716. In a table, insert an empty row at the current line.
  15717. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15718. but also adjust the previous clocked item in the clock history.
  15719. Everywhere else, drag the line at point down."
  15720. (interactive "P")
  15721. (cond
  15722. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15723. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15724. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15725. (call-interactively 'org-timestamp-down)))
  15726. (t (call-interactively 'org-drag-line-forward))))
  15727. (defsubst org-hidden-tree-error ()
  15728. (user-error
  15729. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15730. (defun org-metaleft (&optional _arg)
  15731. "Promote heading, list item at point or move table column left.
  15732. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15733. depending on context. With no specific context, calls the Emacs
  15734. default `backward-word'. See the individual commands for more
  15735. information.
  15736. This function runs the hook `org-metaleft-hook' as a first step,
  15737. and returns at first non-nil value."
  15738. (interactive "P")
  15739. (cond
  15740. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15741. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15742. ((org-with-limited-levels
  15743. (or (org-at-heading-p)
  15744. (and (org-region-active-p)
  15745. (save-excursion
  15746. (goto-char (region-beginning))
  15747. (org-at-heading-p)))))
  15748. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15749. (call-interactively 'org-do-promote))
  15750. ;; At an inline task.
  15751. ((org-at-heading-p)
  15752. (call-interactively 'org-inlinetask-promote))
  15753. ((or (org-at-item-p)
  15754. (and (org-region-active-p)
  15755. (save-excursion
  15756. (goto-char (region-beginning))
  15757. (org-at-item-p))))
  15758. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15759. (call-interactively 'org-outdent-item))
  15760. (t (call-interactively 'backward-word))))
  15761. (defun org-metaright (&optional _arg)
  15762. "Demote heading, list item at point or move table column right.
  15763. In front of a drawer or a block keyword, indent it correctly.
  15764. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15765. `org-indent-drawer' or `org-indent-block' depending on context.
  15766. With no specific context, calls the Emacs default `forward-word'.
  15767. See the individual commands for more information.
  15768. This function runs the hook `org-metaright-hook' as a first step,
  15769. and returns at first non-nil value."
  15770. (interactive "P")
  15771. (cond
  15772. ((run-hook-with-args-until-success 'org-metaright-hook))
  15773. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15774. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15775. ((org-at-block-p) (call-interactively 'org-indent-block))
  15776. ((org-with-limited-levels
  15777. (or (org-at-heading-p)
  15778. (and (org-region-active-p)
  15779. (save-excursion
  15780. (goto-char (region-beginning))
  15781. (org-at-heading-p)))))
  15782. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15783. (call-interactively 'org-do-demote))
  15784. ;; At an inline task.
  15785. ((org-at-heading-p)
  15786. (call-interactively 'org-inlinetask-demote))
  15787. ((or (org-at-item-p)
  15788. (and (org-region-active-p)
  15789. (save-excursion
  15790. (goto-char (region-beginning))
  15791. (org-at-item-p))))
  15792. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15793. (call-interactively 'org-indent-item))
  15794. (t (call-interactively 'forward-word))))
  15795. (defun org-check-for-hidden (what)
  15796. "Check if there are hidden headlines/items in the current visual line.
  15797. WHAT can be either `headlines' or `items'. If the current line is
  15798. an outline or item heading and it has a folded subtree below it,
  15799. this function returns t, nil otherwise."
  15800. (let ((re (cond
  15801. ((eq what 'headlines) org-outline-regexp-bol)
  15802. ((eq what 'items) (org-item-beginning-re))
  15803. (t (error "This should not happen"))))
  15804. beg end)
  15805. (save-excursion
  15806. (catch 'exit
  15807. (unless (org-region-active-p)
  15808. (setq beg (point-at-bol))
  15809. (beginning-of-line 2)
  15810. (while (and (not (eobp)) ;; this is like `next-line'
  15811. (get-char-property (1- (point)) 'invisible))
  15812. (beginning-of-line 2))
  15813. (setq end (point))
  15814. (goto-char beg)
  15815. (goto-char (point-at-eol))
  15816. (setq end (max end (point)))
  15817. (while (re-search-forward re end t)
  15818. (when (get-char-property (match-beginning 0) 'invisible)
  15819. (throw 'exit t))))
  15820. nil))))
  15821. (defun org-metaup (&optional _arg)
  15822. "Move subtree up or move table row up.
  15823. Calls `org-move-subtree-up' or `org-table-move-row' or
  15824. `org-move-item-up', depending on context. See the individual commands
  15825. for more information."
  15826. (interactive "P")
  15827. (cond
  15828. ((run-hook-with-args-until-success 'org-metaup-hook))
  15829. ((org-region-active-p)
  15830. (let* ((a (save-excursion
  15831. (goto-char (min (region-beginning) (region-end)))
  15832. (line-beginning-position)))
  15833. (b (save-excursion
  15834. (goto-char (max (region-beginning) (region-end)))
  15835. (if (bolp) (1- (point)) (line-end-position))))
  15836. (c (save-excursion
  15837. (goto-char a)
  15838. (move-beginning-of-line 0)
  15839. (point)))
  15840. (d (save-excursion
  15841. (goto-char a)
  15842. (move-end-of-line 0)
  15843. (point))))
  15844. (transpose-regions a b c d)
  15845. (goto-char c)))
  15846. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15847. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15848. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15849. (t (org-drag-element-backward))))
  15850. (defun org-metadown (&optional _arg)
  15851. "Move subtree down or move table row down.
  15852. Calls `org-move-subtree-down' or `org-table-move-row' or
  15853. `org-move-item-down', depending on context. See the individual
  15854. commands for more information."
  15855. (interactive "P")
  15856. (cond
  15857. ((run-hook-with-args-until-success 'org-metadown-hook))
  15858. ((org-region-active-p)
  15859. (let* ((a (save-excursion
  15860. (goto-char (min (region-beginning) (region-end)))
  15861. (line-beginning-position)))
  15862. (b (save-excursion
  15863. (goto-char (max (region-beginning) (region-end)))
  15864. (if (bolp) (1- (point)) (line-end-position))))
  15865. (c (save-excursion
  15866. (goto-char b)
  15867. (move-beginning-of-line (if (bolp) 1 2))
  15868. (point)))
  15869. (d (save-excursion
  15870. (goto-char b)
  15871. (move-end-of-line (if (bolp) 1 2))
  15872. (point))))
  15873. (transpose-regions a b c d)
  15874. (goto-char d)))
  15875. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15876. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15877. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15878. (t (org-drag-element-forward))))
  15879. (defun org-shiftup (&optional arg)
  15880. "Act on current element according to context.
  15881. Call `org-timestamp-up' or `org-priority-up', or
  15882. `org-previous-item', or `org-table-move-cell-up'. See the
  15883. individual commands for more information."
  15884. (interactive "P")
  15885. (cond
  15886. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15887. ((and org-support-shift-select (org-region-active-p))
  15888. (org-call-for-shift-select 'previous-line))
  15889. ((org-at-timestamp-p 'lax)
  15890. (call-interactively (if org-edit-timestamp-down-means-later
  15891. 'org-timestamp-down 'org-timestamp-up)))
  15892. ((and (not (eq org-support-shift-select 'always))
  15893. org-enable-priority-commands
  15894. (org-at-heading-p))
  15895. (call-interactively 'org-priority-up))
  15896. ((and (not org-support-shift-select) (org-at-item-p))
  15897. (call-interactively 'org-previous-item))
  15898. ((org-clocktable-try-shift 'up arg))
  15899. ((org-at-table-p) (org-table-move-cell-up))
  15900. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15901. (org-support-shift-select
  15902. (org-call-for-shift-select 'previous-line))
  15903. (t (org-shiftselect-error))))
  15904. (defun org-shiftdown (&optional arg)
  15905. "Act on current element according to context.
  15906. Call `org-timestamp-down' or `org-priority-down', or
  15907. `org-next-item', or `org-table-move-cell-down'. See the
  15908. individual commands for more information."
  15909. (interactive "P")
  15910. (cond
  15911. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15912. ((and org-support-shift-select (org-region-active-p))
  15913. (org-call-for-shift-select 'next-line))
  15914. ((org-at-timestamp-p 'lax)
  15915. (call-interactively (if org-edit-timestamp-down-means-later
  15916. 'org-timestamp-up 'org-timestamp-down)))
  15917. ((and (not (eq org-support-shift-select 'always))
  15918. org-enable-priority-commands
  15919. (org-at-heading-p))
  15920. (call-interactively 'org-priority-down))
  15921. ((and (not org-support-shift-select) (org-at-item-p))
  15922. (call-interactively 'org-next-item))
  15923. ((org-clocktable-try-shift 'down arg))
  15924. ((org-at-table-p) (org-table-move-cell-down))
  15925. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15926. (org-support-shift-select
  15927. (org-call-for-shift-select 'next-line))
  15928. (t (org-shiftselect-error))))
  15929. (defun org-shiftright (&optional arg)
  15930. "Act on the current element according to context.
  15931. This does one of the following:
  15932. - switch a timestamp at point one day into the future
  15933. - on a headline, switch to the next TODO keyword
  15934. - on an item, switch entire list to the next bullet type
  15935. - on a property line, switch to the next allowed value
  15936. - on a clocktable definition line, move time block into the future
  15937. - in a table, move a single cell right"
  15938. (interactive "P")
  15939. (cond
  15940. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15941. ((and org-support-shift-select (org-region-active-p))
  15942. (org-call-for-shift-select 'forward-char))
  15943. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15944. ((and (not (eq org-support-shift-select 'always))
  15945. (org-at-heading-p))
  15946. (let ((org-inhibit-logging
  15947. (not org-treat-S-cursor-todo-selection-as-state-change))
  15948. (org-inhibit-blocking
  15949. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15950. (org-call-with-arg 'org-todo 'right)))
  15951. ((or (and org-support-shift-select
  15952. (not (eq org-support-shift-select 'always))
  15953. (org-at-item-bullet-p))
  15954. (and (not org-support-shift-select) (org-at-item-p)))
  15955. (org-call-with-arg 'org-cycle-list-bullet nil))
  15956. ((and (not (eq org-support-shift-select 'always))
  15957. (org-at-property-p))
  15958. (call-interactively 'org-property-next-allowed-value))
  15959. ((org-clocktable-try-shift 'right arg))
  15960. ((org-at-table-p) (org-table-move-cell-right))
  15961. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15962. (org-support-shift-select
  15963. (org-call-for-shift-select 'forward-char))
  15964. (t (org-shiftselect-error))))
  15965. (defun org-shiftleft (&optional arg)
  15966. "Act on current element according to context.
  15967. This does one of the following:
  15968. - switch a timestamp at point one day into the past
  15969. - on a headline, switch to the previous TODO keyword.
  15970. - on an item, switch entire list to the previous bullet type
  15971. - on a property line, switch to the previous allowed value
  15972. - on a clocktable definition line, move time block into the past
  15973. - in a table, move a single cell left"
  15974. (interactive "P")
  15975. (cond
  15976. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15977. ((and org-support-shift-select (org-region-active-p))
  15978. (org-call-for-shift-select 'backward-char))
  15979. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15980. ((and (not (eq org-support-shift-select 'always))
  15981. (org-at-heading-p))
  15982. (let ((org-inhibit-logging
  15983. (not org-treat-S-cursor-todo-selection-as-state-change))
  15984. (org-inhibit-blocking
  15985. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15986. (org-call-with-arg 'org-todo 'left)))
  15987. ((or (and org-support-shift-select
  15988. (not (eq org-support-shift-select 'always))
  15989. (org-at-item-bullet-p))
  15990. (and (not org-support-shift-select) (org-at-item-p)))
  15991. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15992. ((and (not (eq org-support-shift-select 'always))
  15993. (org-at-property-p))
  15994. (call-interactively 'org-property-previous-allowed-value))
  15995. ((org-clocktable-try-shift 'left arg))
  15996. ((org-at-table-p) (org-table-move-cell-left))
  15997. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15998. (org-support-shift-select
  15999. (org-call-for-shift-select 'backward-char))
  16000. (t (org-shiftselect-error))))
  16001. (defun org-shiftcontrolright ()
  16002. "Switch to next TODO set."
  16003. (interactive)
  16004. (cond
  16005. ((and org-support-shift-select (org-region-active-p))
  16006. (org-call-for-shift-select 'forward-word))
  16007. ((and (not (eq org-support-shift-select 'always))
  16008. (org-at-heading-p))
  16009. (org-call-with-arg 'org-todo 'nextset))
  16010. (org-support-shift-select
  16011. (org-call-for-shift-select 'forward-word))
  16012. (t (org-shiftselect-error))))
  16013. (defun org-shiftcontrolleft ()
  16014. "Switch to previous TODO set."
  16015. (interactive)
  16016. (cond
  16017. ((and org-support-shift-select (org-region-active-p))
  16018. (org-call-for-shift-select 'backward-word))
  16019. ((and (not (eq org-support-shift-select 'always))
  16020. (org-at-heading-p))
  16021. (org-call-with-arg 'org-todo 'previousset))
  16022. (org-support-shift-select
  16023. (org-call-for-shift-select 'backward-word))
  16024. (t (org-shiftselect-error))))
  16025. (defun org-shiftcontrolup (&optional n)
  16026. "Change timestamps synchronously up in CLOCK log lines.
  16027. Optional argument N tells to change by that many units."
  16028. (interactive "P")
  16029. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  16030. (let (org-support-shift-select)
  16031. (org-clock-timestamps-up n))
  16032. (user-error "Not at a clock log")))
  16033. (defun org-shiftcontroldown (&optional n)
  16034. "Change timestamps synchronously down in CLOCK log lines.
  16035. Optional argument N tells to change by that many units."
  16036. (interactive "P")
  16037. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  16038. (let (org-support-shift-select)
  16039. (org-clock-timestamps-down n))
  16040. (user-error "Not at a clock log")))
  16041. (defun org-increase-number-at-point (&optional inc)
  16042. "Increment the number at point.
  16043. With an optional prefix numeric argument INC, increment using
  16044. this numeric value."
  16045. (interactive "p")
  16046. (if (not (number-at-point))
  16047. (user-error "Not on a number")
  16048. (unless inc (setq inc 1))
  16049. (let ((pos (point))
  16050. (beg (skip-chars-backward "-+^/*0-9eE."))
  16051. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  16052. (setq nap (buffer-substring-no-properties
  16053. (+ pos beg) (+ pos beg end)))
  16054. (delete-region (+ pos beg) (+ pos beg end))
  16055. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  16056. (when (org-at-table-p)
  16057. (org-table-align)
  16058. (org-table-end-of-field 1))))
  16059. (defun org-decrease-number-at-point (&optional inc)
  16060. "Decrement the number at point.
  16061. With an optional prefix numeric argument INC, decrement using
  16062. this numeric value."
  16063. (interactive "p")
  16064. (org-increase-number-at-point (- (or inc 1))))
  16065. (defun org-ctrl-c-ret ()
  16066. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  16067. (interactive)
  16068. (cond
  16069. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  16070. (t (call-interactively 'org-insert-heading))))
  16071. (defun org-copy-visible (beg end)
  16072. "Copy the visible parts of the region."
  16073. (interactive "r")
  16074. (let ((result ""))
  16075. (while (/= beg end)
  16076. (when (get-char-property beg 'invisible)
  16077. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  16078. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  16079. (setq result (concat result (buffer-substring beg next)))
  16080. (setq beg next)))
  16081. (setq deactivate-mark t)
  16082. (kill-new result)
  16083. (message "Visible strings have been copied to the kill ring.")))
  16084. (defun org-copy-special ()
  16085. "Copy region in table or copy current subtree.
  16086. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  16087. context. See the individual commands for more information."
  16088. (interactive)
  16089. (call-interactively
  16090. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  16091. (defun org-cut-special ()
  16092. "Cut region in table or cut current subtree.
  16093. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  16094. context. See the individual commands for more information."
  16095. (interactive)
  16096. (call-interactively
  16097. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  16098. (defun org-paste-special (arg)
  16099. "Paste rectangular region into table, or past subtree relative to level.
  16100. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  16101. See the individual commands for more information."
  16102. (interactive "P")
  16103. (if (org-at-table-p)
  16104. (org-table-paste-rectangle)
  16105. (org-paste-subtree arg)))
  16106. (defun org-edit-special (&optional arg)
  16107. "Call a special editor for the element at point.
  16108. When at a table, call the formula editor with `org-table-edit-formulas'.
  16109. When in a source code block, call `org-edit-src-code'.
  16110. When in a fixed-width region, call `org-edit-fixed-width-region'.
  16111. When in an export block, call `org-edit-export-block'.
  16112. When in a LaTeX environment, call `org-edit-latex-environment'.
  16113. When at an #+INCLUDE keyword, visit the included file.
  16114. When at a footnote reference, call `org-edit-footnote-reference'.
  16115. When at a planning line call, `org-deadline' and/or `org-schedule'.
  16116. When at an active timestamp, call `org-time-stamp'.
  16117. When at an inactive timestamp, call `org-time-stamp-inactive'.
  16118. On a link, call `ffap' to visit the link at point.
  16119. Otherwise, return a user error."
  16120. (interactive "P")
  16121. (let ((element (org-element-at-point)))
  16122. (barf-if-buffer-read-only)
  16123. (pcase (org-element-type element)
  16124. (`src-block
  16125. (if (not arg) (org-edit-src-code)
  16126. (let* ((info (org-babel-get-src-block-info))
  16127. (lang (nth 0 info))
  16128. (params (nth 2 info))
  16129. (session (cdr (assq :session params))))
  16130. (if (not session) (org-edit-src-code)
  16131. ;; At a source block with a session and function called
  16132. ;; with an ARG: switch to the buffer related to the
  16133. ;; inferior process.
  16134. (switch-to-buffer
  16135. (funcall (intern (concat "org-babel-prep-session:" lang))
  16136. session params))))))
  16137. (`keyword
  16138. (unless (member (org-element-property :key element)
  16139. '("INCLUDE" "SETUPFILE"))
  16140. (user-error "No special environment to edit here"))
  16141. (let ((value (org-element-property :value element)))
  16142. (unless (org-string-nw-p value) (user-error "No file to edit"))
  16143. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  16144. (or (match-string 1 value)
  16145. (match-string 0 value)))))
  16146. (when (org-file-url-p file)
  16147. (user-error "Files located with a URL cannot be edited"))
  16148. (org-link-open-from-string
  16149. (format "[[%s]]" (expand-file-name file))))))
  16150. (`table
  16151. (if (eq (org-element-property :type element) 'table.el)
  16152. (org-edit-table.el)
  16153. (call-interactively 'org-table-edit-formulas)))
  16154. ;; Only Org tables contain `table-row' type elements.
  16155. (`table-row (call-interactively 'org-table-edit-formulas))
  16156. (`example-block (org-edit-src-code))
  16157. (`export-block (org-edit-export-block))
  16158. (`fixed-width (org-edit-fixed-width-region))
  16159. (`latex-environment (org-edit-latex-environment))
  16160. (`planning
  16161. (let ((proplist (cadr element)))
  16162. (mapc #'call-interactively
  16163. (remq nil
  16164. (list
  16165. (when (plist-get proplist :deadline) #'org-deadline)
  16166. (when (plist-get proplist :scheduled) #'org-schedule))))))
  16167. (_
  16168. ;; No notable element at point. Though, we may be at a link or
  16169. ;; a footnote reference, which are objects. Thus, scan deeper.
  16170. (let ((context (org-element-context element)))
  16171. (pcase (org-element-type context)
  16172. (`footnote-reference (org-edit-footnote-reference))
  16173. (`inline-src-block (org-edit-inline-src-code))
  16174. (`timestamp (if (eq 'inactive (org-element-property :type context))
  16175. (call-interactively #'org-time-stamp-inactive)
  16176. (call-interactively #'org-time-stamp)))
  16177. (`link (call-interactively #'ffap))
  16178. (_ (user-error "No special environment to edit here"))))))))
  16179. (defun org-ctrl-c-ctrl-c (&optional arg)
  16180. "Set tags in headline, or update according to changed information at point.
  16181. This command does many different things, depending on context:
  16182. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  16183. this is what we do.
  16184. - If the cursor is on a statistics cookie, update it.
  16185. - If the cursor is in a headline, prompt for tags and insert them
  16186. into the current line, aligned to `org-tags-column'. When called
  16187. with prefix arg, realign all tags in the current buffer.
  16188. - If the cursor is in one of the special #+KEYWORD lines, this
  16189. triggers scanning the buffer for these lines and updating the
  16190. information.
  16191. - If the cursor is inside a table, realign the table. This command
  16192. works even if the automatic table editor has been turned off.
  16193. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  16194. the entire table.
  16195. - If the cursor is at a footnote reference or definition, jump to
  16196. the corresponding definition or references, respectively.
  16197. - If the cursor is a the beginning of a dynamic block, update it.
  16198. - If the current buffer is a capture buffer, close note and file it.
  16199. - If the cursor is on a <<<target>>>, update radio targets and
  16200. corresponding links in this buffer.
  16201. - If the cursor is on a numbered item in a plain list, renumber the
  16202. ordered list.
  16203. - If the cursor is on a checkbox, toggle it.
  16204. - If the cursor is on a code block, evaluate it. The variable
  16205. `org-confirm-babel-evaluate' can be used to control prompting
  16206. before code block evaluation, by default every code block
  16207. evaluation requires confirmation. Code block evaluation can be
  16208. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  16209. (interactive "P")
  16210. (cond
  16211. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  16212. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  16213. (org-remove-occur-highlights)
  16214. (message "Temporary highlights/overlays removed from current buffer"))
  16215. ((and (local-variable-p 'org-finish-function)
  16216. (fboundp org-finish-function))
  16217. (funcall org-finish-function))
  16218. ((org-babel-hash-at-point))
  16219. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  16220. (t
  16221. (let* ((context
  16222. (org-element-lineage
  16223. (org-element-context)
  16224. ;; Limit to supported contexts.
  16225. '(babel-call clock dynamic-block footnote-definition
  16226. footnote-reference inline-babel-call inline-src-block
  16227. inlinetask item keyword node-property paragraph
  16228. plain-list planning property-drawer radio-target
  16229. src-block statistics-cookie table table-cell table-row
  16230. timestamp)
  16231. t))
  16232. (type (org-element-type context)))
  16233. ;; For convenience: at the first line of a paragraph on the same
  16234. ;; line as an item, apply function on that item instead.
  16235. (when (eq type 'paragraph)
  16236. (let ((parent (org-element-property :parent context)))
  16237. (when (and (eq (org-element-type parent) 'item)
  16238. (= (line-beginning-position)
  16239. (org-element-property :begin parent)))
  16240. (setq context parent)
  16241. (setq type 'item))))
  16242. ;; Act according to type of element or object at point.
  16243. ;;
  16244. ;; Do nothing on a blank line, except if it is contained in
  16245. ;; a source block. Hence, we first check if point is in such
  16246. ;; a block and then if it is at a blank line.
  16247. (pcase type
  16248. ((or `inline-src-block `src-block)
  16249. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  16250. (org-babel-eval-wipe-error-buffer)
  16251. (org-babel-execute-src-block
  16252. current-prefix-arg (org-babel-get-src-block-info nil context))))
  16253. ((guard (org-match-line "[ \t]*$"))
  16254. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  16255. (user-error
  16256. (substitute-command-keys
  16257. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  16258. ((or `babel-call `inline-babel-call)
  16259. (let ((info (org-babel-lob-get-info context)))
  16260. (when info (org-babel-execute-src-block nil info))))
  16261. (`clock (org-clock-update-time-maybe))
  16262. (`dynamic-block
  16263. (save-excursion
  16264. (goto-char (org-element-property :post-affiliated context))
  16265. (org-update-dblock)))
  16266. (`footnote-definition
  16267. (goto-char (org-element-property :post-affiliated context))
  16268. (call-interactively 'org-footnote-action))
  16269. (`footnote-reference (call-interactively #'org-footnote-action))
  16270. ((or `headline `inlinetask)
  16271. (save-excursion (goto-char (org-element-property :begin context))
  16272. (call-interactively #'org-set-tags-command)))
  16273. (`item
  16274. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  16275. ;; unconditionally, whereas `C-u' will toggle its presence.
  16276. ;; Without a universal argument, if the item has a checkbox,
  16277. ;; toggle it. Otherwise repair the list.
  16278. (let* ((box (org-element-property :checkbox context))
  16279. (struct (org-element-property :structure context))
  16280. (old-struct (copy-tree struct))
  16281. (parents (org-list-parents-alist struct))
  16282. (prevs (org-list-prevs-alist struct))
  16283. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  16284. (org-list-set-checkbox
  16285. (org-element-property :begin context) struct
  16286. (cond ((equal arg '(16)) "[-]")
  16287. ((and (not box) (equal arg '(4))) "[ ]")
  16288. ((or (not box) (equal arg '(4))) nil)
  16289. ((eq box 'on) "[ ]")
  16290. (t "[X]")))
  16291. ;; Mimic `org-list-write-struct' but with grabbing a return
  16292. ;; value from `org-list-struct-fix-box'.
  16293. (org-list-struct-fix-ind struct parents 2)
  16294. (org-list-struct-fix-item-end struct)
  16295. (org-list-struct-fix-bul struct prevs)
  16296. (org-list-struct-fix-ind struct parents)
  16297. (let ((block-item
  16298. (org-list-struct-fix-box struct parents prevs orderedp)))
  16299. (if (and box (equal struct old-struct))
  16300. (if (equal arg '(16))
  16301. (message "Checkboxes already reset")
  16302. (user-error "Cannot toggle this checkbox: %s"
  16303. (if (eq box 'on)
  16304. "all subitems checked"
  16305. "unchecked subitems")))
  16306. (org-list-struct-apply-struct struct old-struct)
  16307. (org-update-checkbox-count-maybe))
  16308. (when block-item
  16309. (message "Checkboxes were removed due to empty box at line %d"
  16310. (org-current-line block-item))))))
  16311. (`keyword
  16312. (let ((org-inhibit-startup-visibility-stuff t)
  16313. (org-startup-align-all-tables nil))
  16314. (when (boundp 'org-table-coordinate-overlays)
  16315. (mapc #'delete-overlay org-table-coordinate-overlays)
  16316. (setq org-table-coordinate-overlays nil))
  16317. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  16318. (message "Local setup has been refreshed"))
  16319. (`plain-list
  16320. ;; At a plain list, with a double C-u argument, set
  16321. ;; checkboxes of each item to "[-]", whereas a single one
  16322. ;; will toggle their presence according to the state of the
  16323. ;; first item in the list. Without an argument, repair the
  16324. ;; list.
  16325. (let* ((begin (org-element-property :contents-begin context))
  16326. (struct (org-element-property :structure context))
  16327. (old-struct (copy-tree struct))
  16328. (first-box (save-excursion
  16329. (goto-char begin)
  16330. (looking-at org-list-full-item-re)
  16331. (match-string-no-properties 3)))
  16332. (new-box (cond ((equal arg '(16)) "[-]")
  16333. ((equal arg '(4)) (unless first-box "[ ]"))
  16334. ((equal first-box "[X]") "[ ]")
  16335. (t "[X]"))))
  16336. (cond
  16337. (arg
  16338. (dolist (pos
  16339. (org-list-get-all-items
  16340. begin struct (org-list-prevs-alist struct)))
  16341. (org-list-set-checkbox pos struct new-box)))
  16342. ((and first-box (eq (point) begin))
  16343. ;; For convenience, when point is at bol on the first
  16344. ;; item of the list and no argument is provided, simply
  16345. ;; toggle checkbox of that item, if any.
  16346. (org-list-set-checkbox begin struct new-box)))
  16347. (when (equal
  16348. (org-list-write-struct
  16349. struct (org-list-parents-alist struct) old-struct)
  16350. old-struct)
  16351. (message "Cannot update this checkbox"))
  16352. (org-update-checkbox-count-maybe)))
  16353. ((or `property-drawer `node-property)
  16354. (call-interactively #'org-property-action))
  16355. (`radio-target
  16356. (call-interactively #'org-update-radio-target-regexp))
  16357. (`statistics-cookie
  16358. (call-interactively #'org-update-statistics-cookies))
  16359. ((or `table `table-cell `table-row)
  16360. ;; At a table, recalculate every field and align it. Also
  16361. ;; send the table if necessary. If the table has
  16362. ;; a `table.el' type, just give up. At a table row or cell,
  16363. ;; maybe recalculate line but always align table.
  16364. (if (eq (org-element-property :type context) 'table.el)
  16365. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16366. Use `\\[org-edit-special]' to edit table.el tables"))
  16367. (if (or (eq type 'table)
  16368. ;; Check if point is at a TBLFM line.
  16369. (and (eq type 'table-row)
  16370. (= (point) (org-element-property :end context))))
  16371. (save-excursion
  16372. (if (org-at-TBLFM-p)
  16373. (progn (require 'org-table)
  16374. (org-table-calc-current-TBLFM))
  16375. (goto-char (org-element-property :contents-begin context))
  16376. (org-call-with-arg 'org-table-recalculate (or arg t))
  16377. (orgtbl-send-table 'maybe)))
  16378. (org-table-maybe-eval-formula)
  16379. (cond (arg (call-interactively #'org-table-recalculate))
  16380. ((org-table-maybe-recalculate-line))
  16381. (t (org-table-align))))))
  16382. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16383. (org-timestamp-change 0 'day))
  16384. ((and `nil (guard (org-at-heading-p)))
  16385. ;; When point is on an unsupported object type, we can miss
  16386. ;; the fact that it also is at a heading. Handle it here.
  16387. (call-interactively #'org-set-tags-command))
  16388. ((guard
  16389. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16390. (_
  16391. (user-error
  16392. (substitute-command-keys
  16393. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16394. (defun org-mode-restart ()
  16395. (interactive)
  16396. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16397. (funcall major-mode)
  16398. (hack-local-variables)
  16399. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16400. (org-indent-mode -1))
  16401. (org-reset-file-cache))
  16402. (message "%s restarted" major-mode))
  16403. (defun org-flag-above-first-heading (&optional arg)
  16404. "Hide from bob up to the first heading.
  16405. Move point to the beginning of first heading or end of buffer."
  16406. (goto-char (point-min))
  16407. (unless (org-at-heading-p)
  16408. (outline-next-heading))
  16409. (unless (bobp)
  16410. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16411. (defun org-show-branches-buffer ()
  16412. "Show all branches in the buffer."
  16413. (org-flag-above-first-heading)
  16414. (outline-hide-sublevels 1)
  16415. (unless (eobp)
  16416. (outline-show-branches)
  16417. (while (outline-get-next-sibling)
  16418. (outline-show-branches)))
  16419. (goto-char (point-min)))
  16420. (defun org-kill-note-or-show-branches ()
  16421. "Abort storing current note, or show just branches."
  16422. (interactive)
  16423. (cond (org-finish-function
  16424. (let ((org-note-abort t)) (funcall org-finish-function)))
  16425. ((org-before-first-heading-p)
  16426. (org-show-branches-buffer)
  16427. (org-hide-archived-subtrees (point-min) (point-max)))
  16428. (t
  16429. (let ((beg (progn (org-back-to-heading) (point)))
  16430. (end (save-excursion (org-end-of-subtree t t) (point))))
  16431. (outline-hide-subtree)
  16432. (outline-show-branches)
  16433. (org-hide-archived-subtrees beg end)))))
  16434. (defun org-delete-indentation (&optional arg)
  16435. "Join current line to previous and fix whitespace at join.
  16436. If previous line is a headline add to headline title. Otherwise
  16437. the function calls `delete-indentation'.
  16438. With a non-nil optional argument, join it to the following one."
  16439. (interactive "*P")
  16440. (if (save-excursion
  16441. (beginning-of-line (if arg 1 0))
  16442. (let ((case-fold-search nil))
  16443. (looking-at org-complex-heading-regexp)))
  16444. ;; At headline.
  16445. (let ((tags-column (when (match-beginning 5)
  16446. (save-excursion (goto-char (match-beginning 5))
  16447. (current-column))))
  16448. (string (concat " " (progn (when arg (forward-line 1))
  16449. (org-trim (delete-and-extract-region
  16450. (line-beginning-position)
  16451. (line-end-position)))))))
  16452. (unless (bobp) (delete-region (point) (1- (point))))
  16453. (goto-char (or (match-end 4)
  16454. (match-beginning 5)
  16455. (match-end 0)))
  16456. (skip-chars-backward " \t")
  16457. (save-excursion (insert string))
  16458. ;; Adjust alignment of tags.
  16459. (cond
  16460. ((not tags-column)) ;no tags
  16461. (org-auto-align-tags (org-align-tags))
  16462. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16463. (delete-indentation arg)))
  16464. (defun org-open-line (n)
  16465. "Insert a new row in tables, call `open-line' elsewhere.
  16466. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16467. As a special case, when a document starts with a table, allow to
  16468. call `open-line' on the very first character."
  16469. (interactive "*p")
  16470. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16471. (org-table-insert-row)
  16472. (open-line n)))
  16473. (defun org-return (&optional indent)
  16474. "Goto next table row or insert a newline.
  16475. Calls `org-table-next-row' or `newline', depending on context.
  16476. When optional INDENT argument is non-nil, call
  16477. `newline-and-indent' instead of `newline'.
  16478. When `org-return-follows-link' is non-nil and point is on
  16479. a timestamp or a link, call `org-open-at-point'. However, it
  16480. will not happen if point is in a table or on a \"dead\"
  16481. object (e.g., within a comment). In these case, you need to use
  16482. `org-open-at-point' directly."
  16483. (interactive)
  16484. (let ((context (if org-return-follows-link (org-element-context)
  16485. (org-element-at-point))))
  16486. (cond
  16487. ;; In a table, call `org-table-next-row'. However, before first
  16488. ;; column or after last one, split the table.
  16489. ((or (and (eq 'table (org-element-type context))
  16490. (not (eq 'table.el (org-element-property :type context)))
  16491. (>= (point) (org-element-property :contents-begin context))
  16492. (< (point) (org-element-property :contents-end context)))
  16493. (org-element-lineage context '(table-row table-cell) t))
  16494. (if (or (looking-at-p "[ \t]*$")
  16495. (save-excursion (skip-chars-backward " \t") (bolp)))
  16496. (insert "\n")
  16497. (org-table-justify-field-maybe)
  16498. (call-interactively #'org-table-next-row)))
  16499. ;; On a link or a timestamp, call `org-open-at-point' if
  16500. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16501. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16502. ((and org-return-follows-link
  16503. (or (and (eq 'link (org-element-type context))
  16504. ;; Ensure point is not on the white spaces after
  16505. ;; the link.
  16506. (let ((origin (point)))
  16507. (org-with-point-at (org-element-property :end context)
  16508. (skip-chars-backward " \t")
  16509. (> (point) origin))))
  16510. (org-in-regexp org-ts-regexp-both nil t)
  16511. (org-in-regexp org-tsr-regexp-both nil t)
  16512. (org-in-regexp org-link-any-re nil t)))
  16513. (call-interactively #'org-open-at-point))
  16514. ;; Insert newline in heading, but preserve tags.
  16515. ((and (not (bolp))
  16516. (let ((case-fold-search nil))
  16517. (org-match-line org-complex-heading-regexp)))
  16518. ;; At headline. Split line. However, if point is on keyword,
  16519. ;; priority cookie or tags, do not break any of them: add
  16520. ;; a newline after the headline instead.
  16521. (let ((tags-column (and (match-beginning 5)
  16522. (save-excursion (goto-char (match-beginning 5))
  16523. (current-column))))
  16524. (string
  16525. (when (and (match-end 4) (org-point-in-group (point) 4))
  16526. (delete-and-extract-region (point) (match-end 4)))))
  16527. ;; Adjust tag alignment.
  16528. (cond
  16529. ((not (and tags-column string)))
  16530. (org-auto-align-tags (org-align-tags))
  16531. (t (org--align-tags-here tags-column))) ;preserve tags column
  16532. (end-of-line)
  16533. (org-show-entry)
  16534. (if indent (newline-and-indent) (newline))
  16535. (when string (save-excursion (insert (org-trim string))))))
  16536. ;; In a list, make sure indenting keeps trailing text within.
  16537. ((and indent
  16538. (not (eolp))
  16539. (org-element-lineage context '(item)))
  16540. (let ((trailing-data
  16541. (delete-and-extract-region (point) (line-end-position))))
  16542. (newline-and-indent)
  16543. (save-excursion (insert trailing-data))))
  16544. (t
  16545. ;; Do not auto-fill when point is in an Org property drawer.
  16546. (let ((auto-fill-function (and (not (org-at-property-p))
  16547. auto-fill-function)))
  16548. (if indent
  16549. (newline-and-indent)
  16550. (newline)))))))
  16551. (defun org-return-indent ()
  16552. "Goto next table row or insert a newline and indent.
  16553. Calls `org-table-next-row' or `newline-and-indent', depending on
  16554. context. See the individual commands for more information."
  16555. (interactive)
  16556. (org-return t))
  16557. (defun org-ctrl-c-tab (&optional arg)
  16558. "Toggle columns width in a table, or show children.
  16559. Call `org-table-toggle-column-width' if point is in a table.
  16560. Otherwise, call `org-show-children'. ARG is the level to hide."
  16561. (interactive "p")
  16562. (if (org-at-table-p)
  16563. (call-interactively #'org-table-toggle-column-width)
  16564. (if (org-before-first-heading-p)
  16565. (progn
  16566. (org-flag-above-first-heading)
  16567. (outline-hide-sublevels (or arg 1))
  16568. (goto-char (point-min)))
  16569. (outline-hide-subtree)
  16570. (org-show-children arg))))
  16571. (defun org-ctrl-c-star ()
  16572. "Compute table, or change heading status of lines.
  16573. Calls `org-table-recalculate' or `org-toggle-heading',
  16574. depending on context."
  16575. (interactive)
  16576. (cond
  16577. ((org-at-table-p)
  16578. (call-interactively 'org-table-recalculate))
  16579. (t
  16580. ;; Convert all lines in region to list items
  16581. (call-interactively 'org-toggle-heading))))
  16582. (defun org-ctrl-c-minus ()
  16583. "Insert separator line in table or modify bullet status of line.
  16584. Also turns a plain line or a region of lines into list items.
  16585. Calls `org-table-insert-hline', `org-toggle-item', or
  16586. `org-cycle-list-bullet', depending on context."
  16587. (interactive)
  16588. (cond
  16589. ((org-at-table-p)
  16590. (call-interactively 'org-table-insert-hline))
  16591. ((org-region-active-p)
  16592. (call-interactively 'org-toggle-item))
  16593. ((org-in-item-p)
  16594. (call-interactively 'org-cycle-list-bullet))
  16595. (t
  16596. (call-interactively 'org-toggle-item))))
  16597. (defun org-toggle-heading (&optional nstars)
  16598. "Convert headings to normal text, or items or text to headings.
  16599. If there is no active region, only convert the current line.
  16600. With a `\\[universal-argument]' prefix, convert the whole list at
  16601. point into heading.
  16602. In a region:
  16603. - If the first non blank line is a headline, remove the stars
  16604. from all headlines in the region.
  16605. - If it is a normal line, turn each and every normal line (i.e.,
  16606. not an heading or an item) in the region into headings. If you
  16607. want to convert only the first line of this region, use one
  16608. universal prefix argument.
  16609. - If it is a plain list item, turn all plain list items into headings.
  16610. When converting a line into a heading, the number of stars is chosen
  16611. such that the lines become children of the current entry. However,
  16612. when a numeric prefix argument is given, its value determines the
  16613. number of stars to add."
  16614. (interactive "P")
  16615. (let ((skip-blanks
  16616. (function
  16617. ;; Return beginning of first non-blank line, starting from
  16618. ;; line at POS.
  16619. (lambda (pos)
  16620. (save-excursion
  16621. (goto-char pos)
  16622. (while (org-at-comment-p) (forward-line))
  16623. (skip-chars-forward " \r\t\n")
  16624. (point-at-bol)))))
  16625. beg end toggled)
  16626. ;; Determine boundaries of changes. If a universal prefix has
  16627. ;; been given, put the list in a region. If region ends at a bol,
  16628. ;; do not consider the last line to be in the region.
  16629. (when (and current-prefix-arg (org-at-item-p))
  16630. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16631. (org-mark-element))
  16632. (if (org-region-active-p)
  16633. (setq beg (funcall skip-blanks (region-beginning))
  16634. end (copy-marker (save-excursion
  16635. (goto-char (region-end))
  16636. (if (bolp) (point) (point-at-eol)))))
  16637. (setq beg (funcall skip-blanks (point-at-bol))
  16638. end (copy-marker (point-at-eol))))
  16639. ;; Ensure inline tasks don't count as headings.
  16640. (org-with-limited-levels
  16641. (save-excursion
  16642. (goto-char beg)
  16643. (cond
  16644. ;; Case 1. Started at an heading: de-star headings.
  16645. ((org-at-heading-p)
  16646. (while (< (point) end)
  16647. (when (org-at-heading-p t)
  16648. (looking-at org-outline-regexp) (replace-match "")
  16649. (setq toggled t))
  16650. (forward-line)))
  16651. ;; Case 2. Started at an item: change items into headlines.
  16652. ;; One star will be added by `org-list-to-subtree'.
  16653. ((org-at-item-p)
  16654. (while (< (point) end)
  16655. (when (org-at-item-p)
  16656. ;; Pay attention to cases when region ends before list.
  16657. (let* ((struct (org-list-struct))
  16658. (list-end
  16659. (min (org-list-get-bottom-point struct) (1+ end))))
  16660. (save-restriction
  16661. (narrow-to-region (point) list-end)
  16662. (insert (org-list-to-subtree
  16663. (org-list-to-lisp t)
  16664. (pcase (org-current-level)
  16665. (`nil 1)
  16666. (l (1+ (org-reduced-level l)))))
  16667. "\n")))
  16668. (setq toggled t))
  16669. (forward-line)))
  16670. ;; Case 3. Started at normal text: make every line an heading,
  16671. ;; skipping headlines and items.
  16672. (t (let* ((stars
  16673. (make-string
  16674. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16675. (add-stars
  16676. (cond (nstars "") ; stars from prefix only
  16677. ((equal stars "") "*") ; before first heading
  16678. (org-odd-levels-only "**") ; inside heading, odd
  16679. (t "*"))) ; inside heading, oddeven
  16680. (rpl (concat stars add-stars " "))
  16681. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16682. (while (< (point) (if (equal nstars '(4)) lend end))
  16683. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16684. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16685. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16686. (forward-line)))))))
  16687. (unless toggled (message "Cannot toggle heading from here"))))
  16688. (defun org-meta-return (&optional arg)
  16689. "Insert a new heading or wrap a region in a table.
  16690. Calls `org-insert-heading', `org-insert-item' or
  16691. `org-table-wrap-region', depending on context. When called with
  16692. an argument, unconditionally call `org-insert-heading'."
  16693. (interactive "P")
  16694. (org-check-before-invisible-edit 'insert)
  16695. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16696. (call-interactively (cond (arg #'org-insert-heading)
  16697. ((org-at-table-p) #'org-table-wrap-region)
  16698. ((org-in-item-p) #'org-insert-item)
  16699. (t #'org-insert-heading)))))
  16700. ;;; Menu entries
  16701. (defsubst org-in-subtree-not-table-p ()
  16702. "Are we in a subtree and not in a table?"
  16703. (and (not (org-before-first-heading-p))
  16704. (not (org-at-table-p))))
  16705. ;; Define the Org mode menus
  16706. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  16707. '("Tbl"
  16708. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16709. ["Next Field" org-cycle (org-at-table-p)]
  16710. ["Previous Field" org-shifttab (org-at-table-p)]
  16711. ["Next Row" org-return (org-at-table-p)]
  16712. "--"
  16713. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16714. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16715. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16716. "--"
  16717. ("Column"
  16718. ["Move Column Left" org-metaleft (org-at-table-p)]
  16719. ["Move Column Right" org-metaright (org-at-table-p)]
  16720. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16721. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16722. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16723. ("Row"
  16724. ["Move Row Up" org-metaup (org-at-table-p)]
  16725. ["Move Row Down" org-metadown (org-at-table-p)]
  16726. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16727. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16728. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16729. "--"
  16730. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16731. ("Rectangle"
  16732. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16733. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16734. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16735. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16736. "--"
  16737. ("Calculate"
  16738. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16739. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16740. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16741. "--"
  16742. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16743. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16744. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16745. "--"
  16746. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16747. "--"
  16748. ["Sum Column/Rectangle" org-table-sum
  16749. (or (org-at-table-p) (org-region-active-p))]
  16750. ["Which Column?" org-table-current-column (org-at-table-p)])
  16751. ["Debug Formulas"
  16752. org-table-toggle-formula-debugger
  16753. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16754. ["Show Col/Row Numbers"
  16755. org-table-toggle-coordinate-overlays
  16756. :style toggle
  16757. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16758. "--"
  16759. ["Create" org-table-create (not (org-at-table-p))]
  16760. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16761. ["Import from File" org-table-import (not (org-at-table-p))]
  16762. ["Export to File" org-table-export (org-at-table-p)]
  16763. "--"
  16764. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16765. "--"
  16766. ("Plot"
  16767. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16768. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16769. (easy-menu-define org-org-menu org-mode-map "Org menu"
  16770. '("Org"
  16771. ("Show/Hide"
  16772. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16773. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16774. ["Sparse Tree..." org-sparse-tree t]
  16775. ["Reveal Context" org-reveal t]
  16776. ["Show All" org-show-all t]
  16777. "--"
  16778. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16779. "--"
  16780. ["New Heading" org-insert-heading t]
  16781. ("Navigate Headings"
  16782. ["Up" outline-up-heading t]
  16783. ["Next" outline-next-visible-heading t]
  16784. ["Previous" outline-previous-visible-heading t]
  16785. ["Next Same Level" outline-forward-same-level t]
  16786. ["Previous Same Level" outline-backward-same-level t]
  16787. "--"
  16788. ["Jump" org-goto t])
  16789. ("Edit Structure"
  16790. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  16791. "--"
  16792. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16793. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16794. "--"
  16795. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16796. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16797. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16798. "--"
  16799. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16800. "--"
  16801. ["Copy visible text" org-copy-visible t]
  16802. "--"
  16803. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16804. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16805. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16806. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16807. "--"
  16808. ["Sort Region/Children" org-sort t]
  16809. "--"
  16810. ["Convert to odd levels" org-convert-to-odd-levels t]
  16811. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16812. ("Editing"
  16813. ["Emphasis..." org-emphasize t]
  16814. ["Edit Source Example" org-edit-special t]
  16815. "--"
  16816. ["Footnote new/jump" org-footnote-action t]
  16817. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16818. ("Archive"
  16819. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16820. "--"
  16821. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16822. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16823. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  16824. )
  16825. "--"
  16826. ("Hyperlinks"
  16827. ["Store Link (Global)" org-store-link t]
  16828. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16829. ["Insert Link" org-insert-link t]
  16830. ["Follow Link" org-open-at-point t]
  16831. "--"
  16832. ["Next link" org-next-link t]
  16833. ["Previous link" org-previous-link t]
  16834. "--"
  16835. ["Descriptive Links"
  16836. org-toggle-link-display
  16837. :style radio
  16838. :selected org-descriptive-links
  16839. ]
  16840. ["Literal Links"
  16841. org-toggle-link-display
  16842. :style radio
  16843. :selected (not org-descriptive-links)])
  16844. "--"
  16845. ("TODO Lists"
  16846. ["TODO/DONE/-" org-todo t]
  16847. ("Select keyword"
  16848. ["Next keyword" org-shiftright (org-at-heading-p)]
  16849. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16850. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16851. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16852. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16853. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16854. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16855. "--"
  16856. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16857. :selected org-enforce-todo-dependencies :style toggle :active t]
  16858. "Settings for tree at point"
  16859. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16860. :selected (org-entry-get nil "ORDERED")
  16861. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16862. ["Do Children parallel" org-toggle-ordered-property :style radio
  16863. :selected (not (org-entry-get nil "ORDERED"))
  16864. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16865. "--"
  16866. ["Set Priority" org-priority t]
  16867. ["Priority Up" org-shiftup t]
  16868. ["Priority Down" org-shiftdown t]
  16869. "--"
  16870. ["Get news from all feeds" org-feed-update-all t]
  16871. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16872. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16873. ("TAGS and Properties"
  16874. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16875. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16876. "--"
  16877. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16878. ["Column view of properties" org-columns t]
  16879. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16880. ("Dates and Scheduling"
  16881. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16882. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16883. ("Change Date"
  16884. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16885. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16886. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16887. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16888. ["Compute Time Range" org-evaluate-time-range t]
  16889. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16890. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16891. "--"
  16892. ["Custom time format" org-toggle-time-stamp-overlays
  16893. :style radio :selected org-display-custom-times]
  16894. "--"
  16895. ["Goto Calendar" org-goto-calendar t]
  16896. ["Date from Calendar" org-date-from-calendar t]
  16897. "--"
  16898. ["Start/Restart Timer" org-timer-start t]
  16899. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16900. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16901. ["Insert Timer String" org-timer t]
  16902. ["Insert Timer Item" org-timer-item t])
  16903. ("Logging work"
  16904. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16905. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16906. ["Clock out" org-clock-out t]
  16907. ["Clock cancel" org-clock-cancel t]
  16908. "--"
  16909. ["Mark as default task" org-clock-mark-default-task t]
  16910. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16911. ["Goto running clock" org-clock-goto t]
  16912. "--"
  16913. ["Display times" org-clock-display t]
  16914. ["Create clock table" org-clock-report t]
  16915. "--"
  16916. ["Record DONE time"
  16917. (progn (setq org-log-done (not org-log-done))
  16918. (message "Switching to %s will %s record a timestamp"
  16919. (car org-done-keywords)
  16920. (if org-log-done "automatically" "not")))
  16921. :style toggle :selected org-log-done])
  16922. "--"
  16923. ["Agenda Command..." org-agenda t]
  16924. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16925. ("File List for Agenda")
  16926. ("Special views current file"
  16927. ["TODO Tree" org-show-todo-tree t]
  16928. ["Check Deadlines" org-check-deadlines t]
  16929. ["Tags/Property tree" org-match-sparse-tree t])
  16930. "--"
  16931. ["Export/Publish..." org-export-dispatch t]
  16932. ("LaTeX"
  16933. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16934. :style toggle :selected org-cdlatex-mode]
  16935. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16936. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16937. ["Modify math symbol" org-cdlatex-math-modify
  16938. (org-inside-LaTeX-fragment-p)]
  16939. ["Insert citation" org-reftex-citation t])
  16940. "--"
  16941. ("MobileOrg"
  16942. ["Push Files and Views" org-mobile-push t]
  16943. ["Get Captured and Flagged" org-mobile-pull t]
  16944. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  16945. "--"
  16946. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  16947. "--"
  16948. ("Documentation"
  16949. ["Show Version" org-version t]
  16950. ["Info Documentation" org-info t]
  16951. ["Browse Org News" org-browse-news t])
  16952. ("Customize"
  16953. ["Browse Org Group" org-customize t]
  16954. "--"
  16955. ["Expand This Menu" org-create-customize-menu
  16956. (fboundp 'customize-menu-create)])
  16957. ["Send bug report" org-submit-bug-report t]
  16958. "--"
  16959. ("Refresh/Reload"
  16960. ["Refresh setup current buffer" org-mode-restart t]
  16961. ["Reload Org (after update)" org-reload t]
  16962. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16963. (defun org-info (&optional node)
  16964. "Read documentation for Org in the info system.
  16965. With optional NODE, go directly to that node."
  16966. (interactive)
  16967. (info (format "(org)%s" (or node ""))))
  16968. (defun org-browse-news ()
  16969. "Browse the news for the latest major release."
  16970. (interactive)
  16971. (browse-url "https://orgmode.org/Changes.html"))
  16972. ;;;###autoload
  16973. (defun org-submit-bug-report ()
  16974. "Submit a bug report on Org via mail.
  16975. Don't hesitate to report any problems or inaccurate documentation.
  16976. If you don't have setup sending mail from (X)Emacs, please copy the
  16977. output buffer into your mail program, as it gives us important
  16978. information about your Org version and configuration."
  16979. (interactive)
  16980. (require 'reporter)
  16981. (defvar reporter-prompt-for-summary-p)
  16982. (org-load-modules-maybe)
  16983. (org-require-autoloaded-modules)
  16984. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16985. (reporter-submit-bug-report
  16986. "emacs-orgmode@gnu.org"
  16987. (org-version nil 'full)
  16988. (let (list)
  16989. (save-window-excursion
  16990. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16991. (delete-other-windows)
  16992. (erase-buffer)
  16993. (insert "You are about to submit a bug report to the Org mailing list.
  16994. We would like to add your full Org and Outline configuration to the
  16995. bug report. This greatly simplifies the work of the maintainer and
  16996. other experts on the mailing list.
  16997. HOWEVER, some variables you have customized may contain private
  16998. information. The names of customers, colleagues, or friends, might
  16999. appear in the form of file names, tags, todo states, or search strings.
  17000. If you answer yes to the prompt, you might want to check and remove
  17001. such private information before sending the email.")
  17002. (add-text-properties (point-min) (point-max) '(face org-warning))
  17003. (when (yes-or-no-p "Include your Org configuration ")
  17004. (mapatoms
  17005. (lambda (v)
  17006. (and (boundp v)
  17007. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  17008. (or (and (symbol-value v)
  17009. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  17010. (and
  17011. (get v 'custom-type) (get v 'standard-value)
  17012. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  17013. (push v list)))))
  17014. (kill-buffer (get-buffer "*Warn about privacy*"))
  17015. list))
  17016. nil nil
  17017. "Remember to cover the basics, that is, what you expected to happen and
  17018. what in fact did happen. You don't know how to make a good report? See
  17019. https://orgmode.org/manual/Feedback.html#Feedback
  17020. Your bug report will be posted to the Org mailing list.
  17021. ------------------------------------------------------------------------")
  17022. (save-excursion
  17023. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  17024. (replace-match "\\1Bug: \\3 [\\2]")))))
  17025. (defun org-install-agenda-files-menu ()
  17026. (let ((bl (buffer-list)))
  17027. (save-excursion
  17028. (while bl
  17029. (set-buffer (pop bl))
  17030. (when (derived-mode-p 'org-mode) (setq bl nil)))
  17031. (when (derived-mode-p 'org-mode)
  17032. (easy-menu-change
  17033. '("Org") "File List for Agenda"
  17034. (append
  17035. (list
  17036. ["Edit File List" (org-edit-agenda-file-list) t]
  17037. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  17038. ["Remove Current File from List" org-remove-file t]
  17039. ["Cycle through agenda files" org-cycle-agenda-files t]
  17040. ["Occur in all agenda files" org-occur-in-agenda-files t]
  17041. "--")
  17042. (mapcar 'org-file-menu-entry
  17043. ;; Prevent initialization from failing.
  17044. (ignore-errors (org-agenda-files t)))))))))
  17045. ;;;; Documentation
  17046. (defun org-require-autoloaded-modules ()
  17047. (interactive)
  17048. (mapc #'require
  17049. '(org-agenda org-archive org-attach org-clock org-colview org-id
  17050. org-table org-timer)))
  17051. ;;;###autoload
  17052. (defun org-reload (&optional uncompiled)
  17053. "Reload all Org Lisp files.
  17054. With prefix arg UNCOMPILED, load the uncompiled versions."
  17055. (interactive "P")
  17056. (require 'loadhist)
  17057. (let* ((org-dir (org-find-library-dir "org"))
  17058. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  17059. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  17060. (remove-re (format "\\`%s\\'"
  17061. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  17062. (feats (delete-dups
  17063. (mapcar 'file-name-sans-extension
  17064. (mapcar 'file-name-nondirectory
  17065. (delq nil
  17066. (mapcar 'feature-file
  17067. features))))))
  17068. (lfeat (append
  17069. (sort
  17070. (setq feats
  17071. (delq nil (mapcar
  17072. (lambda (f)
  17073. (if (and (string-match feature-re f)
  17074. (not (string-match remove-re f)))
  17075. f nil))
  17076. feats)))
  17077. 'string-lessp)
  17078. (list "org-version" "org")))
  17079. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  17080. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  17081. load-uncore load-misses)
  17082. (setq load-misses
  17083. (delq 't
  17084. (mapcar (lambda (f)
  17085. (or (org-load-noerror-mustsuffix (concat org-dir f))
  17086. (and (string= org-dir contrib-dir)
  17087. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  17088. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  17089. (push f load-uncore)
  17090. 't)
  17091. f))
  17092. lfeat)))
  17093. (when load-uncore
  17094. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  17095. (if (> (length load-uncore) 1) "s were" " was")
  17096. (reverse load-uncore)))
  17097. (if load-misses
  17098. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  17099. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  17100. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  17101. ;;;###autoload
  17102. (defun org-customize ()
  17103. "Call the customize function with org as argument."
  17104. (interactive)
  17105. (org-load-modules-maybe)
  17106. (org-require-autoloaded-modules)
  17107. (customize-browse 'org))
  17108. (defun org-create-customize-menu ()
  17109. "Create a full customization menu for Org mode, insert it into the menu."
  17110. (interactive)
  17111. (org-load-modules-maybe)
  17112. (org-require-autoloaded-modules)
  17113. (if (fboundp 'customize-menu-create)
  17114. (progn
  17115. (easy-menu-change
  17116. '("Org") "Customize"
  17117. `(["Browse Org group" org-customize t]
  17118. "--"
  17119. ,(customize-menu-create 'org)
  17120. ["Set" Custom-set t]
  17121. ["Save" Custom-save t]
  17122. ["Reset to Current" Custom-reset-current t]
  17123. ["Reset to Saved" Custom-reset-saved t]
  17124. ["Reset to Standard Settings" Custom-reset-standard t]))
  17125. (message "\"Org\"-menu now contains full customization menu"))
  17126. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  17127. ;;;; Miscellaneous stuff
  17128. ;;; Generally useful functions
  17129. (defun org-in-clocktable-p ()
  17130. "Check if the cursor is in a clocktable."
  17131. (let ((pos (point)) start)
  17132. (save-excursion
  17133. (end-of-line 1)
  17134. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  17135. (setq start (match-beginning 0))
  17136. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  17137. (>= (match-end 0) pos)
  17138. start))))
  17139. (defun org-in-verbatim-emphasis ()
  17140. (save-match-data
  17141. (and (org-in-regexp org-verbatim-re 2)
  17142. (>= (point) (match-beginning 3))
  17143. (<= (point) (match-end 4)))))
  17144. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  17145. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  17146. (if (and marker (marker-buffer marker)
  17147. (buffer-live-p (marker-buffer marker)))
  17148. (progn
  17149. (pop-to-buffer-same-window (marker-buffer marker))
  17150. (when (or (> marker (point-max)) (< marker (point-min)))
  17151. (widen))
  17152. (goto-char marker)
  17153. (org-show-context 'org-goto))
  17154. (if bookmark
  17155. (bookmark-jump bookmark)
  17156. (error "Cannot find location"))))
  17157. (defun org-quote-csv-field (s)
  17158. "Quote field for inclusion in CSV material."
  17159. (if (string-match "[\",]" s)
  17160. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  17161. s))
  17162. (defun org-force-self-insert (N)
  17163. "Needed to enforce self-insert under remapping."
  17164. (interactive "p")
  17165. (self-insert-command N))
  17166. (defun org-quote-vert (s)
  17167. "Replace \"|\" with \"\\vert\"."
  17168. (while (string-match "|" s)
  17169. (setq s (replace-match "\\vert" t t s)))
  17170. s)
  17171. (defun org-uuidgen-p (s)
  17172. "Is S an ID created by UUIDGEN?"
  17173. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  17174. (defun org-in-src-block-p (&optional inside)
  17175. "Whether point is in a code source block.
  17176. When INSIDE is non-nil, don't consider we are within a source
  17177. block when point is at #+BEGIN_SRC or #+END_SRC."
  17178. (let ((case-fold-search t))
  17179. (or (and (eq (get-char-property (point) 'src-block) t))
  17180. (and (not inside)
  17181. (save-match-data
  17182. (save-excursion
  17183. (beginning-of-line)
  17184. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  17185. (defun org-context ()
  17186. "Return a list of contexts of the current cursor position.
  17187. If several contexts apply, all are returned.
  17188. Each context entry is a list with a symbol naming the context, and
  17189. two positions indicating start and end of the context. Possible
  17190. contexts are:
  17191. :headline anywhere in a headline
  17192. :headline-stars on the leading stars in a headline
  17193. :todo-keyword on a TODO keyword (including DONE) in a headline
  17194. :tags on the TAGS in a headline
  17195. :priority on the priority cookie in a headline
  17196. :item on the first line of a plain list item
  17197. :item-bullet on the bullet/number of a plain list item
  17198. :checkbox on the checkbox in a plain list item
  17199. :table in an Org table
  17200. :table-special on a special filed in a table
  17201. :table-table in a table.el table
  17202. :clocktable in a clocktable
  17203. :src-block in a source block
  17204. :link on a hyperlink
  17205. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  17206. :latex-fragment on a LaTeX fragment
  17207. :latex-preview on a LaTeX fragment with overlaid preview image
  17208. This function expects the position to be visible because it uses font-lock
  17209. faces as a help to recognize the following contexts: :table-special, :link,
  17210. and :keyword."
  17211. (let* ((f (get-text-property (point) 'face))
  17212. (faces (if (listp f) f (list f)))
  17213. (case-fold-search t)
  17214. (p (point)) clist o)
  17215. ;; First the large context
  17216. (cond
  17217. ((org-at-heading-p t)
  17218. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  17219. (when (progn
  17220. (beginning-of-line 1)
  17221. (looking-at org-todo-line-tags-regexp))
  17222. (push (org-point-in-group p 1 :headline-stars) clist)
  17223. (push (org-point-in-group p 2 :todo-keyword) clist)
  17224. (push (org-point-in-group p 4 :tags) clist))
  17225. (goto-char p)
  17226. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  17227. (when (looking-at "\\[#[A-Z0-9]\\]")
  17228. (push (org-point-in-group p 0 :priority) clist)))
  17229. ((org-at-item-p)
  17230. (push (org-point-in-group p 2 :item-bullet) clist)
  17231. (push (list :item (point-at-bol)
  17232. (save-excursion (org-end-of-item) (point)))
  17233. clist)
  17234. (and (org-at-item-checkbox-p)
  17235. (push (org-point-in-group p 0 :checkbox) clist)))
  17236. ((org-at-table-p)
  17237. (push (list :table (org-table-begin) (org-table-end)) clist)
  17238. (when (memq 'org-formula faces)
  17239. (push (list :table-special
  17240. (previous-single-property-change p 'face)
  17241. (next-single-property-change p 'face)) clist)))
  17242. ((org-at-table-p 'any)
  17243. (push (list :table-table) clist)))
  17244. (goto-char p)
  17245. (let ((case-fold-search t))
  17246. ;; New the "medium" contexts: clocktables, source blocks
  17247. (cond ((org-in-clocktable-p)
  17248. (push (list :clocktable
  17249. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  17250. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  17251. (match-beginning 1))
  17252. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  17253. (match-end 0))) clist))
  17254. ((org-in-src-block-p)
  17255. (push (list :src-block
  17256. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  17257. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  17258. (match-beginning 1))
  17259. (and (search-forward "#+END_SRC" nil t)
  17260. (match-beginning 0))) clist))))
  17261. (goto-char p)
  17262. ;; Now the small context
  17263. (cond
  17264. ((org-at-timestamp-p)
  17265. (push (org-point-in-group p 0 :timestamp) clist))
  17266. ((memq 'org-link faces)
  17267. (push (list :link
  17268. (previous-single-property-change p 'face)
  17269. (next-single-property-change p 'face)) clist))
  17270. ((memq 'org-special-keyword faces)
  17271. (push (list :keyword
  17272. (previous-single-property-change p 'face)
  17273. (next-single-property-change p 'face)) clist))
  17274. ((setq o (cl-some
  17275. (lambda (o)
  17276. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  17277. o))
  17278. (overlays-at (point))))
  17279. (push (list :latex-fragment
  17280. (overlay-start o) (overlay-end o)) clist)
  17281. (push (list :latex-preview
  17282. (overlay-start o) (overlay-end o)) clist))
  17283. ((org-inside-LaTeX-fragment-p)
  17284. ;; FIXME: positions wrong.
  17285. (push (list :latex-fragment (point) (point)) clist)))
  17286. (setq clist (nreverse (delq nil clist)))
  17287. clist))
  17288. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  17289. "Non-nil when point is between matches of START-RE and END-RE.
  17290. Also return a non-nil value when point is on one of the matches.
  17291. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  17292. buffer positions. Default values are the positions of headlines
  17293. surrounding the point.
  17294. The functions returns a cons cell whose car (resp. cdr) is the
  17295. position before START-RE (resp. after END-RE)."
  17296. (save-match-data
  17297. (let ((pos (point))
  17298. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  17299. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  17300. beg end)
  17301. (save-excursion
  17302. ;; Point is on a block when on START-RE or if START-RE can be
  17303. ;; found before it...
  17304. (and (or (org-in-regexp start-re)
  17305. (re-search-backward start-re limit-up t))
  17306. (setq beg (match-beginning 0))
  17307. ;; ... and END-RE after it...
  17308. (goto-char (match-end 0))
  17309. (re-search-forward end-re limit-down t)
  17310. (> (setq end (match-end 0)) pos)
  17311. ;; ... without another START-RE in-between.
  17312. (goto-char (match-beginning 0))
  17313. (not (re-search-backward start-re (1+ beg) t))
  17314. ;; Return value.
  17315. (cons beg end))))))
  17316. (defun org-in-block-p (names)
  17317. "Non-nil when point belongs to a block whose name belongs to NAMES.
  17318. NAMES is a list of strings containing names of blocks.
  17319. Return first block name matched, or nil. Beware that in case of
  17320. nested blocks, the returned name may not belong to the closest
  17321. block from point."
  17322. (save-match-data
  17323. (catch 'exit
  17324. (let ((case-fold-search t)
  17325. (lim-up (save-excursion (outline-previous-heading)))
  17326. (lim-down (save-excursion (outline-next-heading))))
  17327. (dolist (name names)
  17328. (let ((n (regexp-quote name)))
  17329. (when (org-between-regexps-p
  17330. (concat "^[ \t]*#\\+begin_" n)
  17331. (concat "^[ \t]*#\\+end_" n)
  17332. lim-up lim-down)
  17333. (throw 'exit n)))))
  17334. nil)))
  17335. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  17336. "Call `multi-occur' with buffers for all agenda files."
  17337. (interactive "sOrg-files matching: ")
  17338. (let* ((files (org-agenda-files))
  17339. (tnames (mapcar #'file-truename files))
  17340. (extra org-agenda-text-search-extra-files))
  17341. (when (eq (car extra) 'agenda-archives)
  17342. (setq extra (cdr extra))
  17343. (setq files (org-add-archive-files files)))
  17344. (dolist (f extra)
  17345. (unless (member (file-truename f) tnames)
  17346. (unless (member f files) (setq files (append files (list f))))
  17347. (setq tnames (append tnames (list (file-truename f))))))
  17348. (multi-occur
  17349. (mapcar (lambda (x)
  17350. (with-current-buffer
  17351. ;; FIXME: Why not just (find-file-noselect x)?
  17352. ;; Is it to avoid the "revert buffer" prompt?
  17353. (or (get-file-buffer x) (find-file-noselect x))
  17354. (widen)
  17355. (current-buffer)))
  17356. files)
  17357. regexp)))
  17358. (add-hook 'occur-mode-find-occurrence-hook
  17359. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17360. (defun org-occur-link-in-agenda-files ()
  17361. "Create a link and search for it in the agendas.
  17362. The link is not stored in `org-stored-links', it is just created
  17363. for the search purpose."
  17364. (interactive)
  17365. (let ((link (condition-case nil
  17366. (org-store-link nil)
  17367. (error "Unable to create a link to here"))))
  17368. (org-occur-in-agenda-files (regexp-quote link))))
  17369. (defun org-back-over-empty-lines ()
  17370. "Move backwards over whitespace, to the beginning of the first empty line.
  17371. Returns the number of empty lines passed."
  17372. (let ((pos (point)))
  17373. (if (cdr (assq 'heading org-blank-before-new-entry))
  17374. (skip-chars-backward " \t\n\r")
  17375. (unless (eobp)
  17376. (forward-line -1)))
  17377. (beginning-of-line 2)
  17378. (goto-char (min (point) pos))
  17379. (count-lines (point) pos)))
  17380. ;;; TODO: Only called once, from ox-odt which should probably use
  17381. ;;; org-export-inline-image-p or something.
  17382. (defun org-file-image-p (file)
  17383. "Return non-nil if FILE is an image."
  17384. (save-match-data
  17385. (string-match (image-file-name-regexp) file)))
  17386. (defun org-get-cursor-date (&optional with-time)
  17387. "Return the date at cursor in as a time.
  17388. This works in the calendar and in the agenda, anywhere else it just
  17389. returns the current time.
  17390. If WITH-TIME is non-nil, returns the time of the event at point (in
  17391. the agenda) or the current time of the day; otherwise returns the
  17392. earliest time on the cursor date that Org treats as that date
  17393. (bearing in mind `org-extend-today-until')."
  17394. (let (date day defd tp hod mod)
  17395. (when with-time
  17396. (setq tp (get-text-property (point) 'time))
  17397. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  17398. (setq hod (string-to-number (match-string 1 tp))
  17399. mod (string-to-number (match-string 2 tp))))
  17400. (or tp (let ((now (decode-time)))
  17401. (setq hod (nth 2 now)
  17402. mod (nth 1 now)))))
  17403. (cond
  17404. ((eq major-mode 'calendar-mode)
  17405. (setq date (calendar-cursor-to-date)
  17406. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17407. (nth 1 date) (nth 0 date) (nth 2 date))))
  17408. ((eq major-mode 'org-agenda-mode)
  17409. (setq day (get-text-property (point) 'day))
  17410. (when day
  17411. (setq date (calendar-gregorian-from-absolute day)
  17412. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17413. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17414. (or defd (current-time))))
  17415. (defun org-mark-subtree (&optional up)
  17416. "Mark the current subtree.
  17417. This puts point at the start of the current subtree, and mark at
  17418. the end. If a numeric prefix UP is given, move up into the
  17419. hierarchy of headlines by UP levels before marking the subtree."
  17420. (interactive "P")
  17421. (org-with-limited-levels
  17422. (cond ((org-at-heading-p) (beginning-of-line))
  17423. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17424. (t (outline-previous-visible-heading 1))))
  17425. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17426. (if (called-interactively-p 'any)
  17427. (call-interactively 'org-mark-element)
  17428. (org-mark-element)))
  17429. ;;; Indentation
  17430. (defvar org-element-greater-elements)
  17431. (defun org--get-expected-indentation (element contentsp)
  17432. "Expected indentation column for current line, according to ELEMENT.
  17433. ELEMENT is an element containing point. CONTENTSP is non-nil
  17434. when indentation is to be computed according to contents of
  17435. ELEMENT."
  17436. (let ((type (org-element-type element))
  17437. (start (org-element-property :begin element))
  17438. (post-affiliated (org-element-property :post-affiliated element)))
  17439. (org-with-wide-buffer
  17440. (cond
  17441. (contentsp
  17442. (cl-case type
  17443. ((diary-sexp footnote-definition) 0)
  17444. ((headline inlinetask nil)
  17445. (if (not org-adapt-indentation) 0
  17446. (let ((level (org-current-level)))
  17447. (if level (1+ level) 0))))
  17448. ((item plain-list) (org-list-item-body-column post-affiliated))
  17449. (t
  17450. (goto-char start)
  17451. (current-indentation))))
  17452. ((memq type '(headline inlinetask nil))
  17453. (if (org-match-line "[ \t]*$")
  17454. (org--get-expected-indentation element t)
  17455. 0))
  17456. ((memq type '(diary-sexp footnote-definition)) 0)
  17457. ;; First paragraph of a footnote definition or an item.
  17458. ;; Indent like parent.
  17459. ((< (line-beginning-position) start)
  17460. (org--get-expected-indentation
  17461. (org-element-property :parent element) t))
  17462. ;; At first line: indent according to previous sibling, if any,
  17463. ;; ignoring footnote definitions and inline tasks, or parent's
  17464. ;; contents.
  17465. ((= (line-beginning-position) start)
  17466. (catch 'exit
  17467. (while t
  17468. (if (= (point-min) start) (throw 'exit 0)
  17469. (goto-char (1- start))
  17470. (let* ((previous (org-element-at-point))
  17471. (parent previous))
  17472. (while (and parent (<= (org-element-property :end parent) start))
  17473. (setq previous parent
  17474. parent (org-element-property :parent parent)))
  17475. (cond
  17476. ((not previous) (throw 'exit 0))
  17477. ((> (org-element-property :end previous) start)
  17478. (throw 'exit (org--get-expected-indentation previous t)))
  17479. ((memq (org-element-type previous)
  17480. '(footnote-definition inlinetask))
  17481. (setq start (org-element-property :begin previous)))
  17482. (t (goto-char (org-element-property :begin previous))
  17483. (throw 'exit
  17484. (if (bolp) (current-indentation)
  17485. ;; At first paragraph in an item or
  17486. ;; a footnote definition.
  17487. (org--get-expected-indentation
  17488. (org-element-property :parent previous) t))))))))))
  17489. ;; Otherwise, move to the first non-blank line above.
  17490. (t
  17491. (beginning-of-line)
  17492. (let ((pos (point)))
  17493. (skip-chars-backward " \r\t\n")
  17494. (cond
  17495. ;; Two blank lines end a footnote definition or a plain
  17496. ;; list. When we indent an empty line after them, the
  17497. ;; containing list or footnote definition is over, so it
  17498. ;; qualifies as a previous sibling. Therefore, we indent
  17499. ;; like its first line.
  17500. ((and (memq type '(footnote-definition plain-list))
  17501. (> (count-lines (point) pos) 2))
  17502. (goto-char start)
  17503. (current-indentation))
  17504. ;; Line above is the first one of a paragraph at the
  17505. ;; beginning of an item or a footnote definition. Indent
  17506. ;; like parent.
  17507. ((< (line-beginning-position) start)
  17508. (org--get-expected-indentation
  17509. (org-element-property :parent element) t))
  17510. ;; Line above is the beginning of an element, i.e., point
  17511. ;; was originally on the blank lines between element's start
  17512. ;; and contents.
  17513. ((= (line-beginning-position) post-affiliated)
  17514. (org--get-expected-indentation element t))
  17515. ;; POS is after contents in a greater element. Indent like
  17516. ;; the beginning of the element.
  17517. ((and (memq type org-element-greater-elements)
  17518. (let ((cend (org-element-property :contents-end element)))
  17519. (and cend (<= cend pos))))
  17520. ;; As a special case, if point is at the end of a footnote
  17521. ;; definition or an item, indent like the very last element
  17522. ;; within. If that last element is an item, indent like
  17523. ;; its contents.
  17524. (if (memq type '(footnote-definition item plain-list))
  17525. (let ((last (org-element-at-point)))
  17526. (goto-char pos)
  17527. (org--get-expected-indentation
  17528. last (eq (org-element-type last) 'item)))
  17529. (goto-char start)
  17530. (current-indentation)))
  17531. ;; In any other case, indent like the current line.
  17532. (t (current-indentation)))))))))
  17533. (defun org--align-node-property ()
  17534. "Align node property at point.
  17535. Alignment is done according to `org-property-format', which see."
  17536. (when (save-excursion
  17537. (beginning-of-line)
  17538. (looking-at org-property-re))
  17539. (replace-match
  17540. (concat (match-string 4)
  17541. (org-trim
  17542. (format org-property-format (match-string 1) (match-string 3))))
  17543. t t)))
  17544. (defun org-indent-line ()
  17545. "Indent line depending on context.
  17546. Indentation is done according to the following rules:
  17547. - Footnote definitions, diary sexps, headlines and inline tasks
  17548. have to start at column 0.
  17549. - On the very first line of an element, consider, in order, the
  17550. next rules until one matches:
  17551. 1. If there's a sibling element before, ignoring footnote
  17552. definitions and inline tasks, indent like its first line.
  17553. 2. If element has a parent, indent like its contents. More
  17554. precisely, if parent is an item, indent after the bullet.
  17555. Else, indent like parent's first line.
  17556. 3. Otherwise, indent relatively to current level, if
  17557. `org-adapt-indentation' is non-nil, or to left margin.
  17558. - On a blank line at the end of an element, indent according to
  17559. the type of the element. More precisely
  17560. 1. If element is a plain list, an item, or a footnote
  17561. definition, indent like the very last element within.
  17562. 2. If element is a paragraph, indent like its last non blank
  17563. line.
  17564. 3. Otherwise, indent like its very first line.
  17565. - In the code part of a source block, use language major mode
  17566. to indent current line if `org-src-tab-acts-natively' is
  17567. non-nil. If it is nil, do nothing.
  17568. - Otherwise, indent like the first non-blank line above.
  17569. The function doesn't indent an item as it could break the whole
  17570. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17571. `\\[org-shiftmetaright]'.
  17572. Also align node properties according to `org-property-format'."
  17573. (interactive)
  17574. (cond
  17575. ((org-at-heading-p) 'noindent)
  17576. (t
  17577. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17578. (type (org-element-type element)))
  17579. (cond ((and (memq type '(plain-list item))
  17580. (= (line-beginning-position)
  17581. (org-element-property :post-affiliated element)))
  17582. 'noindent)
  17583. ((and (eq type 'latex-environment)
  17584. (>= (point) (org-element-property :post-affiliated element))
  17585. (< (point) (org-with-wide-buffer
  17586. (goto-char (org-element-property :end element))
  17587. (skip-chars-backward " \r\t\n")
  17588. (line-beginning-position 2))))
  17589. 'noindent)
  17590. ((and (eq type 'src-block)
  17591. org-src-tab-acts-natively
  17592. (> (line-beginning-position)
  17593. (org-element-property :post-affiliated element))
  17594. (< (line-beginning-position)
  17595. (org-with-wide-buffer
  17596. (goto-char (org-element-property :end element))
  17597. (skip-chars-backward " \r\t\n")
  17598. (line-beginning-position))))
  17599. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17600. (t
  17601. (let ((column (org--get-expected-indentation element nil)))
  17602. ;; Preserve current column.
  17603. (if (<= (current-column) (current-indentation))
  17604. (indent-line-to column)
  17605. (save-excursion (indent-line-to column))))
  17606. ;; Align node property. Also preserve current column.
  17607. (when (eq type 'node-property)
  17608. (let ((column (current-column)))
  17609. (org--align-node-property)
  17610. (org-move-to-column column)))))))))
  17611. (defun org-indent-region (start end)
  17612. "Indent each non-blank line in the region.
  17613. Called from a program, START and END specify the region to
  17614. indent. The function will not indent contents of example blocks,
  17615. verse blocks and export blocks as leading white spaces are
  17616. assumed to be significant there."
  17617. (interactive "r")
  17618. (save-excursion
  17619. (goto-char start)
  17620. (skip-chars-forward " \r\t\n")
  17621. (unless (eobp) (beginning-of-line))
  17622. (let ((indent-to
  17623. (lambda (ind pos)
  17624. ;; Set IND as indentation for all lines between point and
  17625. ;; POS. Blank lines are ignored. Leave point after POS
  17626. ;; once done.
  17627. (let ((limit (copy-marker pos)))
  17628. (while (< (point) limit)
  17629. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17630. (forward-line))
  17631. (set-marker limit nil))))
  17632. (end (copy-marker end)))
  17633. (while (< (point) end)
  17634. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17635. (let* ((element (org-element-at-point))
  17636. (type (org-element-type element))
  17637. (element-end (copy-marker (org-element-property :end element)))
  17638. (ind (org--get-expected-indentation element nil)))
  17639. (cond
  17640. ;; Element indented as a single block. Example blocks
  17641. ;; preserving indentation are a special case since the
  17642. ;; "contents" must not be indented whereas the block
  17643. ;; boundaries can.
  17644. ((or (memq type '(export-block latex-environment))
  17645. (and (eq type 'example-block)
  17646. (not
  17647. (or org-src-preserve-indentation
  17648. (org-element-property :preserve-indent element)))))
  17649. (let ((offset (- ind (current-indentation))))
  17650. (unless (zerop offset)
  17651. (indent-rigidly (org-element-property :begin element)
  17652. (org-element-property :end element)
  17653. offset)))
  17654. (goto-char element-end))
  17655. ;; Elements indented line wise. Be sure to exclude
  17656. ;; example blocks (preserving indentation) and source
  17657. ;; blocks from this category as they are treated
  17658. ;; specially later.
  17659. ((or (memq type '(paragraph table table-row))
  17660. (not (or (org-element-property :contents-begin element)
  17661. (memq type '(example-block src-block)))))
  17662. (when (eq type 'node-property)
  17663. (org--align-node-property)
  17664. (beginning-of-line))
  17665. (funcall indent-to ind (min element-end end)))
  17666. ;; Elements consisting of three parts: before the
  17667. ;; contents, the contents, and after the contents. The
  17668. ;; contents are treated specially, according to the
  17669. ;; element type, or not indented at all. Other parts are
  17670. ;; indented as a single block.
  17671. (t
  17672. (let* ((post (copy-marker
  17673. (org-element-property :post-affiliated element)))
  17674. (cbeg
  17675. (copy-marker
  17676. (cond
  17677. ((not (org-element-property :contents-begin element))
  17678. ;; Fake contents for source blocks.
  17679. (org-with-wide-buffer
  17680. (goto-char post)
  17681. (line-beginning-position 2)))
  17682. ((memq type '(footnote-definition item plain-list))
  17683. ;; Contents in these elements could start on
  17684. ;; the same line as the beginning of the
  17685. ;; element. Make sure we start indenting
  17686. ;; from the second line.
  17687. (org-with-wide-buffer
  17688. (goto-char post)
  17689. (end-of-line)
  17690. (skip-chars-forward " \r\t\n")
  17691. (if (eobp) (point) (line-beginning-position))))
  17692. (t (org-element-property :contents-begin element)))))
  17693. (cend (copy-marker
  17694. (or (org-element-property :contents-end element)
  17695. ;; Fake contents for source blocks.
  17696. (org-with-wide-buffer
  17697. (goto-char element-end)
  17698. (skip-chars-backward " \r\t\n")
  17699. (line-beginning-position)))
  17700. t)))
  17701. ;; Do not change items indentation individually as it
  17702. ;; might break the list as a whole. On the other
  17703. ;; hand, when at a plain list, indent it as a whole.
  17704. (cond ((eq type 'plain-list)
  17705. (let ((offset (- ind (current-indentation))))
  17706. (unless (zerop offset)
  17707. (indent-rigidly (org-element-property :begin element)
  17708. (org-element-property :end element)
  17709. offset))
  17710. (goto-char cbeg)))
  17711. ((eq type 'item) (goto-char cbeg))
  17712. (t (funcall indent-to ind (min cbeg end))))
  17713. (when (< (point) end)
  17714. (cl-case type
  17715. ((example-block verse-block))
  17716. (src-block
  17717. ;; In a source block, indent source code
  17718. ;; according to language major mode, but only if
  17719. ;; `org-src-tab-acts-natively' is non-nil.
  17720. (when (and (< (point) end) org-src-tab-acts-natively)
  17721. (ignore-errors
  17722. (org-babel-do-in-edit-buffer
  17723. (indent-region (point-min) (point-max))))))
  17724. (t (org-indent-region (point) (min cend end))))
  17725. (goto-char (min cend end))
  17726. (when (< (point) end)
  17727. (funcall indent-to ind (min element-end end))))
  17728. (set-marker post nil)
  17729. (set-marker cbeg nil)
  17730. (set-marker cend nil))))
  17731. (set-marker element-end nil))))
  17732. (set-marker end nil))))
  17733. (defun org-indent-drawer ()
  17734. "Indent the drawer at point."
  17735. (interactive)
  17736. (unless (save-excursion
  17737. (beginning-of-line)
  17738. (looking-at-p org-drawer-regexp))
  17739. (user-error "Not at a drawer"))
  17740. (let ((element (org-element-at-point)))
  17741. (unless (memq (org-element-type element) '(drawer property-drawer))
  17742. (user-error "Not at a drawer"))
  17743. (org-with-wide-buffer
  17744. (org-indent-region (org-element-property :begin element)
  17745. (org-element-property :end element))))
  17746. (message "Drawer at point indented"))
  17747. (defun org-indent-block ()
  17748. "Indent the block at point."
  17749. (interactive)
  17750. (unless (save-excursion
  17751. (beginning-of-line)
  17752. (let ((case-fold-search t))
  17753. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17754. (user-error "Not at a block"))
  17755. (let ((element (org-element-at-point)))
  17756. (unless (memq (org-element-type element)
  17757. '(comment-block center-block dynamic-block example-block
  17758. export-block quote-block special-block
  17759. src-block verse-block))
  17760. (user-error "Not at a block"))
  17761. (org-with-wide-buffer
  17762. (org-indent-region (org-element-property :begin element)
  17763. (org-element-property :end element))))
  17764. (message "Block at point indented"))
  17765. ;;; Filling
  17766. ;; We use our own fill-paragraph and auto-fill functions.
  17767. ;; `org-fill-paragraph' relies on adaptive filling and context
  17768. ;; checking. Appropriate `fill-prefix' is computed with
  17769. ;; `org-adaptive-fill-function'.
  17770. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17771. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17772. ;; `org-adaptive-fill-function' value. Internally,
  17773. ;; `org-comment-line-break-function' breaks the line.
  17774. ;; `org-setup-filling' installs filling and auto-filling related
  17775. ;; variables during `org-mode' initialization.
  17776. (defun org-setup-filling ()
  17777. (require 'org-element)
  17778. ;; Prevent auto-fill from inserting unwanted new items.
  17779. (when (boundp 'fill-nobreak-predicate)
  17780. (setq-local
  17781. fill-nobreak-predicate
  17782. (org-uniquify
  17783. (append fill-nobreak-predicate
  17784. '(org-fill-line-break-nobreak-p
  17785. org-fill-n-macro-as-item-nobreak-p
  17786. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17787. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17788. (setq-local paragraph-start paragraph-ending)
  17789. (setq-local paragraph-separate paragraph-ending))
  17790. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17791. (setq-local auto-fill-inhibit-regexp nil)
  17792. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17793. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17794. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17795. (defun org-fill-line-break-nobreak-p ()
  17796. "Non-nil when a new line at point would create an Org line break."
  17797. (save-excursion
  17798. (skip-chars-backward " \t")
  17799. (skip-chars-backward "\\\\")
  17800. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17801. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17802. "Non-nil when a new line at point would split a timestamp."
  17803. (and (org-at-timestamp-p 'lax)
  17804. (not (looking-at org-ts-regexp-both))))
  17805. (defun org-fill-n-macro-as-item-nobreak-p ()
  17806. "Non-nil when a new line at point would create a new list."
  17807. ;; During export, a "n" macro followed by a dot or a closing
  17808. ;; parenthesis can end up being parsed as a new list item.
  17809. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17810. (defun org-adaptive-fill-function ()
  17811. "Compute a fill prefix for the current line.
  17812. Return fill prefix, as a string, or nil if current line isn't
  17813. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17814. matches in paragraphs or comments, use it."
  17815. (org-with-wide-buffer
  17816. (unless (org-at-heading-p)
  17817. (let* ((p (line-beginning-position))
  17818. (element (save-excursion
  17819. (beginning-of-line)
  17820. (org-element-at-point)))
  17821. (type (org-element-type element))
  17822. (post-affiliated (org-element-property :post-affiliated element)))
  17823. (unless (< p post-affiliated)
  17824. (cl-case type
  17825. (comment
  17826. (save-excursion
  17827. (beginning-of-line)
  17828. (looking-at "[ \t]*")
  17829. (concat (match-string 0) "# ")))
  17830. (footnote-definition "")
  17831. ((item plain-list)
  17832. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17833. (paragraph
  17834. ;; Fill prefix is usually the same as the current line,
  17835. ;; unless the paragraph is at the beginning of an item.
  17836. (let ((parent (org-element-property :parent element)))
  17837. (save-excursion
  17838. (beginning-of-line)
  17839. (cond ((eq (org-element-type parent) 'item)
  17840. (make-string (org-list-item-body-column
  17841. (org-element-property :begin parent))
  17842. ?\s))
  17843. ((and adaptive-fill-regexp
  17844. ;; Locally disable
  17845. ;; `adaptive-fill-function' to let
  17846. ;; `fill-context-prefix' handle
  17847. ;; `adaptive-fill-regexp' variable.
  17848. (let (adaptive-fill-function)
  17849. (fill-context-prefix
  17850. post-affiliated
  17851. (org-element-property :end element)))))
  17852. ((looking-at "[ \t]+") (match-string 0))
  17853. (t "")))))
  17854. (comment-block
  17855. ;; Only fill contents if P is within block boundaries.
  17856. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17857. (forward-line)
  17858. (point)))
  17859. (cend (save-excursion
  17860. (goto-char (org-element-property :end element))
  17861. (skip-chars-backward " \r\t\n")
  17862. (line-beginning-position))))
  17863. (when (and (>= p cbeg) (< p cend))
  17864. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17865. (match-string 0)
  17866. ""))))))))))
  17867. (defun org-fill-element (&optional justify)
  17868. "Fill element at point, when applicable.
  17869. This function only applies to comment blocks, comments, example
  17870. blocks and paragraphs. Also, as a special case, re-align table
  17871. when point is at one.
  17872. If JUSTIFY is non-nil (interactively, with prefix argument),
  17873. justify as well. If `sentence-end-double-space' is non-nil, then
  17874. period followed by one space does not end a sentence, so don't
  17875. break a line there. The variable `fill-column' controls the
  17876. width for filling.
  17877. For convenience, when point is at a plain list, an item or
  17878. a footnote definition, try to fill the first paragraph within."
  17879. (with-syntax-table org-mode-transpose-word-syntax-table
  17880. ;; Move to end of line in order to get the first paragraph within
  17881. ;; a plain list or a footnote definition.
  17882. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17883. ;; First check if point is in a blank line at the beginning of
  17884. ;; the buffer. In that case, ignore filling.
  17885. (cl-case (org-element-type element)
  17886. ;; Use major mode filling function is source blocks.
  17887. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  17888. ;; Align Org tables, leave table.el tables as-is.
  17889. (table-row (org-table-align) t)
  17890. (table
  17891. (when (eq (org-element-property :type element) 'org)
  17892. (save-excursion
  17893. (goto-char (org-element-property :post-affiliated element))
  17894. (org-table-align)))
  17895. t)
  17896. (paragraph
  17897. ;; Paragraphs may contain `line-break' type objects.
  17898. (let ((beg (max (point-min)
  17899. (org-element-property :contents-begin element)))
  17900. (end (min (point-max)
  17901. (org-element-property :contents-end element))))
  17902. ;; Do nothing if point is at an affiliated keyword.
  17903. (if (< (line-end-position) beg) t
  17904. ;; Fill paragraph, taking line breaks into account.
  17905. (save-excursion
  17906. (goto-char beg)
  17907. (let ((cuts (list beg)))
  17908. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17909. (when (eq 'line-break
  17910. (org-element-type
  17911. (save-excursion (backward-char)
  17912. (org-element-context))))
  17913. (push (point) cuts)))
  17914. (dolist (c (delq end cuts))
  17915. (fill-region-as-paragraph c end justify)
  17916. (setq end c))))
  17917. t)))
  17918. ;; Contents of `comment-block' type elements should be
  17919. ;; filled as plain text, but only if point is within block
  17920. ;; markers.
  17921. (comment-block
  17922. (let* ((case-fold-search t)
  17923. (beg (save-excursion
  17924. (goto-char (org-element-property :begin element))
  17925. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17926. (forward-line)
  17927. (point)))
  17928. (end (save-excursion
  17929. (goto-char (org-element-property :end element))
  17930. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17931. (line-beginning-position))))
  17932. (if (or (< (point) beg) (> (point) end)) t
  17933. (fill-region-as-paragraph
  17934. (save-excursion (end-of-line)
  17935. (re-search-backward "^[ \t]*$" beg 'move)
  17936. (line-beginning-position))
  17937. (save-excursion (beginning-of-line)
  17938. (re-search-forward "^[ \t]*$" end 'move)
  17939. (line-beginning-position))
  17940. justify))))
  17941. ;; Fill comments.
  17942. (comment
  17943. (let ((begin (org-element-property :post-affiliated element))
  17944. (end (org-element-property :end element)))
  17945. (when (and (>= (point) begin) (<= (point) end))
  17946. (let ((begin (save-excursion
  17947. (end-of-line)
  17948. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17949. (progn (forward-line) (point))
  17950. begin)))
  17951. (end (save-excursion
  17952. (end-of-line)
  17953. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17954. (1- (line-beginning-position))
  17955. (skip-chars-backward " \r\t\n")
  17956. (line-end-position)))))
  17957. ;; Do not fill comments when at a blank line.
  17958. (when (> end begin)
  17959. (let ((fill-prefix
  17960. (save-excursion
  17961. (beginning-of-line)
  17962. (looking-at "[ \t]*#")
  17963. (let ((comment-prefix (match-string 0)))
  17964. (goto-char (match-end 0))
  17965. (if (looking-at adaptive-fill-regexp)
  17966. (concat comment-prefix (match-string 0))
  17967. (concat comment-prefix " "))))))
  17968. (save-excursion
  17969. (fill-region-as-paragraph begin end justify))))))
  17970. t))
  17971. ;; Ignore every other element.
  17972. (otherwise t)))))
  17973. (defun org-fill-paragraph (&optional justify region)
  17974. "Fill element at point, when applicable.
  17975. This function only applies to comment blocks, comments, example
  17976. blocks and paragraphs. Also, as a special case, re-align table
  17977. when point is at one.
  17978. For convenience, when point is at a plain list, an item or
  17979. a footnote definition, try to fill the first paragraph within.
  17980. If JUSTIFY is non-nil (interactively, with prefix argument),
  17981. justify as well. If `sentence-end-double-space' is non-nil, then
  17982. period followed by one space does not end a sentence, so don't
  17983. break a line there. The variable `fill-column' controls the
  17984. width for filling.
  17985. The REGION argument is non-nil if called interactively; in that
  17986. case, if Transient Mark mode is enabled and the mark is active,
  17987. fill each of the elements in the active region, instead of just
  17988. filling the current element."
  17989. (interactive (progn
  17990. (barf-if-buffer-read-only)
  17991. (list (when current-prefix-arg 'full) t)))
  17992. (let ((hash (and (not (buffer-modified-p))
  17993. (org-buffer-hash))))
  17994. (cond
  17995. ((and region transient-mark-mode mark-active
  17996. (not (eq (region-beginning) (region-end))))
  17997. (let ((origin (point-marker))
  17998. (start (region-beginning)))
  17999. (unwind-protect
  18000. (progn
  18001. (goto-char (region-end))
  18002. (while (> (point) start)
  18003. (org-backward-paragraph)
  18004. (org-fill-element justify)))
  18005. (goto-char origin)
  18006. (set-marker origin nil))))
  18007. (t (org-fill-element justify)))
  18008. ;; If we didn't change anything in the buffer (and the buffer was
  18009. ;; previously unmodified), then flip the modification status back
  18010. ;; to "unchanged".
  18011. (when (and hash (equal hash (org-buffer-hash)))
  18012. (set-buffer-modified-p nil))))
  18013. (defun org-auto-fill-function ()
  18014. "Auto-fill function."
  18015. ;; Check if auto-filling is meaningful.
  18016. (let ((fc (current-fill-column)))
  18017. (when (and fc (> (current-column) fc))
  18018. (let* ((fill-prefix (org-adaptive-fill-function))
  18019. ;; Enforce empty fill prefix, if required. Otherwise, it
  18020. ;; will be computed again.
  18021. (adaptive-fill-mode (not (equal fill-prefix ""))))
  18022. (when fill-prefix (do-auto-fill))))))
  18023. (defun org-comment-line-break-function (&optional soft)
  18024. "Break line at point and indent, continuing comment if within one.
  18025. The inserted newline is marked hard if variable
  18026. `use-hard-newlines' is true, unless optional argument SOFT is
  18027. non-nil."
  18028. (if soft (insert-and-inherit ?\n) (newline 1))
  18029. (save-excursion (forward-char -1) (delete-horizontal-space))
  18030. (delete-horizontal-space)
  18031. (indent-to-left-margin)
  18032. (insert-before-markers-and-inherit fill-prefix))
  18033. ;;; Fixed Width Areas
  18034. (defun org-toggle-fixed-width ()
  18035. "Toggle fixed-width markup.
  18036. Add or remove fixed-width markup on current line, whenever it
  18037. makes sense. Return an error otherwise.
  18038. If a region is active and if it contains only fixed-width areas
  18039. or blank lines, remove all fixed-width markup in it. If the
  18040. region contains anything else, convert all non-fixed-width lines
  18041. to fixed-width ones.
  18042. Blank lines at the end of the region are ignored unless the
  18043. region only contains such lines."
  18044. (interactive)
  18045. (if (not (org-region-active-p))
  18046. ;; No region:
  18047. ;;
  18048. ;; Remove fixed width marker only in a fixed-with element.
  18049. ;;
  18050. ;; Add fixed width maker in paragraphs, in blank lines after
  18051. ;; elements or at the beginning of a headline or an inlinetask,
  18052. ;; and before any one-line elements (e.g., a clock).
  18053. (progn
  18054. (beginning-of-line)
  18055. (let* ((element (org-element-at-point))
  18056. (type (org-element-type element)))
  18057. (cond
  18058. ((and (eq type 'fixed-width)
  18059. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  18060. (replace-match
  18061. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  18062. ((and (memq type '(babel-call clock comment diary-sexp headline
  18063. horizontal-rule keyword paragraph
  18064. planning))
  18065. (<= (org-element-property :post-affiliated element) (point)))
  18066. (skip-chars-forward " \t")
  18067. (insert ": "))
  18068. ((and (looking-at-p "[ \t]*$")
  18069. (or (eq type 'inlinetask)
  18070. (save-excursion
  18071. (skip-chars-forward " \r\t\n")
  18072. (<= (org-element-property :end element) (point)))))
  18073. (delete-region (point) (line-end-position))
  18074. (org-indent-line)
  18075. (insert ": "))
  18076. (t (user-error "Cannot insert a fixed-width line here")))))
  18077. ;; Region active.
  18078. (let* ((begin (save-excursion
  18079. (goto-char (region-beginning))
  18080. (line-beginning-position)))
  18081. (end (copy-marker
  18082. (save-excursion
  18083. (goto-char (region-end))
  18084. (unless (eolp) (beginning-of-line))
  18085. (if (save-excursion (re-search-backward "\\S-" begin t))
  18086. (progn (skip-chars-backward " \r\t\n") (point))
  18087. (point)))))
  18088. (all-fixed-width-p
  18089. (catch 'not-all-p
  18090. (save-excursion
  18091. (goto-char begin)
  18092. (skip-chars-forward " \r\t\n")
  18093. (when (eobp) (throw 'not-all-p nil))
  18094. (while (< (point) end)
  18095. (let ((element (org-element-at-point)))
  18096. (if (eq (org-element-type element) 'fixed-width)
  18097. (goto-char (org-element-property :end element))
  18098. (throw 'not-all-p nil))))
  18099. t))))
  18100. (if all-fixed-width-p
  18101. (save-excursion
  18102. (goto-char begin)
  18103. (while (< (point) end)
  18104. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  18105. (replace-match
  18106. "" nil nil nil
  18107. (if (= (line-end-position) (match-end 0)) 0 1)))
  18108. (forward-line)))
  18109. (let ((min-ind (point-max)))
  18110. ;; Find minimum indentation across all lines.
  18111. (save-excursion
  18112. (goto-char begin)
  18113. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  18114. (setq min-ind 0)
  18115. (catch 'zerop
  18116. (while (< (point) end)
  18117. (unless (looking-at-p "[ \t]*$")
  18118. (let ((ind (current-indentation)))
  18119. (setq min-ind (min min-ind ind))
  18120. (when (zerop ind) (throw 'zerop t))))
  18121. (forward-line)))))
  18122. ;; Loop over all lines and add fixed-width markup everywhere
  18123. ;; but in fixed-width lines.
  18124. (save-excursion
  18125. (goto-char begin)
  18126. (while (< (point) end)
  18127. (cond
  18128. ((org-at-heading-p)
  18129. (insert ": ")
  18130. (forward-line)
  18131. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  18132. (insert ":")
  18133. (forward-line)))
  18134. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  18135. (let* ((element (org-element-at-point))
  18136. (element-end (org-element-property :end element)))
  18137. (if (eq (org-element-type element) 'fixed-width)
  18138. (progn (goto-char element-end)
  18139. (skip-chars-backward " \r\t\n")
  18140. (forward-line))
  18141. (let ((limit (min end element-end)))
  18142. (while (< (point) limit)
  18143. (org-move-to-column min-ind t)
  18144. (insert ": ")
  18145. (forward-line))))))
  18146. (t
  18147. (org-move-to-column min-ind t)
  18148. (insert ": ")
  18149. (forward-line)))))))
  18150. (set-marker end nil))))
  18151. ;;; Blocks
  18152. (defun org-block-map (function &optional start end)
  18153. "Call FUNCTION at the head of all source blocks in the current buffer.
  18154. Optional arguments START and END can be used to limit the range."
  18155. (let ((start (or start (point-min)))
  18156. (end (or end (point-max))))
  18157. (save-excursion
  18158. (goto-char start)
  18159. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  18160. (save-excursion
  18161. (save-match-data
  18162. (goto-char (match-beginning 0))
  18163. (funcall function)))))))
  18164. (defun org-next-block (arg &optional backward block-regexp)
  18165. "Jump to the next block.
  18166. With a prefix argument ARG, jump forward ARG many blocks.
  18167. When BACKWARD is non-nil, jump to the previous block.
  18168. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  18169. Match data is set according to this regexp when the function
  18170. returns.
  18171. Return point at beginning of the opening line of found block.
  18172. Throw an error if no block is found."
  18173. (interactive "p")
  18174. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  18175. (case-fold-search t)
  18176. (search-fn (if backward #'re-search-backward #'re-search-forward))
  18177. (count (or arg 1))
  18178. (origin (point))
  18179. last-element)
  18180. (if backward (beginning-of-line) (end-of-line))
  18181. (while (and (> count 0) (funcall search-fn re nil t))
  18182. (let ((element (save-excursion
  18183. (goto-char (match-beginning 0))
  18184. (save-match-data (org-element-at-point)))))
  18185. (when (and (memq (org-element-type element)
  18186. '(center-block comment-block dynamic-block
  18187. example-block export-block quote-block
  18188. special-block src-block verse-block))
  18189. (<= (match-beginning 0)
  18190. (org-element-property :post-affiliated element)))
  18191. (setq last-element element)
  18192. (cl-decf count))))
  18193. (if (= count 0)
  18194. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  18195. (save-match-data (org-show-context)))
  18196. (goto-char origin)
  18197. (user-error "No %s code blocks" (if backward "previous" "further")))))
  18198. (defun org-previous-block (arg &optional block-regexp)
  18199. "Jump to the previous block.
  18200. With a prefix argument ARG, jump backward ARG many source blocks.
  18201. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  18202. (interactive "p")
  18203. (org-next-block arg t block-regexp))
  18204. ;;; Comments
  18205. ;; Org comments syntax is quite complex. It requires the entire line
  18206. ;; to be just a comment. Also, even with the right syntax at the
  18207. ;; beginning of line, some elements (e.g., verse-block or
  18208. ;; example-block) don't accept comments. Usual Emacs comment commands
  18209. ;; cannot cope with those requirements. Therefore, Org replaces them.
  18210. ;; Org still relies on `comment-dwim', but cannot trust
  18211. ;; `comment-only-p'. So, `comment-region-function' and
  18212. ;; `uncomment-region-function' both point
  18213. ;; to`org-comment-or-uncomment-region'. Eventually,
  18214. ;; `org-insert-comment' takes care of insertion of comments at the
  18215. ;; beginning of line.
  18216. ;; `org-setup-comments-handling' install comments related variables
  18217. ;; during `org-mode' initialization.
  18218. (defun org-setup-comments-handling ()
  18219. (interactive)
  18220. (setq-local comment-use-syntax nil)
  18221. (setq-local comment-start "# ")
  18222. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  18223. (setq-local comment-insert-comment-function 'org-insert-comment)
  18224. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  18225. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  18226. (defun org-insert-comment ()
  18227. "Insert an empty comment above current line.
  18228. If the line is empty, insert comment at its beginning. When
  18229. point is within a source block, comment according to the related
  18230. major mode."
  18231. (if (let ((element (org-element-at-point)))
  18232. (and (eq (org-element-type element) 'src-block)
  18233. (< (save-excursion
  18234. (goto-char (org-element-property :post-affiliated element))
  18235. (line-end-position))
  18236. (point))
  18237. (> (save-excursion
  18238. (goto-char (org-element-property :end element))
  18239. (skip-chars-backward " \r\t\n")
  18240. (line-beginning-position))
  18241. (point))))
  18242. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  18243. (beginning-of-line)
  18244. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  18245. (open-line 1))
  18246. (org-indent-line)
  18247. (insert "# ")))
  18248. (defvar comment-empty-lines) ; From newcomment.el.
  18249. (defun org-comment-or-uncomment-region (beg end &rest _)
  18250. "Comment or uncomment each non-blank line in the region.
  18251. Uncomment each non-blank line between BEG and END if it only
  18252. contains commented lines. Otherwise, comment them. If region is
  18253. strictly within a source block, use appropriate comment syntax."
  18254. (if (let ((element (org-element-at-point)))
  18255. (and (eq (org-element-type element) 'src-block)
  18256. (< (save-excursion
  18257. (goto-char (org-element-property :post-affiliated element))
  18258. (line-end-position))
  18259. beg)
  18260. (>= (save-excursion
  18261. (goto-char (org-element-property :end element))
  18262. (skip-chars-backward " \r\t\n")
  18263. (line-beginning-position))
  18264. end)))
  18265. ;; Translate region boundaries for the Org buffer to the source
  18266. ;; buffer.
  18267. (let ((offset (- end beg)))
  18268. (save-excursion
  18269. (goto-char beg)
  18270. (org-babel-do-in-edit-buffer
  18271. (comment-or-uncomment-region (point) (+ offset (point))))))
  18272. (save-restriction
  18273. ;; Restrict region
  18274. (narrow-to-region (save-excursion (goto-char beg)
  18275. (skip-chars-forward " \r\t\n" end)
  18276. (line-beginning-position))
  18277. (save-excursion (goto-char end)
  18278. (skip-chars-backward " \r\t\n" beg)
  18279. (line-end-position)))
  18280. (let ((uncommentp
  18281. ;; UNCOMMENTP is non-nil when every non blank line between
  18282. ;; BEG and END is a comment.
  18283. (save-excursion
  18284. (goto-char (point-min))
  18285. (while (and (not (eobp))
  18286. (let ((element (org-element-at-point)))
  18287. (and (eq (org-element-type element) 'comment)
  18288. (goto-char (min (point-max)
  18289. (org-element-property
  18290. :end element)))))))
  18291. (eobp))))
  18292. (if uncommentp
  18293. ;; Only blank lines and comments in region: uncomment it.
  18294. (save-excursion
  18295. (goto-char (point-min))
  18296. (while (not (eobp))
  18297. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  18298. (replace-match "" nil nil nil 1))
  18299. (forward-line)))
  18300. ;; Comment each line in region.
  18301. (let ((min-indent (point-max)))
  18302. ;; First find the minimum indentation across all lines.
  18303. (save-excursion
  18304. (goto-char (point-min))
  18305. (while (and (not (eobp)) (not (zerop min-indent)))
  18306. (unless (looking-at "[ \t]*$")
  18307. (setq min-indent (min min-indent (current-indentation))))
  18308. (forward-line)))
  18309. ;; Then loop over all lines.
  18310. (save-excursion
  18311. (goto-char (point-min))
  18312. (while (not (eobp))
  18313. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18314. ;; Don't get fooled by invisible text (e.g. link path)
  18315. ;; when moving to column MIN-INDENT.
  18316. (let ((buffer-invisibility-spec nil))
  18317. (org-move-to-column min-indent t))
  18318. (insert comment-start))
  18319. (forward-line)))))))))
  18320. (defun org-comment-dwim (_arg)
  18321. "Call the comment command you mean.
  18322. Call `org-toggle-comment' if on a heading, otherwise call
  18323. `comment-dwim', within a source edit buffer if needed."
  18324. (interactive "*P")
  18325. (cond ((org-at-heading-p)
  18326. (call-interactively #'org-toggle-comment))
  18327. ((org-in-src-block-p)
  18328. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18329. (t (call-interactively #'comment-dwim))))
  18330. ;;; Timestamps API
  18331. ;; This section contains tools to operate on, or create, timestamp
  18332. ;; objects, as returned by, e.g. `org-element-context'.
  18333. (defun org-timestamp-from-string (s)
  18334. "Convert Org timestamp S, as a string, into a timestamp object.
  18335. Return nil if S is not a valid timestamp string."
  18336. (when (org-string-nw-p s)
  18337. (with-temp-buffer
  18338. (save-excursion (insert s))
  18339. (org-element-timestamp-parser))))
  18340. (defun org-timestamp-from-time (time &optional with-time inactive)
  18341. "Convert a time value into a timestamp object.
  18342. TIME is an Emacs internal time representation, as returned, e.g.,
  18343. by `current-time'.
  18344. When optional argument WITH-TIME is non-nil, return a timestamp
  18345. object with a time part, i.e., with hours and minutes.
  18346. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18347. return an active timestamp."
  18348. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18349. (org-element-create 'timestamp
  18350. (list :type (if inactive 'inactive 'active)
  18351. :year-start year
  18352. :month-start month
  18353. :day-start day
  18354. :hour-start (and with-time hour)
  18355. :minute-start (and with-time minute)))))
  18356. (defun org-timestamp-to-time (timestamp &optional end)
  18357. "Convert TIMESTAMP object into an Emacs internal time value.
  18358. Use end of date range or time range when END is non-nil.
  18359. Otherwise, use its start."
  18360. (apply #'encode-time 0
  18361. (mapcar
  18362. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18363. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18364. '(:minute-start :hour-start :day-start :month-start
  18365. :year-start)))))
  18366. (defun org-timestamp-has-time-p (timestamp)
  18367. "Non-nil when TIMESTAMP has a time specified."
  18368. (org-element-property :hour-start timestamp))
  18369. (defun org-timestamp-format (timestamp format &optional end utc)
  18370. "Format a TIMESTAMP object into a string.
  18371. FORMAT is a format specifier to be passed to
  18372. `format-time-string'.
  18373. When optional argument END is non-nil, use end of date-range or
  18374. time-range, if possible.
  18375. When optional argument UTC is non-nil, time is be expressed as
  18376. Universal Time."
  18377. (format-time-string format (org-timestamp-to-time timestamp end)
  18378. (and utc t)))
  18379. (defun org-timestamp-split-range (timestamp &optional end)
  18380. "Extract a TIMESTAMP object from a date or time range.
  18381. END, when non-nil, means extract the end of the range.
  18382. Otherwise, extract its start.
  18383. Return a new timestamp object."
  18384. (let ((type (org-element-property :type timestamp)))
  18385. (if (memq type '(active inactive diary)) timestamp
  18386. (let ((split-ts (org-element-copy timestamp)))
  18387. ;; Set new type.
  18388. (org-element-put-property
  18389. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18390. ;; Copy start properties over end properties if END is
  18391. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18392. (let ((p-alist '((:minute-start . :minute-end)
  18393. (:hour-start . :hour-end)
  18394. (:day-start . :day-end)
  18395. (:month-start . :month-end)
  18396. (:year-start . :year-end))))
  18397. (dolist (p-cell p-alist)
  18398. (org-element-put-property
  18399. split-ts
  18400. (funcall (if end #'car #'cdr) p-cell)
  18401. (org-element-property
  18402. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18403. ;; Eventually refresh `:raw-value'.
  18404. (org-element-put-property split-ts :raw-value nil)
  18405. (org-element-put-property
  18406. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18407. (defun org-timestamp-translate (timestamp &optional boundary)
  18408. "Translate TIMESTAMP object to custom format.
  18409. Format string is defined in `org-time-stamp-custom-formats',
  18410. which see.
  18411. When optional argument BOUNDARY is non-nil, it is either the
  18412. symbol `start' or `end'. In this case, only translate the
  18413. starting or ending part of TIMESTAMP if it is a date or time
  18414. range. Otherwise, translate both parts.
  18415. Return timestamp as-is if `org-display-custom-times' is nil or if
  18416. it has a `diary' type."
  18417. (let ((type (org-element-property :type timestamp)))
  18418. (if (or (not org-display-custom-times) (eq type 'diary))
  18419. (org-element-interpret-data timestamp)
  18420. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18421. org-time-stamp-custom-formats)))
  18422. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18423. (concat (org-timestamp-format timestamp fmt)
  18424. "--"
  18425. (org-timestamp-format timestamp fmt t))
  18426. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18427. ;;; Other stuff
  18428. (defvar reftex-docstruct-symbol)
  18429. (defvar org--rds)
  18430. (defun org-reftex-citation ()
  18431. "Use reftex-citation to insert a citation into the buffer.
  18432. This looks for a line like
  18433. #+BIBLIOGRAPHY: foo plain option:-d
  18434. and derives from it that foo.bib is the bibliography file relevant
  18435. for this document. It then installs the necessary environment for RefTeX
  18436. to work in this buffer and calls `reftex-citation' to insert a citation
  18437. into the buffer.
  18438. Export of such citations to both LaTeX and HTML is handled by the contributed
  18439. package ox-bibtex by Taru Karttunen."
  18440. (interactive)
  18441. (let ((reftex-docstruct-symbol 'org--rds)
  18442. org--rds bib)
  18443. (org-with-wide-buffer
  18444. (let ((case-fold-search t)
  18445. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18446. (if (not (save-excursion
  18447. (or (re-search-forward re nil t)
  18448. (re-search-backward re nil t))))
  18449. (user-error "No bibliography defined in file")
  18450. (setq bib (concat (match-string 1) ".bib")
  18451. org--rds (list (list 'bib bib))))))
  18452. (call-interactively 'reftex-citation)))
  18453. ;;;; Functions extending outline functionality
  18454. (defun org-beginning-of-line (&optional n)
  18455. "Go to the beginning of the current visible line.
  18456. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18457. symbol `reversed', on the first attempt move to where the
  18458. headline text starts, and only move to beginning of line when the
  18459. cursor is already before the start of the text of the headline.
  18460. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18461. start of the text on the second attempt.
  18462. With argument N not nil or 1, move forward N - 1 lines first."
  18463. (interactive "^p")
  18464. (let ((origin (point))
  18465. (special (pcase org-special-ctrl-a/e
  18466. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18467. deactivate-mark)
  18468. ;; First move to a visible line.
  18469. (if (bound-and-true-p visual-line-mode)
  18470. (beginning-of-visual-line n)
  18471. (move-beginning-of-line n)
  18472. ;; `move-beginning-of-line' may leave point after invisible
  18473. ;; characters if line starts with such of these (e.g., with
  18474. ;; a link at column 0). Really move to the beginning of the
  18475. ;; current visible line.
  18476. (beginning-of-line))
  18477. (cond
  18478. ;; No special behavior. Point is already at the beginning of
  18479. ;; a line, logical or visual.
  18480. ((not special))
  18481. ;; `beginning-of-visual-line' left point before logical beginning
  18482. ;; of line: point is at the beginning of a visual line. Bail
  18483. ;; out.
  18484. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18485. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18486. ;; At a headline, special position is before the title, but
  18487. ;; after any TODO keyword or priority cookie.
  18488. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18489. (line-end-position)))
  18490. (bol (point)))
  18491. (if (eq special 'reversed)
  18492. (when (and (= origin bol) (eq last-command this-command))
  18493. (goto-char refpos))
  18494. (when (or (> origin refpos) (= origin bol))
  18495. (goto-char refpos)))))
  18496. ((and (looking-at org-list-full-item-re)
  18497. (memq (org-element-type (save-match-data (org-element-at-point)))
  18498. '(item plain-list)))
  18499. ;; Set special position at first white space character after
  18500. ;; bullet, and check-box, if any.
  18501. (let ((after-bullet
  18502. (let ((box (match-end 3)))
  18503. (cond ((not box) (match-end 1))
  18504. ((eq (char-after box) ?\s) (1+ box))
  18505. (t box)))))
  18506. (if (eq special 'reversed)
  18507. (when (and (= (point) origin) (eq last-command this-command))
  18508. (goto-char after-bullet))
  18509. (when (or (> origin after-bullet) (= (point) origin))
  18510. (goto-char after-bullet)))))
  18511. ;; No special context. Point is already at beginning of line.
  18512. (t nil))))
  18513. (defun org-end-of-line (&optional n)
  18514. "Go to the end of the line, but before ellipsis, if any.
  18515. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18516. symbol `reversed', ignore tags on the first attempt, and only
  18517. move to after the tags when the cursor is already beyond the end
  18518. of the headline.
  18519. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18520. on the second attempt.
  18521. With argument N not nil or 1, move forward N - 1 lines first."
  18522. (interactive "^p")
  18523. (let ((origin (point))
  18524. (special (pcase org-special-ctrl-a/e
  18525. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18526. deactivate-mark)
  18527. ;; First move to a visible line.
  18528. (if (bound-and-true-p visual-line-mode)
  18529. (beginning-of-visual-line n)
  18530. (move-beginning-of-line n))
  18531. (cond
  18532. ;; At a headline, with tags.
  18533. ((and special
  18534. (save-excursion
  18535. (beginning-of-line)
  18536. (let ((case-fold-search nil))
  18537. (looking-at org-complex-heading-regexp)))
  18538. (match-end 5))
  18539. (let ((tags (save-excursion
  18540. (goto-char (match-beginning 5))
  18541. (skip-chars-backward " \t")
  18542. (point)))
  18543. (visual-end (and (bound-and-true-p visual-line-mode)
  18544. (save-excursion
  18545. (end-of-visual-line)
  18546. (point)))))
  18547. ;; If `end-of-visual-line' brings us before end of line or
  18548. ;; even tags, i.e., the headline spans over multiple visual
  18549. ;; lines, move there.
  18550. (cond ((and visual-end
  18551. (< visual-end tags)
  18552. (<= origin visual-end))
  18553. (goto-char visual-end))
  18554. ((eq special 'reversed)
  18555. (if (and (= origin (line-end-position))
  18556. (eq this-command last-command))
  18557. (goto-char tags)
  18558. (end-of-line)))
  18559. (t
  18560. (if (or (< origin tags) (= origin (line-end-position)))
  18561. (goto-char tags)
  18562. (end-of-line))))))
  18563. ((bound-and-true-p visual-line-mode)
  18564. (let ((bol (line-beginning-position)))
  18565. (end-of-visual-line)
  18566. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18567. ;; end of a line, backtrack and use `end-of-line' instead.
  18568. (when (/= bol (line-beginning-position))
  18569. (goto-char bol)
  18570. (end-of-line))))
  18571. (t (end-of-line)))))
  18572. (defun org-backward-sentence (&optional _arg)
  18573. "Go to beginning of sentence, or beginning of table field.
  18574. This will call `backward-sentence' or `org-table-beginning-of-field',
  18575. depending on context."
  18576. (interactive)
  18577. (let* ((element (org-element-at-point))
  18578. (contents-begin (org-element-property :contents-begin element))
  18579. (table (org-element-lineage element '(table) t)))
  18580. (if (and table
  18581. (> (point) contents-begin)
  18582. (<= (point) (org-element-property :contents-end table)))
  18583. (call-interactively #'org-table-beginning-of-field)
  18584. (save-restriction
  18585. (when (and contents-begin
  18586. (< (point-min) contents-begin)
  18587. (> (point) contents-begin))
  18588. (narrow-to-region contents-begin
  18589. (org-element-property :contents-end element)))
  18590. (call-interactively #'backward-sentence)))))
  18591. (defun org-forward-sentence (&optional _arg)
  18592. "Go to end of sentence, or end of table field.
  18593. This will call `forward-sentence' or `org-table-end-of-field',
  18594. depending on context."
  18595. (interactive)
  18596. (if (and (org-at-heading-p)
  18597. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18598. (save-restriction
  18599. (narrow-to-region (line-beginning-position) (line-end-position))
  18600. (call-interactively #'forward-sentence))
  18601. (let* ((element (org-element-at-point))
  18602. (contents-end (org-element-property :contents-end element))
  18603. (table (org-element-lineage element '(table) t)))
  18604. (if (and table
  18605. (>= (point) (org-element-property :contents-begin table))
  18606. (< (point) contents-end))
  18607. (call-interactively #'org-table-end-of-field)
  18608. (save-restriction
  18609. (when (and contents-end
  18610. (> (point-max) contents-end)
  18611. ;; Skip blank lines between elements.
  18612. (< (org-element-property :end element)
  18613. (save-excursion (goto-char contents-end)
  18614. (skip-chars-forward " \r\t\n"))))
  18615. (narrow-to-region (org-element-property :contents-begin element)
  18616. contents-end))
  18617. ;; End of heading is considered as the end of a sentence.
  18618. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18619. (call-interactively #'forward-sentence)))))))
  18620. (defun org-kill-line (&optional _arg)
  18621. "Kill line, to tags or end of line."
  18622. (interactive)
  18623. (cond
  18624. ((or (not org-special-ctrl-k)
  18625. (bolp)
  18626. (not (org-at-heading-p)))
  18627. (when (and (get-char-property (line-end-position) 'invisible)
  18628. org-ctrl-k-protect-subtree
  18629. (or (eq org-ctrl-k-protect-subtree 'error)
  18630. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18631. (user-error
  18632. (substitute-command-keys
  18633. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18634. (call-interactively
  18635. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18636. ((org-match-line org-tag-line-re)
  18637. (let ((end (save-excursion
  18638. (goto-char (match-beginning 1))
  18639. (skip-chars-backward " \t")
  18640. (point))))
  18641. (if (<= end (point)) ;on tags part
  18642. (kill-region (point) (line-end-position))
  18643. (kill-region (point) end)))
  18644. (org-align-tags))
  18645. (t (kill-region (point) (line-end-position)))))
  18646. (defun org-yank (&optional arg)
  18647. "Yank. If the kill is a subtree, treat it specially.
  18648. This command will look at the current kill and check if is a single
  18649. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18650. cursor is at the beginning of a line or after the stars of a currently
  18651. empty headline, then the yank is handled specially. How exactly depends
  18652. on the value of the following variables.
  18653. `org-yank-folded-subtrees'
  18654. By default, this variable is non-nil, which results in
  18655. subtree(s) being folded after insertion, except if doing so
  18656. would swallow text after the yanked text.
  18657. `org-yank-adjusted-subtrees'
  18658. When non-nil (the default value is nil), the subtree will be
  18659. promoted or demoted in order to fit into the local outline tree
  18660. structure, which means that the level will be adjusted so that it
  18661. becomes the smaller one of the two *visible* surrounding headings.
  18662. Any prefix to this command will cause `yank' to be called directly with
  18663. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18664. will just
  18665. plainly yank the text as it is.
  18666. \[1] The test checks if the first non-white line is a heading
  18667. and if there are no other headings with fewer stars."
  18668. (interactive "P")
  18669. (org-yank-generic 'yank arg))
  18670. (defun org-yank-generic (command arg)
  18671. "Perform some yank-like command.
  18672. This function implements the behavior described in the `org-yank'
  18673. documentation. However, it has been generalized to work for any
  18674. interactive command with similar behavior."
  18675. ;; pretend to be command COMMAND
  18676. (setq this-command command)
  18677. (if arg
  18678. (call-interactively command)
  18679. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18680. (and (org-kill-is-subtree-p)
  18681. (or (bolp)
  18682. (and (looking-at "[ \t]*$")
  18683. (string-match
  18684. "\\`\\*+\\'"
  18685. (buffer-substring (point-at-bol) (point)))))))
  18686. swallowp)
  18687. (cond
  18688. ((and subtreep org-yank-folded-subtrees)
  18689. (let ((beg (point))
  18690. end)
  18691. (if (and subtreep org-yank-adjusted-subtrees)
  18692. (org-paste-subtree nil nil 'for-yank)
  18693. (call-interactively command))
  18694. (setq end (point))
  18695. (goto-char beg)
  18696. (when (and (bolp) subtreep
  18697. (not (setq swallowp
  18698. (org-yank-folding-would-swallow-text beg end))))
  18699. (org-with-limited-levels
  18700. (or (looking-at org-outline-regexp)
  18701. (re-search-forward org-outline-regexp-bol end t))
  18702. (while (and (< (point) end) (looking-at org-outline-regexp))
  18703. (org-flag-subtree t)
  18704. (org-cycle-show-empty-lines 'folded)
  18705. (condition-case nil
  18706. (outline-forward-same-level 1)
  18707. (error (goto-char end))))))
  18708. (when swallowp
  18709. (message
  18710. "Inserted text not folded because that would swallow text"))
  18711. (goto-char end)
  18712. (skip-chars-forward " \t\n\r")
  18713. (beginning-of-line 1)
  18714. (push-mark beg 'nomsg)))
  18715. ((and subtreep org-yank-adjusted-subtrees)
  18716. (let ((beg (point-at-bol)))
  18717. (org-paste-subtree nil nil 'for-yank)
  18718. (push-mark beg 'nomsg)))
  18719. (t
  18720. (call-interactively command))))))
  18721. (defun org-yank-folding-would-swallow-text (beg end)
  18722. "Would hide-subtree at BEG swallow any text after END?"
  18723. (let (level)
  18724. (org-with-limited-levels
  18725. (save-excursion
  18726. (goto-char beg)
  18727. (when (or (looking-at org-outline-regexp)
  18728. (re-search-forward org-outline-regexp-bol end t))
  18729. (setq level (org-outline-level)))
  18730. (goto-char end)
  18731. (skip-chars-forward " \t\r\n\v\f")
  18732. (not (or (eobp)
  18733. (and (bolp) (looking-at-p org-outline-regexp)
  18734. (<= (org-outline-level) level))))))))
  18735. (defun org-back-to-heading (&optional invisible-ok)
  18736. "Call `outline-back-to-heading', but provide a better error message."
  18737. (condition-case nil
  18738. (outline-back-to-heading invisible-ok)
  18739. (error (error "Before first headline at position %d in buffer %s"
  18740. (point) (current-buffer)))))
  18741. (defun org-before-first-heading-p ()
  18742. "Before first heading?"
  18743. (org-with-limited-levels
  18744. (save-excursion
  18745. (end-of-line)
  18746. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18747. (defun org-at-heading-p (&optional _)
  18748. "Non-nil when on a headline."
  18749. (outline-on-heading-p t))
  18750. (defun org-in-commented-heading-p (&optional no-inheritance)
  18751. "Non-nil if point is under a commented heading.
  18752. This function also checks ancestors of the current headline,
  18753. unless optional argument NO-INHERITANCE is non-nil."
  18754. (cond
  18755. ((org-before-first-heading-p) nil)
  18756. ((let ((headline (nth 4 (org-heading-components))))
  18757. (and headline
  18758. (let ((case-fold-search nil))
  18759. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18760. headline)))))
  18761. (no-inheritance nil)
  18762. (t
  18763. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18764. (defun org-at-comment-p nil
  18765. "Return t if cursor is in a commented line."
  18766. (save-excursion
  18767. (save-match-data
  18768. (beginning-of-line)
  18769. (looking-at "^[ \t]*# "))))
  18770. (defun org-at-drawer-p nil
  18771. "Return t if cursor is at a drawer keyword."
  18772. (save-excursion
  18773. (move-beginning-of-line 1)
  18774. (looking-at org-drawer-regexp)))
  18775. (defun org-at-block-p nil
  18776. "Return t if cursor is at a block keyword."
  18777. (save-excursion
  18778. (move-beginning-of-line 1)
  18779. (looking-at org-block-regexp)))
  18780. (defun org-point-at-end-of-empty-headline ()
  18781. "If point is at the end of an empty headline, return t, else nil.
  18782. If the heading only contains a TODO keyword, it is still still considered
  18783. empty."
  18784. (let ((case-fold-search nil))
  18785. (and (looking-at "[ \t]*$")
  18786. org-todo-line-regexp
  18787. (save-excursion
  18788. (beginning-of-line)
  18789. (looking-at org-todo-line-regexp)
  18790. (string= (match-string 3) "")))))
  18791. (defun org-at-heading-or-item-p ()
  18792. (or (org-at-heading-p) (org-at-item-p)))
  18793. (defun org-up-heading-all (arg)
  18794. "Move to the heading line of which the present line is a subheading.
  18795. This function considers both visible and invisible heading lines.
  18796. With argument, move up ARG levels."
  18797. (outline-up-heading arg t))
  18798. (defun org-up-heading-safe ()
  18799. "Move to the heading line of which the present line is a subheading.
  18800. This version will not throw an error. It will return the level of the
  18801. headline found, or nil if no higher level is found.
  18802. Also, this function will be a lot faster than `outline-up-heading',
  18803. because it relies on stars being the outline starters. This can really
  18804. make a significant difference in outlines with very many siblings."
  18805. (when (ignore-errors (org-back-to-heading t))
  18806. (let ((level-up (1- (funcall outline-level))))
  18807. (and (> level-up 0)
  18808. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  18809. (funcall outline-level)))))
  18810. (defun org-first-sibling-p ()
  18811. "Is this heading the first child of its parents?"
  18812. (interactive)
  18813. (let ((re org-outline-regexp-bol)
  18814. level l)
  18815. (unless (org-at-heading-p t)
  18816. (user-error "Not at a heading"))
  18817. (setq level (funcall outline-level))
  18818. (save-excursion
  18819. (if (not (re-search-backward re nil t))
  18820. t
  18821. (setq l (funcall outline-level))
  18822. (< l level)))))
  18823. (defun org-goto-sibling (&optional previous)
  18824. "Goto the next sibling, even if it is invisible.
  18825. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18826. when a sibling was found. When none is found, return nil and don't
  18827. move point."
  18828. (let ((fun (if previous 're-search-backward 're-search-forward))
  18829. (pos (point))
  18830. (re org-outline-regexp-bol)
  18831. level l)
  18832. (when (ignore-errors (org-back-to-heading t))
  18833. (setq level (funcall outline-level))
  18834. (catch 'exit
  18835. (or previous (forward-char 1))
  18836. (while (funcall fun re nil t)
  18837. (setq l (funcall outline-level))
  18838. (when (< l level) (goto-char pos) (throw 'exit nil))
  18839. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18840. (goto-char pos)
  18841. nil))))
  18842. (defun org-show-siblings ()
  18843. "Show all siblings of the current headline."
  18844. (save-excursion
  18845. (while (org-goto-sibling) (org-flag-heading nil)))
  18846. (save-excursion
  18847. (while (org-goto-sibling 'previous)
  18848. (org-flag-heading nil))))
  18849. (defun org-goto-first-child ()
  18850. "Goto the first child, even if it is invisible.
  18851. Return t when a child was found. Otherwise don't move point and
  18852. return nil."
  18853. (let (level (pos (point)) (re org-outline-regexp-bol))
  18854. (when (ignore-errors (org-back-to-heading t))
  18855. (setq level (outline-level))
  18856. (forward-char 1)
  18857. (if (and (re-search-forward re nil t) (> (outline-level) level))
  18858. (progn (goto-char (match-beginning 0)) t)
  18859. (goto-char pos) nil))))
  18860. (defun org-show-hidden-entry ()
  18861. "Show an entry where even the heading is hidden."
  18862. (save-excursion
  18863. (org-show-entry)))
  18864. (defun org-flag-heading (flag &optional entry)
  18865. "Flag the current heading. FLAG non-nil means make invisible.
  18866. When ENTRY is non-nil, show the entire entry."
  18867. (save-excursion
  18868. (org-back-to-heading t)
  18869. ;; Check if we should show the entire entry
  18870. (if (not entry)
  18871. (org-flag-region
  18872. (line-end-position 0) (line-end-position) flag 'outline)
  18873. (org-show-entry)
  18874. (save-excursion
  18875. (and (outline-next-heading)
  18876. (org-flag-heading nil))))))
  18877. (defun org-get-next-sibling ()
  18878. "Move to next heading of the same level, and return point.
  18879. If there is no such heading, return nil.
  18880. This is like outline-next-sibling, but invisible headings are ok."
  18881. (let ((level (funcall outline-level)))
  18882. (outline-next-heading)
  18883. (while (and (not (eobp)) (> (funcall outline-level) level))
  18884. (outline-next-heading))
  18885. (unless (or (eobp) (< (funcall outline-level) level))
  18886. (point))))
  18887. (defun org-get-last-sibling ()
  18888. "Move to previous heading of the same level, and return point.
  18889. If there is no such heading, return nil."
  18890. (let ((opoint (point))
  18891. (level (funcall outline-level)))
  18892. (outline-previous-heading)
  18893. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18894. (while (and (> (funcall outline-level) level)
  18895. (not (bobp)))
  18896. (outline-previous-heading))
  18897. (unless (< (funcall outline-level) level)
  18898. (point)))))
  18899. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18900. "Goto to the end of a subtree."
  18901. ;; This contains an exact copy of the original function, but it uses
  18902. ;; `org-back-to-heading', to make it work also in invisible
  18903. ;; trees. And is uses an invisible-ok argument.
  18904. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18905. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18906. ;; with many children and grandchildren etc, this can be much faster
  18907. ;; than the outline version.
  18908. (org-back-to-heading invisible-ok)
  18909. (let ((first t)
  18910. (level (funcall outline-level)))
  18911. (if (and (derived-mode-p 'org-mode) (< level 1000))
  18912. ;; A true heading (not a plain list item), in Org
  18913. ;; This means we can easily find the end by looking
  18914. ;; only for the right number of stars. Using a regexp to do
  18915. ;; this is so much faster than using a Lisp loop.
  18916. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  18917. (forward-char 1)
  18918. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  18919. ;; something else, do it the slow way
  18920. (while (and (not (eobp))
  18921. (or first (> (funcall outline-level) level)))
  18922. (setq first nil)
  18923. (outline-next-heading)))
  18924. (unless to-heading
  18925. (when (memq (preceding-char) '(?\n ?\^M))
  18926. ;; Go to end of line before heading
  18927. (forward-char -1)
  18928. (when (memq (preceding-char) '(?\n ?\^M))
  18929. ;; leave blank line before heading
  18930. (forward-char -1)))))
  18931. (point))
  18932. (defun org-end-of-meta-data (&optional full)
  18933. "Skip planning line and properties drawer in current entry.
  18934. When optional argument FULL is non-nil, also skip empty lines,
  18935. clocking lines and regular drawers at the beginning of the
  18936. entry."
  18937. (org-back-to-heading t)
  18938. (forward-line)
  18939. (when (looking-at-p org-planning-line-re) (forward-line))
  18940. (when (looking-at org-property-drawer-re)
  18941. (goto-char (match-end 0))
  18942. (forward-line))
  18943. (when (and full (not (org-at-heading-p)))
  18944. (catch 'exit
  18945. (let ((end (save-excursion (outline-next-heading) (point)))
  18946. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18947. (while (not (eobp))
  18948. (cond ((looking-at-p org-drawer-regexp)
  18949. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18950. (forward-line)
  18951. (throw 'exit t)))
  18952. ((looking-at-p re) (forward-line))
  18953. (t (throw 'exit t))))))))
  18954. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18955. "Move forward to the ARG'th subheading at same level as this one.
  18956. Stop at the first and last subheadings of a superior heading.
  18957. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18958. non-nil it will also look at invisible ones."
  18959. (interactive "p")
  18960. (let ((backward? (and arg (< arg 0))))
  18961. (if (org-before-first-heading-p)
  18962. (if backward? (goto-char (point-min)) (outline-next-heading))
  18963. (org-back-to-heading invisible-ok)
  18964. (unless backward? (end-of-line)) ;do not match current headline
  18965. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18966. (f (if backward? #'re-search-backward #'re-search-forward))
  18967. (count (if arg (abs arg) 1))
  18968. (result (point)))
  18969. (while (and (> count 0)
  18970. (funcall f org-outline-regexp-bol nil 'move))
  18971. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18972. (cond ((< l level) (setq count 0))
  18973. ((and (= l level)
  18974. (or invisible-ok
  18975. (not (org-invisible-p
  18976. (line-beginning-position)))))
  18977. (cl-decf count)
  18978. (when (= l level) (setq result (point)))))))
  18979. (goto-char result))
  18980. (beginning-of-line))))
  18981. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18982. "Move backward to the ARG'th subheading at same level as this one.
  18983. Stop at the first and last subheadings of a superior heading."
  18984. (interactive "p")
  18985. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18986. (defun org-next-visible-heading (arg)
  18987. "Move to the next visible heading.
  18988. This function wraps `outline-next-visible-heading' with
  18989. `org-with-limited-levels' in order to skip over inline tasks and
  18990. respect customization of `org-odd-levels-only'."
  18991. (interactive "p")
  18992. (org-with-limited-levels
  18993. (outline-next-visible-heading arg)))
  18994. (defun org-previous-visible-heading (arg)
  18995. "Move to the previous visible heading.
  18996. This function wraps `outline-previous-visible-heading' with
  18997. `org-with-limited-levels' in order to skip over inline tasks and
  18998. respect customization of `org-odd-levels-only'."
  18999. (interactive "p")
  19000. (org-with-limited-levels
  19001. (outline-previous-visible-heading arg)))
  19002. (defun org-forward-paragraph ()
  19003. "Move forward to beginning of next paragraph or equivalent.
  19004. The function moves point to the beginning of the next visible
  19005. structural element, which can be a paragraph, a table, a list
  19006. item, etc. It also provides some special moves for convenience:
  19007. - On an affiliated keyword, jump to the beginning of the
  19008. relative element.
  19009. - On an item or a footnote definition, move to the second
  19010. element inside, if any.
  19011. - On a table or a property drawer, jump after it.
  19012. - On a verse or source block, stop after blank lines."
  19013. (interactive)
  19014. (unless (eobp)
  19015. (let* ((deactivate-mark nil)
  19016. (element (org-element-at-point))
  19017. (type (org-element-type element))
  19018. (post-affiliated (org-element-property :post-affiliated element))
  19019. (contents-begin (org-element-property :contents-begin element))
  19020. (contents-end (org-element-property :contents-end element))
  19021. (end (let ((end (org-element-property :end element)) (parent element))
  19022. (while (and (setq parent (org-element-property :parent parent))
  19023. (= (org-element-property :contents-end parent) end))
  19024. (setq end (org-element-property :end parent)))
  19025. end)))
  19026. (cond ((not element)
  19027. (skip-chars-forward " \r\t\n")
  19028. (or (eobp) (beginning-of-line)))
  19029. ;; On affiliated keywords, move to element's beginning.
  19030. ((< (point) post-affiliated)
  19031. (goto-char post-affiliated))
  19032. ;; At a table row, move to the end of the table. Similarly,
  19033. ;; at a node property, move to the end of the property
  19034. ;; drawer.
  19035. ((memq type '(node-property table-row))
  19036. (goto-char (org-element-property
  19037. :end (org-element-property :parent element))))
  19038. ((memq type '(property-drawer table)) (goto-char end))
  19039. ;; Consider blank lines as separators in verse and source
  19040. ;; blocks to ease editing.
  19041. ((memq type '(src-block verse-block))
  19042. (when (eq type 'src-block)
  19043. (setq contents-end
  19044. (save-excursion (goto-char end)
  19045. (skip-chars-backward " \r\t\n")
  19046. (line-beginning-position))))
  19047. (beginning-of-line)
  19048. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  19049. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  19050. (goto-char end)
  19051. (skip-chars-forward " \r\t\n")
  19052. (if (= (point) contents-end) (goto-char end)
  19053. (beginning-of-line))))
  19054. ;; With no contents, just skip element.
  19055. ((not contents-begin) (goto-char end))
  19056. ;; If contents are invisible, skip the element altogether.
  19057. ((org-invisible-p (line-end-position))
  19058. (cl-case type
  19059. (headline
  19060. (org-with-limited-levels (outline-next-visible-heading 1)))
  19061. ;; At a plain list, make sure we move to the next item
  19062. ;; instead of skipping the whole list.
  19063. (plain-list (forward-char)
  19064. (org-forward-paragraph))
  19065. (otherwise (goto-char end))))
  19066. ((>= (point) contents-end) (goto-char end))
  19067. ((>= (point) contents-begin)
  19068. ;; This can only happen on paragraphs and plain lists.
  19069. (cl-case type
  19070. (paragraph (goto-char end))
  19071. ;; At a plain list, try to move to second element in
  19072. ;; first item, if possible.
  19073. (plain-list (end-of-line)
  19074. (org-forward-paragraph))))
  19075. ;; When contents start on the middle of a line (e.g. in
  19076. ;; items and footnote definitions), try to reach first
  19077. ;; element starting after current line.
  19078. ((> (line-end-position) contents-begin)
  19079. (end-of-line)
  19080. (org-forward-paragraph))
  19081. (t (goto-char contents-begin))))))
  19082. (defun org-backward-paragraph ()
  19083. "Move backward to start of previous paragraph or equivalent.
  19084. The function moves point to the beginning of the current
  19085. structural element, which can be a paragraph, a table, a list
  19086. item, etc., or to the beginning of the previous visible one if
  19087. point is already there. It also provides some special moves for
  19088. convenience:
  19089. - On an affiliated keyword, jump to the first one.
  19090. - On a table or a property drawer, move to its beginning.
  19091. - On comment, example, export, src and verse blocks, stop
  19092. before blank lines."
  19093. (interactive)
  19094. (unless (bobp)
  19095. (let* ((deactivate-mark nil)
  19096. (element (org-element-at-point))
  19097. (type (org-element-type element))
  19098. (contents-end (org-element-property :contents-end element))
  19099. (post-affiliated (org-element-property :post-affiliated element))
  19100. (begin (org-element-property :begin element))
  19101. (special? ;blocks handled specially
  19102. (memq type '(comment-block example-block export-block src-block
  19103. verse-block)))
  19104. (contents-begin
  19105. (if special?
  19106. ;; These types have no proper contents. Fake line
  19107. ;; below the block opening line as contents beginning.
  19108. (save-excursion (goto-char begin) (line-beginning-position 2))
  19109. (org-element-property :contents-begin element))))
  19110. (cond
  19111. ((not element) (goto-char (point-min)))
  19112. ((= (point) begin)
  19113. (backward-char)
  19114. (org-backward-paragraph))
  19115. ((<= (point) post-affiliated) (goto-char begin))
  19116. ;; Special behavior: on a table or a property drawer, move to
  19117. ;; its beginning.
  19118. ((memq type '(node-property table-row))
  19119. (goto-char (org-element-property
  19120. :post-affiliated (org-element-property :parent element))))
  19121. (special?
  19122. (if (<= (point) contents-begin) (goto-char post-affiliated)
  19123. ;; Inside a verse block, see blank lines as paragraph
  19124. ;; separators.
  19125. (let ((origin (point)))
  19126. (skip-chars-backward " \r\t\n" contents-begin)
  19127. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  19128. (skip-chars-forward " \r\t\n" origin)
  19129. (if (= (point) origin) (goto-char contents-begin)
  19130. (beginning-of-line))))))
  19131. ((eq type 'paragraph) (goto-char contents-begin)
  19132. ;; When at first paragraph in an item or a footnote definition,
  19133. ;; move directly to beginning of line.
  19134. (let ((parent-contents
  19135. (org-element-property
  19136. :contents-begin (org-element-property :parent element))))
  19137. (when (and parent-contents (= parent-contents contents-begin))
  19138. (beginning-of-line))))
  19139. ;; At the end of a greater element, move to the beginning of
  19140. ;; the last element within.
  19141. ((and contents-end (>= (point) contents-end))
  19142. (goto-char (1- contents-end))
  19143. (org-backward-paragraph))
  19144. (t (goto-char (or post-affiliated begin))))
  19145. ;; Ensure we never leave point invisible.
  19146. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  19147. (defun org-forward-element ()
  19148. "Move forward by one element.
  19149. Move to the next element at the same level, when possible."
  19150. (interactive)
  19151. (cond ((eobp) (user-error "Cannot move further down"))
  19152. ((org-with-limited-levels (org-at-heading-p))
  19153. (let ((origin (point)))
  19154. (goto-char (org-end-of-subtree nil t))
  19155. (unless (org-with-limited-levels (org-at-heading-p))
  19156. (goto-char origin)
  19157. (user-error "Cannot move further down"))))
  19158. (t
  19159. (let* ((elem (org-element-at-point))
  19160. (end (org-element-property :end elem))
  19161. (parent (org-element-property :parent elem)))
  19162. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19163. (goto-char (org-element-property :end parent)))
  19164. ((integer-or-marker-p end) (goto-char end))
  19165. (t (message "No element at point")))))))
  19166. (defun org-backward-element ()
  19167. "Move backward by one element.
  19168. Move to the previous element at the same level, when possible."
  19169. (interactive)
  19170. (cond ((bobp) (user-error "Cannot move further up"))
  19171. ((org-with-limited-levels (org-at-heading-p))
  19172. ;; At a headline, move to the previous one, if any, or stay
  19173. ;; here.
  19174. (let ((origin (point)))
  19175. (org-with-limited-levels (org-backward-heading-same-level 1))
  19176. ;; When current headline has no sibling above, move to its
  19177. ;; parent.
  19178. (when (= (point) origin)
  19179. (or (org-with-limited-levels (org-up-heading-safe))
  19180. (progn (goto-char origin)
  19181. (user-error "Cannot move further up"))))))
  19182. (t
  19183. (let* ((elem (org-element-at-point))
  19184. (beg (org-element-property :begin elem)))
  19185. (cond
  19186. ;; Move to beginning of current element if point isn't
  19187. ;; there already.
  19188. ((null beg) (message "No element at point"))
  19189. ((/= (point) beg) (goto-char beg))
  19190. (t (goto-char beg)
  19191. (skip-chars-backward " \r\t\n")
  19192. (unless (bobp)
  19193. (let ((prev (org-element-at-point)))
  19194. (goto-char (org-element-property :begin prev))
  19195. (while (and (setq prev (org-element-property :parent prev))
  19196. (<= (org-element-property :end prev) beg))
  19197. (goto-char (org-element-property :begin prev)))))))))))
  19198. (defun org-up-element ()
  19199. "Move to upper element."
  19200. (interactive)
  19201. (if (org-with-limited-levels (org-at-heading-p))
  19202. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19203. (let* ((elem (org-element-at-point))
  19204. (parent (org-element-property :parent elem)))
  19205. (if parent (goto-char (org-element-property :begin parent))
  19206. (if (org-with-limited-levels (org-before-first-heading-p))
  19207. (user-error "No surrounding element")
  19208. (org-with-limited-levels (org-back-to-heading)))))))
  19209. (defun org-down-element ()
  19210. "Move to inner element."
  19211. (interactive)
  19212. (let ((element (org-element-at-point)))
  19213. (cond
  19214. ((memq (org-element-type element) '(plain-list table))
  19215. (goto-char (org-element-property :contents-begin element))
  19216. (forward-char))
  19217. ((memq (org-element-type element) org-element-greater-elements)
  19218. ;; If contents are hidden, first disclose them.
  19219. (when (org-invisible-p (line-end-position)) (org-cycle))
  19220. (goto-char (or (org-element-property :contents-begin element)
  19221. (user-error "No content for this element"))))
  19222. (t (user-error "No inner element")))))
  19223. (defun org-drag-element-backward ()
  19224. "Move backward element at point."
  19225. (interactive)
  19226. (let ((elem (or (org-element-at-point)
  19227. (user-error "No element at point"))))
  19228. (if (eq (org-element-type elem) 'headline)
  19229. ;; Preserve point when moving a whole tree, even if point was
  19230. ;; on blank lines below the headline.
  19231. (let ((offset (skip-chars-backward " \t\n")))
  19232. (unwind-protect (org-move-subtree-up)
  19233. (forward-char (- offset))))
  19234. (let ((prev-elem
  19235. (save-excursion
  19236. (goto-char (org-element-property :begin elem))
  19237. (skip-chars-backward " \r\t\n")
  19238. (unless (bobp)
  19239. (let* ((beg (org-element-property :begin elem))
  19240. (prev (org-element-at-point))
  19241. (up prev))
  19242. (while (and (setq up (org-element-property :parent up))
  19243. (<= (org-element-property :end up) beg))
  19244. (setq prev up))
  19245. prev)))))
  19246. ;; Error out if no previous element or previous element is
  19247. ;; a parent of the current one.
  19248. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19249. (user-error "Cannot drag element backward")
  19250. (let ((pos (point)))
  19251. (org-element-swap-A-B prev-elem elem)
  19252. (goto-char (+ (org-element-property :begin prev-elem)
  19253. (- pos (org-element-property :begin elem))))))))))
  19254. (defun org-drag-element-forward ()
  19255. "Move forward element at point."
  19256. (interactive)
  19257. (let* ((pos (point))
  19258. (elem (or (org-element-at-point)
  19259. (user-error "No element at point"))))
  19260. (when (= (point-max) (org-element-property :end elem))
  19261. (user-error "Cannot drag element forward"))
  19262. (goto-char (org-element-property :end elem))
  19263. (let ((next-elem (org-element-at-point)))
  19264. (when (or (org-element-nested-p elem next-elem)
  19265. (and (eq (org-element-type next-elem) 'headline)
  19266. (not (eq (org-element-type elem) 'headline))))
  19267. (goto-char pos)
  19268. (user-error "Cannot drag element forward"))
  19269. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19270. ;; body's length (without final blanks) and by the length of
  19271. ;; blanks between ELEM and NEXT-ELEM.
  19272. (let ((size-next (- (save-excursion
  19273. (goto-char (org-element-property :end next-elem))
  19274. (skip-chars-backward " \r\t\n")
  19275. (forward-line)
  19276. ;; Small correction if buffer doesn't end
  19277. ;; with a newline character.
  19278. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19279. (org-element-property :begin next-elem)))
  19280. (size-blank (- (org-element-property :end elem)
  19281. (save-excursion
  19282. (goto-char (org-element-property :end elem))
  19283. (skip-chars-backward " \r\t\n")
  19284. (forward-line)
  19285. (point)))))
  19286. (org-element-swap-A-B elem next-elem)
  19287. (goto-char (+ pos size-next size-blank))))))
  19288. (defun org-drag-line-forward (arg)
  19289. "Drag the line at point ARG lines forward."
  19290. (interactive "p")
  19291. (dotimes (_ (abs arg))
  19292. (let ((c (current-column)))
  19293. (if (< 0 arg)
  19294. (progn
  19295. (beginning-of-line 2)
  19296. (transpose-lines 1)
  19297. (beginning-of-line 0))
  19298. (transpose-lines 1)
  19299. (beginning-of-line -1))
  19300. (org-move-to-column c))))
  19301. (defun org-drag-line-backward (arg)
  19302. "Drag the line at point ARG lines backward."
  19303. (interactive "p")
  19304. (org-drag-line-forward (- arg)))
  19305. (defun org-mark-element ()
  19306. "Put point at beginning of this element, mark at end.
  19307. Interactively, if this command is repeated or (in Transient Mark
  19308. mode) if the mark is active, it marks the next element after the
  19309. ones already marked."
  19310. (interactive)
  19311. (let (deactivate-mark)
  19312. (if (and (called-interactively-p 'any)
  19313. (or (and (eq last-command this-command) (mark t))
  19314. (and transient-mark-mode mark-active)))
  19315. (set-mark
  19316. (save-excursion
  19317. (goto-char (mark))
  19318. (goto-char (org-element-property :end (org-element-at-point)))))
  19319. (let ((element (org-element-at-point)))
  19320. (end-of-line)
  19321. (push-mark (org-element-property :end element) t t)
  19322. (goto-char (org-element-property :begin element))))))
  19323. (defun org-narrow-to-element ()
  19324. "Narrow buffer to current element."
  19325. (interactive)
  19326. (let ((elem (org-element-at-point)))
  19327. (cond
  19328. ((eq (car elem) 'headline)
  19329. (narrow-to-region
  19330. (org-element-property :begin elem)
  19331. (org-element-property :end elem)))
  19332. ((memq (car elem) org-element-greater-elements)
  19333. (narrow-to-region
  19334. (org-element-property :contents-begin elem)
  19335. (org-element-property :contents-end elem)))
  19336. (t
  19337. (narrow-to-region
  19338. (org-element-property :begin elem)
  19339. (org-element-property :end elem))))))
  19340. (defun org-transpose-element ()
  19341. "Transpose current and previous elements, keeping blank lines between.
  19342. Point is moved after both elements."
  19343. (interactive)
  19344. (org-skip-whitespace)
  19345. (let ((end (org-element-property :end (org-element-at-point))))
  19346. (org-drag-element-backward)
  19347. (goto-char end)))
  19348. (defun org-unindent-buffer ()
  19349. "Un-indent the visible part of the buffer.
  19350. Relative indentation (between items, inside blocks, etc.) isn't
  19351. modified."
  19352. (interactive)
  19353. (unless (eq major-mode 'org-mode)
  19354. (user-error "Cannot un-indent a buffer not in Org mode"))
  19355. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19356. (unindent-tree
  19357. (lambda (contents)
  19358. (dolist (element (reverse contents))
  19359. (if (memq (org-element-type element) '(headline section))
  19360. (funcall unindent-tree (org-element-contents element))
  19361. (save-excursion
  19362. (save-restriction
  19363. (narrow-to-region
  19364. (org-element-property :begin element)
  19365. (org-element-property :end element))
  19366. (org-do-remove-indentation))))))))
  19367. (funcall unindent-tree (org-element-contents parse-tree))))
  19368. (defun org-make-options-regexp (kwds &optional extra)
  19369. "Make a regular expression for keyword lines.
  19370. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19371. when non-nil, is a regexp matching keywords names."
  19372. (concat "^[ \t]*#\\+\\("
  19373. (regexp-opt kwds)
  19374. (and extra (concat (and kwds "\\|") extra))
  19375. "\\):[ \t]*\\(.*\\)"))
  19376. ;;; Conveniently switch to Info nodes
  19377. (defun org-info-find-node (&optional nodename)
  19378. "Find Info documentation NODENAME or Org documentation according context.
  19379. Started from `gnus-info-find-node'."
  19380. (interactive)
  19381. (Info-goto-node
  19382. (or nodename
  19383. (let ((default-org-info-node "(org) Top"))
  19384. (cond
  19385. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19386. ((eq 'org-mode major-mode)
  19387. (let* ((context (org-element-at-point))
  19388. (element-info-nodes ; compare to `org-element-all-elements'.
  19389. `((babel-call . "(org) Evaluating Code Blocks")
  19390. (center-block . "(org) Paragraphs")
  19391. (clock . ,default-org-info-node)
  19392. (comment . "(org) Comment Lines")
  19393. (comment-block . "(org) Comment Lines")
  19394. (diary-sexp . ,default-org-info-node)
  19395. (drawer . "(org) Drawers")
  19396. (dynamic-block . "(org) Dynamic Blocks")
  19397. (example-block . "(org) Literal Examples")
  19398. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19399. (fixed-width . ,default-org-info-node)
  19400. (footnote-definition . "(org) Creating Footnotes")
  19401. (headline . "(org) Document Structure")
  19402. (horizontal-rule . "(org) Built-in Table Editor")
  19403. (inlinetask . ,default-org-info-node)
  19404. (item . "(org) Plain Lists")
  19405. (keyword . "(org) Per-file keywords")
  19406. (latex-environment . "(org) LaTeX Export")
  19407. (node-property . "(org) Properties and Columns")
  19408. (paragraph . "(org) Paragraphs")
  19409. (plain-list . "(org) Plain Lists")
  19410. (planning . "(org) Deadlines and Scheduling")
  19411. (property-drawer . "(org) Properties and Columns")
  19412. (quote-block . "(org) Paragraphs")
  19413. (section . ,default-org-info-node)
  19414. (special-block . ,default-org-info-node)
  19415. (src-block . "(org) Working with Source Code")
  19416. (table . "(org) Tables")
  19417. (table-row . "(org) Tables")
  19418. (verse-block . "(org) Paragraphs"))))
  19419. (or (cdr (assoc (car context) element-info-nodes))
  19420. default-org-info-node)))
  19421. (t default-org-info-node))))))
  19422. ;;; Finish up
  19423. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19424. (lambda () (add-hook 'change-major-mode-hook
  19425. 'org-show-all 'append 'local)))
  19426. (provide 'org)
  19427. (run-hooks 'org-load-hook)
  19428. ;;; org.el ends here