org.el 804 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235
  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-2019 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Keywords: outlines, hypermedia, calendar, wp
  7. ;; Homepage: https://orgmode.org
  8. ;; Version: 9.3
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; https://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; https://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar org-inlinetask-min-level)
  64. ;;;; Require other packages
  65. (require 'cl-lib)
  66. (eval-when-compile (require 'gnus-sum))
  67. (require 'calendar)
  68. (require 'find-func)
  69. (require 'format-spec)
  70. (or (eq this-command 'eval-buffer)
  71. (condition-case nil
  72. (load (concat (file-name-directory load-file-name)
  73. "org-loaddefs.el")
  74. nil t t t)
  75. (error
  76. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  77. (sit-for 3)
  78. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  79. (sit-for 3))))
  80. (eval-and-compile (require 'org-macs))
  81. (require 'org-compat)
  82. (require 'org-keys)
  83. (require 'ol)
  84. (require 'org-table)
  85. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  86. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  87. (defvar org-outline-regexp "\\*+ "
  88. "Regexp to match Org headlines.")
  89. (defvar org-outline-regexp-bol "^\\*+ "
  90. "Regexp to match Org headlines.
  91. This is similar to `org-outline-regexp' but additionally makes
  92. sure that we are at the beginning of the line.")
  93. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  94. "Matches a headline, putting stars and text into groups.
  95. Stars are put in group 1 and the trimmed body in group 2.")
  96. (declare-function calendar-check-holidays "holidays" (date))
  97. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  98. (declare-function cdlatex-math-symbol "ext:cdlatex")
  99. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  100. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  101. (declare-function org-add-archive-files "org-archive" (files))
  102. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  103. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  104. (declare-function org-agenda-redo "org-agenda" (&optional all))
  105. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  106. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  107. (declare-function org-archive-subtree-default "org-archive" ())
  108. (declare-function org-archive-to-archive-sibling "org-archive" ())
  109. (declare-function org-attach "org-attach" ())
  110. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  111. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  112. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  113. (declare-function org-clock-cancel "org-clock" ())
  114. (declare-function org-clock-display "org-clock" (&optional arg))
  115. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  116. (declare-function org-clock-goto "org-clock" (&optional select))
  117. (declare-function org-clock-in "org-clock" (&optional select start-time))
  118. (declare-function org-clock-in-last "org-clock" (&optional arg))
  119. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  120. (declare-function org-clock-out-if-current "org-clock" ())
  121. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  122. (declare-function org-clock-report "org-clock" (&optional arg))
  123. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  124. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  125. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  126. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  127. (declare-function org-clock-update-time-maybe "org-clock" ())
  128. (declare-function org-clocking-buffer "org-clock" ())
  129. (declare-function org-clocktable-shift "org-clock" (dir n))
  130. (declare-function org-columns-insert-dblock "org-colview" ())
  131. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  132. (declare-function org-element-at-point "org-element" ())
  133. (declare-function org-element-cache-refresh "org-element" (pos))
  134. (declare-function org-element-cache-reset "org-element" (&optional all))
  135. (declare-function org-element-contents "org-element" (element))
  136. (declare-function org-element-context "org-element" (&optional element))
  137. (declare-function org-element-copy "org-element" (datum))
  138. (declare-function org-element-create "org-element" (type &optional props &rest children))
  139. (declare-function org-element-interpret-data "org-element" (data))
  140. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  141. (declare-function org-element-link-parser "org-element" ())
  142. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  143. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  144. (declare-function org-element-property "org-element" (property element))
  145. (declare-function org-element-put-property "org-element" (element property value))
  146. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  147. (declare-function org-element-timestamp-parser "org-element" ())
  148. (declare-function org-element-type "org-element" (element))
  149. (declare-function org-export-dispatch "ox" (&optional arg))
  150. (declare-function org-export-get-backend "ox" (name))
  151. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  152. (declare-function org-feed-goto-inbox "org-feed" (feed))
  153. (declare-function org-feed-update-all "org-feed" ())
  154. (declare-function org-goto "org-goto" (&optional alternative-interface))
  155. (declare-function org-id-find-id-file "org-id" (id))
  156. (declare-function org-id-get-create "org-id" (&optional force))
  157. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  158. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  159. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  160. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  161. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  162. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  163. (declare-function org-timer "org-timer" (&optional restart no-insert))
  164. (declare-function org-timer-item "org-timer" (&optional arg))
  165. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  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-timer-stop "org-timer" ())
  171. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  172. (declare-function org-update-radio-target-regexp "ol" ())
  173. (defvar ffap-url-regexp)
  174. (defvar org-element-paragraph-separate)
  175. (defvar org-indent-indentation-per-level)
  176. (defvar org-radio-target-regexp)
  177. (defvar org-target-link-regexp)
  178. (defvar org-target-regexp)
  179. ;; load languages based on value of `org-babel-load-languages'
  180. (defvar org-babel-load-languages)
  181. ;;;###autoload
  182. (defun org-babel-do-load-languages (sym value)
  183. "Load the languages defined in `org-babel-load-languages'."
  184. (set-default sym value)
  185. (dolist (pair org-babel-load-languages)
  186. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  187. (if active
  188. (require (intern (concat "ob-" lang)))
  189. (fmakunbound
  190. (intern (concat "org-babel-execute:" lang)))
  191. (fmakunbound
  192. (intern (concat "org-babel-expand-body:" lang)))))))
  193. ;;;###autoload
  194. (defun org-babel-load-file (file &optional compile)
  195. "Load Emacs Lisp source code blocks in the Org FILE.
  196. This function exports the source code using `org-babel-tangle'
  197. and then loads the resulting file using `load-file'. With
  198. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  199. byte-compiled before it is loaded."
  200. (interactive "fFile to load: \nP")
  201. (let* ((tangled-file (concat (file-name-sans-extension file) ".el")))
  202. ;; Tangle only if the Org file is newer than the Elisp file.
  203. (unless (org-file-newer-than-p
  204. tangled-file
  205. (file-attribute-modification-time (file-attributes 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. (defcustom org-enable-fixed-width-editor t
  1470. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1471. This currently only means they are never auto-wrapped.
  1472. When nil, such lines will be treated like ordinary lines."
  1473. :group 'org-edit-structure
  1474. :type 'boolean)
  1475. (defgroup org-sparse-trees nil
  1476. "Options concerning sparse trees in Org mode."
  1477. :tag "Org Sparse Trees"
  1478. :group 'org-structure)
  1479. (defcustom org-highlight-sparse-tree-matches t
  1480. "Non-nil means highlight all matches that define a sparse tree.
  1481. The highlights will automatically disappear the next time the buffer is
  1482. changed by an edit command."
  1483. :group 'org-sparse-trees
  1484. :type 'boolean)
  1485. (defcustom org-remove-highlights-with-change t
  1486. "Non-nil means any change to the buffer will remove temporary highlights.
  1487. \\<org-mode-map>\
  1488. Such highlights are created by `org-occur' and `org-clock-display'.
  1489. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1490. to get rid of the highlights.
  1491. The highlights created by `org-latex-preview' always need
  1492. `\\[org-latex-preview]' to be removed."
  1493. :group 'org-sparse-trees
  1494. :group 'org-time
  1495. :type 'boolean)
  1496. (defcustom org-occur-case-fold-search t
  1497. "Non-nil means `org-occur' should be case-insensitive.
  1498. If set to `smart' the search will be case-insensitive only if it
  1499. doesn't specify any upper case character."
  1500. :group 'org-sparse-trees
  1501. :version "26.1"
  1502. :type '(choice
  1503. (const :tag "Case-sensitive" nil)
  1504. (const :tag "Case-insensitive" t)
  1505. (const :tag "Case-insensitive for lower case searches only" smart)))
  1506. (defcustom org-occur-hook '(org-first-headline-recenter)
  1507. "Hook that is run after `org-occur' has constructed a sparse tree.
  1508. This can be used to recenter the window to show as much of the structure
  1509. as possible."
  1510. :group 'org-sparse-trees
  1511. :type 'hook)
  1512. (defcustom org-self-insert-cluster-for-undo nil
  1513. "Non-nil means cluster self-insert commands for undo when possible.
  1514. If this is set, then, like in the Emacs command loop, 20 consecutive
  1515. characters will be undone together.
  1516. This is configurable, because there is some impact on typing performance."
  1517. :group 'org-table
  1518. :type 'boolean)
  1519. (defvaralias 'org-activate-links 'org-highlight-links)
  1520. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1521. "Types of links that should be highlighted in Org files.
  1522. This is a list of symbols, each one of them leading to the
  1523. highlighting of a certain link type.
  1524. You can still open links that are not highlighted.
  1525. In principle, it does not hurt to turn on highlighting for all
  1526. link types. There may be a small gain when turning off unused
  1527. link types. The types are:
  1528. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1529. angle Links in angular brackets that may contain whitespace like
  1530. <bbdb:Carsten Dominik>.
  1531. plain Plain links in normal text, no whitespace, like http://google.com.
  1532. radio Text that is matched by a radio target, see manual for details.
  1533. tag Tag settings in a headline (link to tag search).
  1534. date Time stamps (link to calendar).
  1535. footnote Footnote labels.
  1536. If you set this variable during an Emacs session, use `org-mode-restart'
  1537. in the Org buffer so that the change takes effect."
  1538. :group 'org-appearance
  1539. :type '(set :greedy t
  1540. (const :tag "Double bracket links" bracket)
  1541. (const :tag "Angular bracket links" angle)
  1542. (const :tag "Plain text links" plain)
  1543. (const :tag "Radio target matches" radio)
  1544. (const :tag "Tags" tag)
  1545. (const :tag "Timestamps" date)
  1546. (const :tag "Footnotes" footnote)))
  1547. (defcustom org-mark-ring-length 4
  1548. "Number of different positions to be recorded in the ring.
  1549. Changing this requires a restart of Emacs to work correctly."
  1550. :group 'org-link-follow
  1551. :type 'integer)
  1552. (defgroup org-refile nil
  1553. "Options concerning refiling entries in Org mode."
  1554. :tag "Org Refile"
  1555. :group 'org)
  1556. (defcustom org-directory "~/org"
  1557. "Directory with Org files.
  1558. This is just a default location to look for Org files. There is no need
  1559. at all to put your files into this directory. It is used in the
  1560. following situations:
  1561. 1. When a capture template specifies a target file that is not an
  1562. absolute path. The path will then be interpreted relative to
  1563. `org-directory'
  1564. 2. When the value of variable `org-agenda-files' is a single file, any
  1565. relative paths in this file will be taken as relative to
  1566. `org-directory'."
  1567. :group 'org-refile
  1568. :group 'org-capture
  1569. :type 'directory)
  1570. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  1571. "Default target for storing notes.
  1572. Used as a fall back file for org-capture.el, for templates that
  1573. do not specify a target file."
  1574. :group 'org-refile
  1575. :group 'org-capture
  1576. :type 'file)
  1577. (defcustom org-reverse-note-order nil
  1578. "Non-nil means store new notes at the beginning of a file or entry.
  1579. When nil, new notes will be filed to the end of a file or entry.
  1580. This can also be a list with cons cells of regular expressions that
  1581. are matched against file names, and values."
  1582. :group 'org-capture
  1583. :group 'org-refile
  1584. :type '(choice
  1585. (const :tag "Reverse always" t)
  1586. (const :tag "Reverse never" nil)
  1587. (repeat :tag "By file name regexp"
  1588. (cons regexp boolean))))
  1589. (defcustom org-log-refile nil
  1590. "Information to record when a task is refiled.
  1591. Possible values are:
  1592. nil Don't add anything
  1593. time Add a time stamp to the task
  1594. note Prompt for a note and add it with template `org-log-note-headings'
  1595. This option can also be set with on a per-file-basis with
  1596. #+STARTUP: nologrefile
  1597. #+STARTUP: logrefile
  1598. #+STARTUP: lognoterefile
  1599. You can have local logging settings for a subtree by setting the LOGGING
  1600. property to one or more of these keywords.
  1601. When bulk-refiling, e.g., from the agenda, the value `note' is
  1602. forbidden and will temporarily be changed to `time'."
  1603. :group 'org-refile
  1604. :group 'org-progress
  1605. :version "24.1"
  1606. :type '(choice
  1607. (const :tag "No logging" nil)
  1608. (const :tag "Record timestamp" time)
  1609. (const :tag "Record timestamp with note." note)))
  1610. (defcustom org-refile-targets nil
  1611. "Targets for refiling entries with `\\[org-refile]'.
  1612. This is a list of cons cells. Each cell contains:
  1613. - a specification of the files to be considered, either a list of files,
  1614. or a symbol whose function or variable value will be used to retrieve
  1615. a file name or a list of file names. If you use `org-agenda-files' for
  1616. that, all agenda files will be scanned for targets. Nil means consider
  1617. headings in the current buffer.
  1618. - A specification of how to find candidate refile targets. This may be
  1619. any of:
  1620. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  1621. This tag has to be present in all target headlines, inheritance will
  1622. not be considered.
  1623. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  1624. todo keyword.
  1625. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  1626. headlines that are refiling targets.
  1627. - a cons cell (:level . N). Any headline of level N is considered a target.
  1628. Note that, when `org-odd-levels-only' is set, level corresponds to
  1629. order in hierarchy, not to the number of stars.
  1630. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  1631. Note that, when `org-odd-levels-only' is set, level corresponds to
  1632. order in hierarchy, not to the number of stars.
  1633. Each element of this list generates a set of possible targets.
  1634. The union of these sets is presented (with completion) to
  1635. the user by `org-refile'.
  1636. You can set the variable `org-refile-target-verify-function' to a function
  1637. to verify each headline found by the simple criteria above.
  1638. When this variable is nil, all top-level headlines in the current buffer
  1639. are used, equivalent to the value `((nil . (:level . 1))'."
  1640. :group 'org-refile
  1641. :type '(repeat
  1642. (cons
  1643. (choice :value org-agenda-files
  1644. (const :tag "All agenda files" org-agenda-files)
  1645. (const :tag "Current buffer" nil)
  1646. (function) (variable) (file))
  1647. (choice :tag "Identify target headline by"
  1648. (cons :tag "Specific tag" (const :value :tag) (string))
  1649. (cons :tag "TODO keyword" (const :value :todo) (string))
  1650. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  1651. (cons :tag "Level number" (const :value :level) (integer))
  1652. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  1653. (defcustom org-refile-target-verify-function nil
  1654. "Function to verify if the headline at point should be a refile target.
  1655. The function will be called without arguments, with point at the
  1656. beginning of the headline. It should return t and leave point
  1657. where it is if the headline is a valid target for refiling.
  1658. If the target should not be selected, the function must return nil.
  1659. In addition to this, it may move point to a place from where the search
  1660. should be continued. For example, the function may decide that the entire
  1661. subtree of the current entry should be excluded and move point to the end
  1662. of the subtree."
  1663. :group 'org-refile
  1664. :type '(choice
  1665. (const nil)
  1666. (function)))
  1667. (defcustom org-refile-use-cache nil
  1668. "Non-nil means cache refile targets to speed up the process.
  1669. \\<org-mode-map>\
  1670. The cache for a particular file will be updated automatically when
  1671. the buffer has been killed, or when any of the marker used for flagging
  1672. refile targets no longer points at a live buffer.
  1673. If you have added new entries to a buffer that might themselves be targets,
  1674. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  1675. if you find that easier, \
  1676. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  1677. \\[org-refile]'."
  1678. :group 'org-refile
  1679. :version "24.1"
  1680. :type 'boolean)
  1681. (defcustom org-refile-use-outline-path nil
  1682. "Non-nil means provide refile targets as paths.
  1683. So a level 3 headline will be available as level1/level2/level3.
  1684. When the value is `file', also include the file name (without directory)
  1685. into the path. In this case, you can also stop the completion after
  1686. the file name, to get entries inserted as top level in the file.
  1687. When `full-file-path', include the full file path.
  1688. When `buffer-name', use the buffer name."
  1689. :group 'org-refile
  1690. :type '(choice
  1691. (const :tag "Not" nil)
  1692. (const :tag "Yes" t)
  1693. (const :tag "Start with file name" file)
  1694. (const :tag "Start with full file path" full-file-path)
  1695. (const :tag "Start with buffer name" buffer-name)))
  1696. (defcustom org-outline-path-complete-in-steps t
  1697. "Non-nil means complete the outline path in hierarchical steps.
  1698. When Org uses the refile interface to select an outline path (see
  1699. `org-refile-use-outline-path'), the completion of the path can be
  1700. done in a single go, or it can be done in steps down the headline
  1701. hierarchy. Going in steps is probably the best if you do not use
  1702. a special completion package like `ido' or `icicles'. However,
  1703. when using these packages, going in one step can be very fast,
  1704. while still showing the whole path to the entry."
  1705. :group 'org-refile
  1706. :type 'boolean)
  1707. (defcustom org-refile-allow-creating-parent-nodes nil
  1708. "Non-nil means allow the creation of new nodes as refile targets.
  1709. New nodes are then created by adding \"/new node name\" to the completion
  1710. of an existing node. When the value of this variable is `confirm',
  1711. new node creation must be confirmed by the user (recommended).
  1712. When nil, the completion must match an existing entry.
  1713. Note that, if the new heading is not seen by the criteria
  1714. listed in `org-refile-targets', multiple instances of the same
  1715. heading would be created by trying again to file under the new
  1716. heading."
  1717. :group 'org-refile
  1718. :type '(choice
  1719. (const :tag "Never" nil)
  1720. (const :tag "Always" t)
  1721. (const :tag "Prompt for confirmation" confirm)))
  1722. (defcustom org-refile-active-region-within-subtree nil
  1723. "Non-nil means also refile active region within a subtree.
  1724. By default `org-refile' doesn't allow refiling regions if they
  1725. don't contain a set of subtrees, but it might be convenient to
  1726. do so sometimes: in that case, the first line of the region is
  1727. converted to a headline before refiling."
  1728. :group 'org-refile
  1729. :version "24.1"
  1730. :type 'boolean)
  1731. (defgroup org-todo nil
  1732. "Options concerning TODO items in Org mode."
  1733. :tag "Org TODO"
  1734. :group 'org)
  1735. (defgroup org-progress nil
  1736. "Options concerning Progress logging in Org mode."
  1737. :tag "Org Progress"
  1738. :group 'org-time)
  1739. (defvar org-todo-interpretation-widgets
  1740. '((:tag "Sequence (cycling hits every state)" sequence)
  1741. (:tag "Type (cycling directly to DONE)" type))
  1742. "The available interpretation symbols for customizing `org-todo-keywords'.
  1743. Interested libraries should add to this list.")
  1744. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1745. "List of TODO entry keyword sequences and their interpretation.
  1746. \\<org-mode-map>This is a list of sequences.
  1747. Each sequence starts with a symbol, either `sequence' or `type',
  1748. indicating if the keywords should be interpreted as a sequence of
  1749. action steps, or as different types of TODO items. The first
  1750. keywords are states requiring action - these states will select a headline
  1751. for inclusion into the global TODO list Org produces. If one of the
  1752. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1753. signify that no further action is necessary. If \"|\" is not found,
  1754. the last keyword is treated as the only DONE state of the sequence.
  1755. The command `\\[org-todo]' cycles an entry through these states, and one
  1756. additional state where no keyword is present. For details about this
  1757. cycling, see the manual.
  1758. TODO keywords and interpretation can also be set on a per-file basis with
  1759. the special #+SEQ_TODO and #+TYP_TODO lines.
  1760. Each keyword can optionally specify a character for fast state selection
  1761. \(in combination with the variable `org-use-fast-todo-selection')
  1762. and specifiers for state change logging, using the same syntax that
  1763. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1764. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1765. indicates to record a time stamp each time this state is selected.
  1766. Each keyword may also specify if a timestamp or a note should be
  1767. recorded when entering or leaving the state, by adding additional
  1768. characters in the parenthesis after the keyword. This looks like this:
  1769. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1770. record only the time of the state change. With X and Y being either
  1771. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1772. Y when leaving the state if and only if the *target* state does not
  1773. define X. You may omit any of the fast-selection key or X or /Y,
  1774. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1775. For backward compatibility, this variable may also be just a list
  1776. of keywords. In this case the interpretation (sequence or type) will be
  1777. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1778. :group 'org-todo
  1779. :group 'org-keywords
  1780. :type '(choice
  1781. (repeat :tag "Old syntax, just keywords"
  1782. (string :tag "Keyword"))
  1783. (repeat :tag "New syntax"
  1784. (cons
  1785. (choice
  1786. :tag "Interpretation"
  1787. ;;Quick and dirty way to see
  1788. ;;`org-todo-interpretations'. This takes the
  1789. ;;place of item arguments
  1790. :convert-widget
  1791. (lambda (widget)
  1792. (widget-put widget
  1793. :args (mapcar
  1794. (lambda (x)
  1795. (widget-convert
  1796. (cons 'const x)))
  1797. org-todo-interpretation-widgets))
  1798. widget))
  1799. (repeat
  1800. (string :tag "Keyword"))))))
  1801. (defvar-local org-todo-keywords-1 nil
  1802. "All TODO and DONE keywords active in a buffer.")
  1803. (defvar org-todo-keywords-for-agenda nil)
  1804. (defvar org-done-keywords-for-agenda nil)
  1805. (defvar org-todo-keyword-alist-for-agenda nil)
  1806. (defvar org-tag-alist-for-agenda nil
  1807. "Alist of all tags from all agenda files.")
  1808. (defvar org-tag-groups-alist-for-agenda nil
  1809. "Alist of all groups tags from all current agenda files.")
  1810. (defvar-local org-tag-groups-alist nil)
  1811. (defvar org-agenda-contributing-files nil)
  1812. (defvar-local org-current-tag-alist nil
  1813. "Alist of all tag groups in current buffer.
  1814. This variable takes into consideration `org-tag-alist',
  1815. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1816. (defvar-local org-not-done-keywords nil)
  1817. (defvar-local org-done-keywords nil)
  1818. (defvar-local org-todo-heads nil)
  1819. (defvar-local org-todo-sets nil)
  1820. (defvar-local org-todo-log-states nil)
  1821. (defvar-local org-todo-kwd-alist nil)
  1822. (defvar-local org-todo-key-alist nil)
  1823. (defvar-local org-todo-key-trigger nil)
  1824. (defcustom org-todo-interpretation 'sequence
  1825. "Controls how TODO keywords are interpreted.
  1826. This variable is in principle obsolete and is only used for
  1827. backward compatibility, if the interpretation of todo keywords is
  1828. not given already in `org-todo-keywords'. See that variable for
  1829. more information."
  1830. :group 'org-todo
  1831. :group 'org-keywords
  1832. :type '(choice (const sequence)
  1833. (const type)))
  1834. (defcustom org-use-fast-todo-selection 'auto
  1835. "\\<org-mode-map>\
  1836. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1837. This variable describes if and under what circumstances the cycling
  1838. mechanism for TODO keywords will be replaced by a single-key, direct
  1839. selection scheme, where the choices are displayed in a little window.
  1840. When nil, fast selection is never used. This means that the command
  1841. will always switch to the next state.
  1842. When it is the symbol `auto', fast selection is whenever selection
  1843. keys have been defined.
  1844. `expert' is like `auto', but no special window with the keyword
  1845. will be shown, choices will only be listed in the prompt.
  1846. In all cases, the special interface is only used if access keys have
  1847. actually been assigned by the user, i.e. if keywords in the configuration
  1848. are followed by a letter in parenthesis, like TODO(t)."
  1849. :group 'org-todo
  1850. :set (lambda (var val)
  1851. (cond
  1852. ((eq var t) (set var 'auto))
  1853. ((eq var 'prefix) (set var nil))
  1854. (t (set var val))))
  1855. :type '(choice
  1856. (const :tag "Never" nil)
  1857. (const :tag "Automatically, when key letter have been defined" auto)
  1858. (const :tag "Automatically, but don't show the selection window" expert)))
  1859. (defcustom org-provide-todo-statistics t
  1860. "Non-nil means update todo statistics after insert and toggle.
  1861. ALL-HEADLINES means update todo statistics by including headlines
  1862. with no TODO keyword as well, counting them as not done.
  1863. A list of TODO keywords means the same, but skip keywords that are
  1864. not in this list.
  1865. When set to a list of two lists, the first list contains keywords
  1866. to consider as TODO keywords, the second list contains keywords
  1867. to consider as DONE keywords.
  1868. When this is set, todo statistics is updated in the parent of the
  1869. current entry each time a todo state is changed."
  1870. :group 'org-todo
  1871. :type '(choice
  1872. (const :tag "Yes, only for TODO entries" t)
  1873. (const :tag "Yes, including all entries" all-headlines)
  1874. (repeat :tag "Yes, for TODOs in this list"
  1875. (string :tag "TODO keyword"))
  1876. (list :tag "Yes, for TODOs and DONEs in these lists"
  1877. (repeat (string :tag "TODO keyword"))
  1878. (repeat (string :tag "DONE keyword")))
  1879. (other :tag "No TODO statistics" nil)))
  1880. (defcustom org-hierarchical-todo-statistics t
  1881. "Non-nil means TODO statistics covers just direct children.
  1882. When nil, all entries in the subtree are considered.
  1883. This has only an effect if `org-provide-todo-statistics' is set.
  1884. To set this to nil for only a single subtree, use a COOKIE_DATA
  1885. property and include the word \"recursive\" into the value."
  1886. :group 'org-todo
  1887. :type 'boolean)
  1888. (defcustom org-after-todo-state-change-hook nil
  1889. "Hook which is run after the state of a TODO item was changed.
  1890. The new state (a string with a TODO keyword, or nil) is available in the
  1891. Lisp variable `org-state'."
  1892. :group 'org-todo
  1893. :type 'hook)
  1894. (defvar org-blocker-hook nil
  1895. "Hook for functions that are allowed to block a state change.
  1896. Functions in this hook should not modify the buffer.
  1897. Each function gets as its single argument a property list,
  1898. see `org-trigger-hook' for more information about this list.
  1899. If any of the functions in this hook returns nil, the state change
  1900. is blocked.")
  1901. (defvar org-trigger-hook nil
  1902. "Hook for functions that are triggered by a state change.
  1903. Each function gets as its single argument a property list with at
  1904. least the following elements:
  1905. (:type type-of-change :position pos-at-entry-start
  1906. :from old-state :to new-state)
  1907. Depending on the type, more properties may be present.
  1908. This mechanism is currently implemented for:
  1909. TODO state changes
  1910. ------------------
  1911. :type todo-state-change
  1912. :from previous state (keyword as a string), or nil, or a symbol
  1913. `todo' or `done', to indicate the general type of state.
  1914. :to new state, like in :from")
  1915. (defcustom org-enforce-todo-dependencies nil
  1916. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1917. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1918. be blocked if any prior sibling is not yet done.
  1919. Finally, if the parent is blocked because of ordered siblings of its own,
  1920. the child will also be blocked."
  1921. :set (lambda (var val)
  1922. (set var val)
  1923. (if val
  1924. (add-hook 'org-blocker-hook
  1925. 'org-block-todo-from-children-or-siblings-or-parent)
  1926. (remove-hook 'org-blocker-hook
  1927. 'org-block-todo-from-children-or-siblings-or-parent)))
  1928. :group 'org-todo
  1929. :type 'boolean)
  1930. (defcustom org-enforce-todo-checkbox-dependencies nil
  1931. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1932. When this is nil, checkboxes have no influence on switching TODO states.
  1933. When non-nil, you first need to check off all check boxes before the TODO
  1934. entry can be switched to DONE.
  1935. This variable needs to be set before org.el is loaded, and you need to
  1936. restart Emacs after a change to make the change effective. The only way
  1937. to change it while Emacs is running is through the customize interface."
  1938. :set (lambda (var val)
  1939. (set var val)
  1940. (if val
  1941. (add-hook 'org-blocker-hook
  1942. 'org-block-todo-from-checkboxes)
  1943. (remove-hook 'org-blocker-hook
  1944. 'org-block-todo-from-checkboxes)))
  1945. :group 'org-todo
  1946. :type 'boolean)
  1947. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1948. "Non-nil means inserting a TODO heading is treated as state change.
  1949. So when the command `\\[org-insert-todo-heading]' is used, state change
  1950. logging will apply if appropriate. When nil, the new TODO item will
  1951. be inserted directly, and no logging will take place."
  1952. :group 'org-todo
  1953. :type 'boolean)
  1954. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1955. "Non-nil means switching TODO states with S-cursor counts as state change.
  1956. This is the default behavior. However, setting this to nil allows a
  1957. convenient way to select a TODO state and bypass any logging associated
  1958. with that."
  1959. :group 'org-todo
  1960. :type 'boolean)
  1961. (defcustom org-todo-state-tags-triggers nil
  1962. "Tag changes that should be triggered by TODO state changes.
  1963. This is a list. Each entry is
  1964. (state-change (tag . flag) .......)
  1965. State-change can be a string with a state, and empty string to indicate the
  1966. state that has no TODO keyword, or it can be one of the symbols `todo'
  1967. or `done', meaning any not-done or done state, respectively."
  1968. :group 'org-todo
  1969. :group 'org-tags
  1970. :type '(repeat
  1971. (cons (choice :tag "When changing to"
  1972. (const :tag "Not-done state" todo)
  1973. (const :tag "Done state" done)
  1974. (string :tag "State"))
  1975. (repeat
  1976. (cons :tag "Tag action"
  1977. (string :tag "Tag")
  1978. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1979. (defcustom org-log-done nil
  1980. "Information to record when a task moves to the DONE state.
  1981. Possible values are:
  1982. nil Don't add anything, just change the keyword
  1983. time Add a time stamp to the task
  1984. note Prompt for a note and add it with template `org-log-note-headings'
  1985. This option can also be set with on a per-file-basis with
  1986. #+STARTUP: nologdone
  1987. #+STARTUP: logdone
  1988. #+STARTUP: lognotedone
  1989. You can have local logging settings for a subtree by setting the LOGGING
  1990. property to one or more of these keywords."
  1991. :group 'org-todo
  1992. :group 'org-progress
  1993. :type '(choice
  1994. (const :tag "No logging" nil)
  1995. (const :tag "Record CLOSED timestamp" time)
  1996. (const :tag "Record CLOSED timestamp with note." note)))
  1997. ;; Normalize old uses of org-log-done.
  1998. (cond
  1999. ((eq org-log-done t) (setq org-log-done 'time))
  2000. ((and (listp org-log-done) (memq 'done org-log-done))
  2001. (setq org-log-done 'note)))
  2002. (defcustom org-log-reschedule nil
  2003. "Information to record when the scheduling date of a task is modified.
  2004. Possible values are:
  2005. nil Don't add anything, just change the date
  2006. time Add a time stamp to the task
  2007. note Prompt for a note and add it with template `org-log-note-headings'
  2008. This option can also be set with on a per-file-basis with
  2009. #+STARTUP: nologreschedule
  2010. #+STARTUP: logreschedule
  2011. #+STARTUP: lognotereschedule
  2012. You can have local logging settings for a subtree by setting the LOGGING
  2013. property to one or more of these keywords.
  2014. This variable has an effect when calling `org-schedule' or
  2015. `org-agenda-schedule' only."
  2016. :group 'org-todo
  2017. :group 'org-progress
  2018. :type '(choice
  2019. (const :tag "No logging" nil)
  2020. (const :tag "Record timestamp" time)
  2021. (const :tag "Record timestamp with note" note)))
  2022. (defcustom org-log-redeadline nil
  2023. "Information to record when the deadline date of a task is modified.
  2024. Possible values are:
  2025. nil Don't add anything, just change the date
  2026. time Add a time stamp to the task
  2027. note Prompt for a note and add it with template `org-log-note-headings'
  2028. This option can also be set with on a per-file-basis with
  2029. #+STARTUP: nologredeadline
  2030. #+STARTUP: logredeadline
  2031. #+STARTUP: lognoteredeadline
  2032. You can have local logging settings for a subtree by setting the LOGGING
  2033. property to one or more of these keywords.
  2034. This variable has an effect when calling `org-deadline' or
  2035. `org-agenda-deadline' only."
  2036. :group 'org-todo
  2037. :group 'org-progress
  2038. :type '(choice
  2039. (const :tag "No logging" nil)
  2040. (const :tag "Record timestamp" time)
  2041. (const :tag "Record timestamp with note." note)))
  2042. (defcustom org-log-note-clock-out nil
  2043. "Non-nil means record a note when clocking out of an item.
  2044. This can also be configured on a per-file basis by adding one of
  2045. the following lines anywhere in the buffer:
  2046. #+STARTUP: lognoteclock-out
  2047. #+STARTUP: nolognoteclock-out"
  2048. :group 'org-todo
  2049. :group 'org-progress
  2050. :type 'boolean)
  2051. (defcustom org-log-done-with-time t
  2052. "Non-nil means the CLOSED time stamp will contain date and time.
  2053. When nil, only the date will be recorded."
  2054. :group 'org-progress
  2055. :type 'boolean)
  2056. (defcustom org-log-note-headings
  2057. '((done . "CLOSING NOTE %t")
  2058. (state . "State %-12s from %-12S %t")
  2059. (note . "Note taken on %t")
  2060. (reschedule . "Rescheduled from %S on %t")
  2061. (delschedule . "Not scheduled, was %S on %t")
  2062. (redeadline . "New deadline from %S on %t")
  2063. (deldeadline . "Removed deadline, was %S on %t")
  2064. (refile . "Refiled on %t")
  2065. (clock-out . ""))
  2066. "Headings for notes added to entries.
  2067. The value is an alist, with the car being a symbol indicating the
  2068. note context, and the cdr is the heading to be used. The heading
  2069. may also be the empty string. The following placeholders can be
  2070. used:
  2071. %t a time stamp.
  2072. %T an active time stamp instead the default inactive one
  2073. %d a short-format time stamp.
  2074. %D an active short-format time stamp.
  2075. %s the new TODO state or time stamp (inactive), in double quotes.
  2076. %S the old TODO state or time stamp (inactive), in double quotes.
  2077. %u the user name.
  2078. %U full user name.
  2079. In fact, it is not a good idea to change the `state' entry,
  2080. because Agenda Log mode depends on the format of these entries."
  2081. :group 'org-todo
  2082. :group 'org-progress
  2083. :type '(list :greedy t
  2084. (cons (const :tag "Heading when closing an item" done) string)
  2085. (cons (const :tag
  2086. "Heading when changing todo state (todo sequence only)"
  2087. state) string)
  2088. (cons (const :tag "Heading when just taking a note" note) string)
  2089. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2090. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2091. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2092. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2093. (cons (const :tag "Heading when refiling" refile) string)
  2094. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2095. (unless (assq 'note org-log-note-headings)
  2096. (push '(note . "%t") org-log-note-headings))
  2097. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2098. (defcustom org-log-into-drawer nil
  2099. "Non-nil means insert state change notes and time stamps into a drawer.
  2100. When nil, state changes notes will be inserted after the headline and
  2101. any scheduling and clock lines, but not inside a drawer.
  2102. The value of this variable should be the name of the drawer to use.
  2103. LOGBOOK is proposed as the default drawer for this purpose, you can
  2104. also set this to a string to define the drawer of your choice.
  2105. A value of t is also allowed, representing \"LOGBOOK\".
  2106. A value of t or nil can also be set with on a per-file-basis with
  2107. #+STARTUP: logdrawer
  2108. #+STARTUP: nologdrawer
  2109. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2110. will be ignored.
  2111. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2112. a subtree.
  2113. Do not check directly this variable in a Lisp program. Call
  2114. function `org-log-into-drawer' instead."
  2115. :group 'org-todo
  2116. :group 'org-progress
  2117. :type '(choice
  2118. (const :tag "Not into a drawer" nil)
  2119. (const :tag "LOGBOOK" t)
  2120. (string :tag "Other")))
  2121. (defun org-log-into-drawer ()
  2122. "Name of the log drawer, as a string, or nil.
  2123. This is the value of `org-log-into-drawer'. However, if the
  2124. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2125. be used instead of the default value."
  2126. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2127. (cond ((equal p "nil") nil)
  2128. ((equal p "t") "LOGBOOK")
  2129. ((stringp p) p)
  2130. (p "LOGBOOK")
  2131. ((stringp org-log-into-drawer) org-log-into-drawer)
  2132. (org-log-into-drawer "LOGBOOK"))))
  2133. (defcustom org-log-state-notes-insert-after-drawers nil
  2134. "Non-nil means insert state change notes after any drawers in entry.
  2135. Only the drawers that *immediately* follow the headline and the
  2136. deadline/scheduled line are skipped.
  2137. When nil, insert notes right after the heading and perhaps the line
  2138. with deadline/scheduling if present.
  2139. This variable will have no effect if `org-log-into-drawer' is
  2140. set."
  2141. :group 'org-todo
  2142. :group 'org-progress
  2143. :type 'boolean)
  2144. (defcustom org-log-states-order-reversed t
  2145. "Non-nil means the latest state note will be directly after heading.
  2146. When nil, the state change notes will be ordered according to time.
  2147. This option can also be set with on a per-file-basis with
  2148. #+STARTUP: logstatesreversed
  2149. #+STARTUP: nologstatesreversed"
  2150. :group 'org-todo
  2151. :group 'org-progress
  2152. :type 'boolean)
  2153. (defcustom org-todo-repeat-to-state nil
  2154. "The TODO state to which a repeater should return the repeating task.
  2155. By default this is the first task of a TODO sequence or the
  2156. previous state of a TYPE_TODO set. But you can specify to use
  2157. the previous state in a TODO sequence or a string.
  2158. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2159. entry, which has precedence over this option."
  2160. :group 'org-todo
  2161. :version "24.1"
  2162. :type '(choice (const :tag "Use the previous TODO state" t)
  2163. (const :tag "Use the head of the TODO sequence" nil)
  2164. (string :tag "Use a specific TODO state")))
  2165. (defcustom org-log-repeat 'time
  2166. "Non-nil means record moving through the DONE state when triggering repeat.
  2167. An auto-repeating task is immediately switched back to TODO when
  2168. marked DONE. If you are not logging state changes (by adding \"@\"
  2169. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2170. record a closing note, there will be no record of the task moving
  2171. through DONE. This variable forces taking a note anyway.
  2172. nil Don't force a record
  2173. time Record a time stamp
  2174. note Prompt for a note and add it with template `org-log-note-headings'
  2175. This option can also be set with on a per-file-basis with
  2176. #+STARTUP: nologrepeat
  2177. #+STARTUP: logrepeat
  2178. #+STARTUP: lognoterepeat
  2179. You can have local logging settings for a subtree by setting the LOGGING
  2180. property to one or more of these keywords."
  2181. :group 'org-todo
  2182. :group 'org-progress
  2183. :type '(choice
  2184. (const :tag "Don't force a record" nil)
  2185. (const :tag "Force recording the DONE state" time)
  2186. (const :tag "Force recording a note with the DONE state" note)))
  2187. (defcustom org-todo-repeat-hook nil
  2188. "Hook that is run after a task has been repeated."
  2189. :package-version '(Org . "9.2")
  2190. :group 'org-todo
  2191. :type 'hook)
  2192. (defgroup org-priorities nil
  2193. "Priorities in Org mode."
  2194. :tag "Org Priorities"
  2195. :group 'org-todo)
  2196. (defcustom org-enable-priority-commands t
  2197. "Non-nil means priority commands are active.
  2198. When nil, these commands will be disabled, so that you never accidentally
  2199. set a priority."
  2200. :group 'org-priorities
  2201. :type 'boolean)
  2202. (defcustom org-highest-priority ?A
  2203. "The highest priority of TODO items. A character like ?A, ?B etc.
  2204. Must have a smaller ASCII number than `org-lowest-priority'."
  2205. :group 'org-priorities
  2206. :type 'character)
  2207. (defcustom org-lowest-priority ?C
  2208. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2209. Must have a larger ASCII number than `org-highest-priority'."
  2210. :group 'org-priorities
  2211. :type 'character)
  2212. (defcustom org-default-priority ?B
  2213. "The default priority of TODO items.
  2214. This is the priority an item gets if no explicit priority is given.
  2215. When starting to cycle on an empty priority the first step in the cycle
  2216. depends on `org-priority-start-cycle-with-default'. The resulting first
  2217. step priority must not exceed the range from `org-highest-priority' to
  2218. `org-lowest-priority' which means that `org-default-priority' has to be
  2219. in this range exclusive or inclusive the range boundaries. Else the
  2220. first step refuses to set the default and the second will fall back
  2221. to (depending on the command used) the highest or lowest priority."
  2222. :group 'org-priorities
  2223. :type 'character)
  2224. (defcustom org-priority-start-cycle-with-default t
  2225. "Non-nil means start with default priority when starting to cycle.
  2226. When this is nil, the first step in the cycle will be (depending on the
  2227. command used) one higher or lower than the default priority.
  2228. See also `org-default-priority'."
  2229. :group 'org-priorities
  2230. :type 'boolean)
  2231. (defcustom org-get-priority-function nil
  2232. "Function to extract the priority from a string.
  2233. The string is normally the headline. If this is nil Org computes the
  2234. priority from the priority cookie like [#A] in the headline. It returns
  2235. an integer, increasing by 1000 for each priority level.
  2236. The user can set a different function here, which should take a string
  2237. as an argument and return the numeric priority."
  2238. :group 'org-priorities
  2239. :version "24.1"
  2240. :type '(choice
  2241. (const nil)
  2242. (function)))
  2243. (defgroup org-time nil
  2244. "Options concerning time stamps and deadlines in Org mode."
  2245. :tag "Org Time"
  2246. :group 'org)
  2247. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2248. "Number of minutes to round time stamps to.
  2249. \\<org-mode-map>\
  2250. These are two values, the first applies when first creating a time stamp.
  2251. The second applies when changing it with the commands `S-up' and `S-down'.
  2252. When changing the time stamp, this means that it will change in steps
  2253. of N minutes, as given by the second value.
  2254. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2255. numbers should be factors of 60, so for example 5, 10, 15.
  2256. When this is larger than 1, you can still force an exact time stamp by using
  2257. a double prefix argument to a time stamp command like \
  2258. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2259. and by using a prefix arg to `S-up/down' to specify the exact number
  2260. of minutes to shift."
  2261. :group 'org-time
  2262. :get (lambda (var) ; Make sure both elements are there
  2263. (if (integerp (default-value var))
  2264. (list (default-value var) 5)
  2265. (default-value var)))
  2266. :type '(list
  2267. (integer :tag "when inserting times")
  2268. (integer :tag "when modifying times")))
  2269. ;; Normalize old customizations of this variable.
  2270. (when (integerp org-time-stamp-rounding-minutes)
  2271. (setq org-time-stamp-rounding-minutes
  2272. (list org-time-stamp-rounding-minutes
  2273. org-time-stamp-rounding-minutes)))
  2274. (defcustom org-display-custom-times nil
  2275. "Non-nil means overlay custom formats over all time stamps.
  2276. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2277. To turn this on on a per-file basis, insert anywhere in the file:
  2278. #+STARTUP: customtime"
  2279. :group 'org-time
  2280. :set 'set-default
  2281. :type 'sexp)
  2282. (make-variable-buffer-local 'org-display-custom-times)
  2283. (defcustom org-time-stamp-custom-formats
  2284. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2285. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2286. These are overlaid over the default ISO format if the variable
  2287. `org-display-custom-times' is set. Time like %H:%M should be at the
  2288. end of the second format. The custom formats are also honored by export
  2289. commands, if custom time display is turned on at the time of export."
  2290. :group 'org-time
  2291. :type 'sexp)
  2292. (defun org-time-stamp-format (&optional long inactive)
  2293. "Get the right format for a time string."
  2294. (let ((f (if long (cdr org-time-stamp-formats)
  2295. (car org-time-stamp-formats))))
  2296. (if inactive
  2297. (concat "[" (substring f 1 -1) "]")
  2298. f)))
  2299. (defcustom org-deadline-warning-days 14
  2300. "Number of days before expiration during which a deadline becomes active.
  2301. This variable governs the display in sparse trees and in the agenda.
  2302. When 0 or negative, it means use this number (the absolute value of it)
  2303. even if a deadline has a different individual lead time specified.
  2304. Custom commands can set this variable in the options section."
  2305. :group 'org-time
  2306. :group 'org-agenda-daily/weekly
  2307. :type 'integer)
  2308. (defcustom org-scheduled-delay-days 0
  2309. "Number of days before a scheduled item becomes active.
  2310. This variable governs the display in sparse trees and in the agenda.
  2311. The default value (i.e. 0) means: don't delay scheduled item.
  2312. When negative, it means use this number (the absolute value of it)
  2313. even if a scheduled item has a different individual delay time
  2314. specified.
  2315. Custom commands can set this variable in the options section."
  2316. :group 'org-time
  2317. :group 'org-agenda-daily/weekly
  2318. :version "24.4"
  2319. :package-version '(Org . "8.0")
  2320. :type 'integer)
  2321. (defcustom org-read-date-prefer-future t
  2322. "Non-nil means assume future for incomplete date input from user.
  2323. This affects the following situations:
  2324. 1. The user gives a month but not a year.
  2325. For example, if it is April and you enter \"feb 2\", this will be read
  2326. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2327. 2. The user gives a day, but no month.
  2328. For example, if today is the 15th, and you enter \"3\", Org will read
  2329. this as the third of *next* month. However, if you enter \"17\",
  2330. it will be considered as *this* month.
  2331. If you set this variable to the symbol `time', then also the following
  2332. will work:
  2333. 3. If the user gives a time.
  2334. If the time is before now, it will be interpreted as tomorrow.
  2335. Currently none of this works for ISO week specifications.
  2336. When this option is nil, the current day, month and year will always be
  2337. used as defaults.
  2338. See also `org-agenda-jump-prefer-future'."
  2339. :group 'org-time
  2340. :type '(choice
  2341. (const :tag "Never" nil)
  2342. (const :tag "Check month and day" t)
  2343. (const :tag "Check month, day, and time" time)))
  2344. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2345. "Should the agenda jump command prefer the future for incomplete dates?
  2346. The default is to do the same as configured in `org-read-date-prefer-future'.
  2347. But you can also set a deviating value here.
  2348. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2349. :group 'org-agenda
  2350. :group 'org-time
  2351. :version "24.1"
  2352. :type '(choice
  2353. (const :tag "Use org-read-date-prefer-future"
  2354. org-read-date-prefer-future)
  2355. (const :tag "Never" nil)
  2356. (const :tag "Always" t)))
  2357. (defcustom org-read-date-force-compatible-dates t
  2358. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2359. Depending on the system Emacs is running on, certain dates cannot
  2360. be represented with the type used internally to represent time.
  2361. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2362. correctly. Some systems allow for earlier dates, some for later,
  2363. some for both. One way to find out is to insert any date into an
  2364. Org buffer, putting the cursor on the year and hitting S-up and
  2365. S-down to test the range.
  2366. When this variable is set to t, the date/time prompt will not let
  2367. you specify dates outside the 1970-2037 range, so it is certain that
  2368. these dates will work in whatever version of Emacs you are
  2369. running, and also that you can move a file from one Emacs implementation
  2370. to another. Whenever Org is forcing the year for you, it will display
  2371. a message and beep.
  2372. When this variable is nil, Org will check if the date is
  2373. representable in the specific Emacs implementation you are using.
  2374. If not, it will force a year, usually the current year, and beep
  2375. to remind you. Currently this setting is not recommended because
  2376. the likelihood that you will open your Org files in an Emacs that
  2377. has limited date range is not negligible.
  2378. A workaround for this problem is to use diary sexp dates for time
  2379. stamps outside of this range."
  2380. :group 'org-time
  2381. :version "24.1"
  2382. :type 'boolean)
  2383. (defcustom org-read-date-display-live t
  2384. "Non-nil means display current interpretation of date prompt live.
  2385. This display will be in an overlay, in the minibuffer."
  2386. :group 'org-time
  2387. :type 'boolean)
  2388. (defvaralias 'org-popup-calendar-for-date-prompt
  2389. 'org-read-date-popup-calendar)
  2390. (defcustom org-read-date-popup-calendar t
  2391. "Non-nil means pop up a calendar when prompting for a date.
  2392. In the calendar, the date can be selected with mouse-1. However, the
  2393. minibuffer will also be active, and you can simply enter the date as well.
  2394. When nil, only the minibuffer will be available."
  2395. :group 'org-time
  2396. :type 'boolean)
  2397. (defcustom org-extend-today-until 0
  2398. "The hour when your day really ends. Must be an integer.
  2399. This has influence for the following applications:
  2400. - When switching the agenda to \"today\". It it is still earlier than
  2401. the time given here, the day recognized as TODAY is actually yesterday.
  2402. - When a date is read from the user and it is still before the time given
  2403. here, the current date and time will be assumed to be yesterday, 23:59.
  2404. Also, timestamps inserted in capture templates follow this rule.
  2405. IMPORTANT: This is a feature whose implementation is and likely will
  2406. remain incomplete. Really, it is only here because past midnight seems to
  2407. be the favorite working time of John Wiegley :-)"
  2408. :group 'org-time
  2409. :type 'integer)
  2410. (defcustom org-use-effective-time nil
  2411. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2412. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2413. \"effective time\" of any timestamps between midnight and 8am will be
  2414. 23:59 of the previous day."
  2415. :group 'org-time
  2416. :version "24.1"
  2417. :type 'boolean)
  2418. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2419. "When non-nil, use the last clock out time for `org-todo'.
  2420. Note that this option has precedence over the combined use of
  2421. `org-use-effective-time' and `org-extend-today-until'."
  2422. :group 'org-time
  2423. :version "24.4"
  2424. :package-version '(Org . "8.0")
  2425. :type 'boolean)
  2426. (defcustom org-edit-timestamp-down-means-later nil
  2427. "Non-nil means S-down will increase the time in a time stamp.
  2428. When nil, S-up will increase."
  2429. :group 'org-time
  2430. :type 'boolean)
  2431. (defcustom org-calendar-follow-timestamp-change t
  2432. "Non-nil means make the calendar window follow timestamp changes.
  2433. When a timestamp is modified and the calendar window is visible, it will be
  2434. moved to the new date."
  2435. :group 'org-time
  2436. :type 'boolean)
  2437. (defgroup org-tags nil
  2438. "Options concerning tags in Org mode."
  2439. :tag "Org Tags"
  2440. :group 'org)
  2441. (defcustom org-tag-alist nil
  2442. "Default tags available in Org files.
  2443. The value of this variable is an alist. Associations either:
  2444. (TAG)
  2445. (TAG . SELECT)
  2446. (SPECIAL)
  2447. where TAG is a tag as a string, SELECT is character, used to
  2448. select that tag through the fast tag selection interface, and
  2449. SPECIAL is one of the following keywords: `:startgroup',
  2450. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2451. `:newline'. These keywords are used to define a hierarchy of
  2452. tags. See manual for details.
  2453. When this variable is nil, Org mode bases tag input on what is
  2454. already in the buffer. The value can be overridden locally by
  2455. using a TAGS keyword, e.g.,
  2456. #+TAGS: tag1 tag2
  2457. See also `org-tag-persistent-alist' to sidestep this behavior."
  2458. :group 'org-tags
  2459. :type '(repeat
  2460. (choice
  2461. (cons :tag "Tag with key"
  2462. (string :tag "Tag name")
  2463. (character :tag "Access char"))
  2464. (list :tag "Tag" (string :tag "Tag name"))
  2465. (const :tag "Start radio group" (:startgroup))
  2466. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2467. (const :tag "Group tags delimiter" (:grouptags))
  2468. (const :tag "End radio group" (:endgroup))
  2469. (const :tag "End tag group, non distinct" (:endgrouptag))
  2470. (const :tag "New line" (:newline)))))
  2471. (defcustom org-tag-persistent-alist nil
  2472. "Tags always available in Org files.
  2473. The value of this variable is an alist. Associations either:
  2474. (TAG)
  2475. (TAG . SELECT)
  2476. (SPECIAL)
  2477. where TAG is a tag as a string, SELECT is a character, used to
  2478. select that tag through the fast tag selection interface, and
  2479. SPECIAL is one of the following keywords: `:startgroup',
  2480. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2481. `:newline'. These keywords are used to define a hierarchy of
  2482. tags. See manual for details.
  2483. Unlike to `org-tag-alist', tags defined in this variable do not
  2484. depend on a local TAGS keyword. Instead, to disable these tags
  2485. on a per-file basis, insert anywhere in the file:
  2486. #+STARTUP: noptag"
  2487. :group 'org-tags
  2488. :type '(repeat
  2489. (choice
  2490. (cons :tag "Tag with key"
  2491. (string :tag "Tag name")
  2492. (character :tag "Access char"))
  2493. (list :tag "Tag" (string :tag "Tag name"))
  2494. (const :tag "Start radio group" (:startgroup))
  2495. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2496. (const :tag "Group tags delimiter" (:grouptags))
  2497. (const :tag "End radio group" (:endgroup))
  2498. (const :tag "End tag group, non distinct" (:endgrouptag))
  2499. (const :tag "New line" (:newline)))))
  2500. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2501. "If non-nil, always offer completion for all tags of all agenda files.
  2502. Setting this variable locally allows for dynamic generation of tag
  2503. completions in capture buffers.
  2504. (add-hook \\='org-capture-mode-hook
  2505. (lambda ()
  2506. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2507. :group 'org-tags
  2508. :version "24.1"
  2509. :type 'boolean)
  2510. (defvar org-file-tags nil
  2511. "List of tags that can be inherited by all entries in the file.
  2512. The tags will be inherited if the variable `org-use-tag-inheritance'
  2513. says they should be.
  2514. This variable is populated from #+FILETAGS lines.")
  2515. (defcustom org-use-fast-tag-selection 'auto
  2516. "Non-nil means use fast tag selection scheme.
  2517. This is a special interface to select and deselect tags with single keys.
  2518. When nil, fast selection is never used.
  2519. When the symbol `auto', fast selection is used if and only if selection
  2520. characters for tags have been configured, either through the variable
  2521. `org-tag-alist' or through a #+TAGS line in the buffer.
  2522. When t, fast selection is always used and selection keys are assigned
  2523. automatically if necessary."
  2524. :group 'org-tags
  2525. :type '(choice
  2526. (const :tag "Always" t)
  2527. (const :tag "Never" nil)
  2528. (const :tag "When selection characters are configured" auto)))
  2529. (defcustom org-fast-tag-selection-single-key nil
  2530. "Non-nil means fast tag selection exits after first change.
  2531. When nil, you have to press RET to exit it.
  2532. During fast tag selection, you can toggle this flag with `C-c'.
  2533. This variable can also have the value `expert'. In this case, the window
  2534. displaying the tags menu is not even shown, until you press C-c again."
  2535. :group 'org-tags
  2536. :type '(choice
  2537. (const :tag "No" nil)
  2538. (const :tag "Yes" t)
  2539. (const :tag "Expert" expert)))
  2540. (defvar org-fast-tag-selection-include-todo nil
  2541. "Non-nil means fast tags selection interface will also offer TODO states.
  2542. This is an undocumented feature, you should not rely on it.")
  2543. (defcustom org-tags-column -77
  2544. "The column to which tags should be indented in a headline.
  2545. If this number is positive, it specifies the column. If it is negative,
  2546. it means that the tags should be flushright to that column. For example,
  2547. -80 works well for a normal 80 character screen.
  2548. When 0, place tags directly after headline text, with only one space in
  2549. between."
  2550. :group 'org-tags
  2551. :type 'integer)
  2552. (defcustom org-auto-align-tags t
  2553. "Non-nil keeps tags aligned when modifying headlines.
  2554. Some operations (i.e. demoting) change the length of a headline and
  2555. therefore shift the tags around. With this option turned on, after
  2556. each such operation the tags are again aligned to `org-tags-column'."
  2557. :group 'org-tags
  2558. :type 'boolean)
  2559. (defcustom org-use-tag-inheritance t
  2560. "Non-nil means tags in levels apply also for sublevels.
  2561. When nil, only the tags directly given in a specific line apply there.
  2562. This may also be a list of tags that should be inherited, or a regexp that
  2563. matches tags that should be inherited. Additional control is possible
  2564. with the variable `org-tags-exclude-from-inheritance' which gives an
  2565. explicit list of tags to be excluded from inheritance, even if the value of
  2566. `org-use-tag-inheritance' would select it for inheritance.
  2567. If this option is t, a match early-on in a tree can lead to a large
  2568. number of matches in the subtree when constructing the agenda or creating
  2569. a sparse tree. If you only want to see the first match in a tree during
  2570. a search, check out the variable `org-tags-match-list-sublevels'."
  2571. :group 'org-tags
  2572. :type '(choice
  2573. (const :tag "Not" nil)
  2574. (const :tag "Always" t)
  2575. (repeat :tag "Specific tags" (string :tag "Tag"))
  2576. (regexp :tag "Tags matched by regexp")))
  2577. (defcustom org-tags-exclude-from-inheritance nil
  2578. "List of tags that should never be inherited.
  2579. This is a way to exclude a few tags from inheritance. For way to do
  2580. the opposite, to actively allow inheritance for selected tags,
  2581. see the variable `org-use-tag-inheritance'."
  2582. :group 'org-tags
  2583. :type '(repeat (string :tag "Tag")))
  2584. (defun org-tag-inherit-p (tag)
  2585. "Check if TAG is one that should be inherited."
  2586. (cond
  2587. ((member tag org-tags-exclude-from-inheritance) nil)
  2588. ((eq org-use-tag-inheritance t) t)
  2589. ((not org-use-tag-inheritance) nil)
  2590. ((stringp org-use-tag-inheritance)
  2591. (string-match org-use-tag-inheritance tag))
  2592. ((listp org-use-tag-inheritance)
  2593. (member tag org-use-tag-inheritance))
  2594. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2595. (defcustom org-tags-match-list-sublevels t
  2596. "Non-nil means list also sublevels of headlines matching a search.
  2597. This variable applies to tags/property searches, and also to stuck
  2598. projects because this search is based on a tags match as well.
  2599. When set to the symbol `indented', sublevels are indented with
  2600. leading dots.
  2601. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2602. the sublevels of a headline matching a tag search often also match
  2603. the same search. Listing all of them can create very long lists.
  2604. Setting this variable to nil causes subtrees of a match to be skipped.
  2605. This variable is semi-obsolete and probably should always be true. It
  2606. is better to limit inheritance to certain tags using the variables
  2607. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2608. :group 'org-tags
  2609. :type '(choice
  2610. (const :tag "No, don't list them" nil)
  2611. (const :tag "Yes, do list them" t)
  2612. (const :tag "List them, indented with leading dots" indented)))
  2613. (defcustom org-tags-sort-function nil
  2614. "When set, tags are sorted using this function as a comparator."
  2615. :group 'org-tags
  2616. :type '(choice
  2617. (const :tag "No sorting" nil)
  2618. (const :tag "Alphabetical" org-string-collate-lessp)
  2619. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2620. (function :tag "Custom function" nil)))
  2621. (defvar org-tags-history nil
  2622. "History of minibuffer reads for tags.")
  2623. (defvar org-last-tags-completion-table nil
  2624. "The last used completion table for tags.")
  2625. (defvar org-after-tags-change-hook nil
  2626. "Hook that is run after the tags in a line have changed.")
  2627. (defgroup org-properties nil
  2628. "Options concerning properties in Org mode."
  2629. :tag "Org Properties"
  2630. :group 'org)
  2631. (defcustom org-property-format "%-10s %s"
  2632. "How property key/value pairs should be formatted by `indent-line'.
  2633. When `indent-line' hits a property definition, it will format the line
  2634. according to this format, mainly to make sure that the values are
  2635. lined-up with respect to each other."
  2636. :group 'org-properties
  2637. :type 'string)
  2638. (defcustom org-properties-postprocess-alist nil
  2639. "Alist of properties and functions to adjust inserted values.
  2640. Elements of this alist must be of the form
  2641. ([string] [function])
  2642. where [string] must be a property name and [function] must be a
  2643. lambda expression: this lambda expression must take one argument,
  2644. the value to adjust, and return the new value as a string.
  2645. For example, this element will allow the property \"Remaining\"
  2646. to be updated wrt the relation between the \"Effort\" property
  2647. and the clock summary:
  2648. ((\"Remaining\" (lambda(value)
  2649. (let ((clocksum (org-clock-sum-current-item))
  2650. (effort (org-duration-to-minutes
  2651. (org-entry-get (point) \"Effort\"))))
  2652. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2653. :group 'org-properties
  2654. :version "24.1"
  2655. :type '(alist :key-type (string :tag "Property")
  2656. :value-type (function :tag "Function")))
  2657. (defcustom org-use-property-inheritance nil
  2658. "Non-nil means properties apply also for sublevels.
  2659. This setting is chiefly used during property searches. Turning it on can
  2660. cause significant overhead when doing a search, which is why it is not
  2661. on by default.
  2662. When nil, only the properties directly given in the current entry count.
  2663. When t, every property is inherited. The value may also be a list of
  2664. properties that should have inheritance, or a regular expression matching
  2665. properties that should be inherited.
  2666. However, note that some special properties use inheritance under special
  2667. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2668. and the properties ending in \"_ALL\" when they are used as descriptor
  2669. for valid values of a property.
  2670. Note for programmers:
  2671. When querying an entry with `org-entry-get', you can control if inheritance
  2672. should be used. By default, `org-entry-get' looks only at the local
  2673. properties. You can request inheritance by setting the inherit argument
  2674. to t (to force inheritance) or to `selective' (to respect the setting
  2675. in this variable)."
  2676. :group 'org-properties
  2677. :type '(choice
  2678. (const :tag "Not" nil)
  2679. (const :tag "Always" t)
  2680. (repeat :tag "Specific properties" (string :tag "Property"))
  2681. (regexp :tag "Properties matched by regexp")))
  2682. (defun org-property-inherit-p (property)
  2683. "Return a non-nil value if PROPERTY should be inherited."
  2684. (cond
  2685. ((eq org-use-property-inheritance t) t)
  2686. ((not org-use-property-inheritance) nil)
  2687. ((stringp org-use-property-inheritance)
  2688. (string-match org-use-property-inheritance property))
  2689. ((listp org-use-property-inheritance)
  2690. (member-ignore-case property org-use-property-inheritance))
  2691. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2692. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2693. "The default column format, if no other format has been defined.
  2694. This variable can be set on the per-file basis by inserting a line
  2695. #+COLUMNS: %25ITEM ....."
  2696. :group 'org-properties
  2697. :type 'string)
  2698. (defcustom org-columns-default-format-for-agenda nil
  2699. "The default column format in an agenda buffer.
  2700. Whis will be used for column view in the agenda unless a format has
  2701. been set by adding `org-overriding-columns-format' to the local
  2702. settings list of a custom agenda view. When nil, the columns format
  2703. for the first item in the agenda list will be used, or as a fall-back,
  2704. `org-columns-default-format'."
  2705. :group 'org-properties
  2706. :type '(choice
  2707. (const :tag "No default" nil)
  2708. (string :tag "Format string")))
  2709. (defcustom org-columns-ellipses ".."
  2710. "The ellipses to be used when a field in column view is truncated.
  2711. When this is the empty string, as many characters as possible are shown,
  2712. but then there will be no visual indication that the field has been truncated.
  2713. When this is a string of length N, the last N characters of a truncated
  2714. field are replaced by this string. If the column is narrower than the
  2715. ellipses string, only part of the ellipses string will be shown."
  2716. :group 'org-properties
  2717. :type 'string)
  2718. (defconst org-global-properties-fixed
  2719. '(("VISIBILITY_ALL" . "folded children content all")
  2720. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2721. "List of property/value pairs that can be inherited by any entry.
  2722. These are fixed values, for the preset properties. The user variable
  2723. that can be used to add to this list is `org-global-properties'.
  2724. The entries in this list are cons cells where the car is a property
  2725. name and cdr is a string with the value. If the value represents
  2726. multiple items like an \"_ALL\" property, separate the items by
  2727. spaces.")
  2728. (defcustom org-global-properties nil
  2729. "List of property/value pairs that can be inherited by any entry.
  2730. This list will be combined with the constant `org-global-properties-fixed'.
  2731. The entries in this list are cons cells where the car is a property
  2732. name and cdr is a string with the value.
  2733. You can set buffer-local values for the same purpose in the variable
  2734. `org-file-properties' this by adding lines like
  2735. #+PROPERTY: NAME VALUE"
  2736. :group 'org-properties
  2737. :type '(repeat
  2738. (cons (string :tag "Property")
  2739. (string :tag "Value"))))
  2740. (defvar-local org-file-properties nil
  2741. "List of property/value pairs that can be inherited by any entry.
  2742. Valid for the current buffer.
  2743. This variable is populated from #+PROPERTY lines.")
  2744. (defgroup org-agenda nil
  2745. "Options concerning agenda views in Org mode."
  2746. :tag "Org Agenda"
  2747. :group 'org)
  2748. (defvar-local org-category nil
  2749. "Variable used by Org files to set a category for agenda display.
  2750. Such files should use a file variable to set it, for example
  2751. # -*- mode: org; org-category: \"ELisp\"
  2752. or contain a special line
  2753. #+CATEGORY: ELisp
  2754. If the file does not specify a category, then file's base name
  2755. is used instead.")
  2756. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2757. (defcustom org-agenda-files nil
  2758. "The files to be used for agenda display.
  2759. If an entry is a directory, all files in that directory that are matched
  2760. by `org-agenda-file-regexp' will be part of the file list.
  2761. If the value of the variable is not a list but a single file name, then
  2762. the list of agenda files is actually stored and maintained in that file,
  2763. one agenda file per line. In this file paths can be given relative to
  2764. `org-directory'. Tilde expansion and environment variable substitution
  2765. are also made.
  2766. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2767. and removed with `\\[org-remove-file]'."
  2768. :group 'org-agenda
  2769. :type '(choice
  2770. (repeat :tag "List of files and directories" file)
  2771. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2772. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2773. "Regular expression to match files for `org-agenda-files'.
  2774. If any element in the list in that variable contains a directory instead
  2775. of a normal file, all files in that directory that are matched by this
  2776. regular expression will be included."
  2777. :group 'org-agenda
  2778. :type 'regexp)
  2779. (defvaralias 'org-agenda-multi-occur-extra-files
  2780. 'org-agenda-text-search-extra-files)
  2781. (defcustom org-agenda-text-search-extra-files nil
  2782. "List of extra files to be searched by text search commands.
  2783. These files will be searched in addition to the agenda files by the
  2784. commands `org-search-view' (`\\[org-agenda] s') \
  2785. and `org-occur-in-agenda-files'.
  2786. Note that these files will only be searched for text search commands,
  2787. not for the other agenda views like todo lists, tag searches or the weekly
  2788. agenda. This variable is intended to list notes and possibly archive files
  2789. that should also be searched by these two commands.
  2790. In fact, if the first element in the list is the symbol `agenda-archives',
  2791. then all archive files of all agenda files will be added to the search
  2792. scope."
  2793. :group 'org-agenda
  2794. :type '(set :greedy t
  2795. (const :tag "Agenda Archives" agenda-archives)
  2796. (repeat :inline t (file))))
  2797. (defcustom org-agenda-skip-unavailable-files nil
  2798. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2799. A nil value means to remove them, after a query, from the list."
  2800. :group 'org-agenda
  2801. :type 'boolean)
  2802. (defcustom org-agenda-diary-file 'diary-file
  2803. "File to which to add new entries with the `i' key in agenda and calendar.
  2804. When this is the symbol `diary-file', the functionality in the Emacs
  2805. calendar will be used to add entries to the `diary-file'. But when this
  2806. points to a file, `org-agenda-diary-entry' will be used instead."
  2807. :group 'org-agenda
  2808. :type '(choice
  2809. (const :tag "The standard Emacs diary file" diary-file)
  2810. (file :tag "Special Org file diary entries")))
  2811. (defgroup org-latex nil
  2812. "Options for embedding LaTeX code into Org mode."
  2813. :tag "Org LaTeX"
  2814. :group 'org)
  2815. (defcustom org-format-latex-options
  2816. '(:foreground default :background default :scale 1.0
  2817. :html-foreground "Black" :html-background "Transparent"
  2818. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2819. "Options for creating images from LaTeX fragments.
  2820. This is a property list with the following properties:
  2821. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2822. `default' means use the foreground of the default face.
  2823. `auto' means use the foreground from the text face.
  2824. :background the background color, or \"Transparent\".
  2825. `default' means use the background of the default face.
  2826. `auto' means use the background from the text face.
  2827. :scale a scaling factor for the size of the images, to get more pixels
  2828. :html-foreground, :html-background, :html-scale
  2829. the same numbers for HTML export.
  2830. :matchers a list indicating which matchers should be used to
  2831. find LaTeX fragments. Valid members of this list are:
  2832. \"begin\" find environments
  2833. \"$1\" find single characters surrounded by $.$
  2834. \"$\" find math expressions surrounded by $...$
  2835. \"$$\" find math expressions surrounded by $$....$$
  2836. \"\\(\" find math expressions surrounded by \\(...\\)
  2837. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2838. :group 'org-latex
  2839. :type 'plist)
  2840. (defcustom org-format-latex-signal-error t
  2841. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2842. When nil, just push out a message."
  2843. :group 'org-latex
  2844. :version "24.1"
  2845. :type 'boolean)
  2846. (defcustom org-latex-to-mathml-jar-file nil
  2847. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2848. Use this to specify additional executable file say a jar file.
  2849. When using MathToWeb as the converter, specify the full-path to
  2850. your mathtoweb.jar file."
  2851. :group 'org-latex
  2852. :version "24.1"
  2853. :type '(choice
  2854. (const :tag "None" nil)
  2855. (file :tag "JAR file" :must-match t)))
  2856. (defcustom org-latex-to-mathml-convert-command nil
  2857. "Command to convert LaTeX fragments to MathML.
  2858. Replace format-specifiers in the command as noted below and use
  2859. `shell-command' to convert LaTeX to MathML.
  2860. %j: Executable file in fully expanded form as specified by
  2861. `org-latex-to-mathml-jar-file'.
  2862. %I: Input LaTeX file in fully expanded form.
  2863. %i: The latex fragment to be converted.
  2864. %o: Output MathML file.
  2865. This command is used by `org-create-math-formula'.
  2866. When using MathToWeb as the converter, set this option to
  2867. \"java -jar %j -unicode -force -df %o %I\".
  2868. When using LaTeXML set this option to
  2869. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2870. :group 'org-latex
  2871. :version "24.1"
  2872. :type '(choice
  2873. (const :tag "None" nil)
  2874. (string :tag "\nShell command")))
  2875. (defcustom org-preview-latex-default-process 'dvipng
  2876. "The default process to convert LaTeX fragments to image files.
  2877. All available processes and theirs documents can be found in
  2878. `org-preview-latex-process-alist', which see."
  2879. :group 'org-latex
  2880. :version "26.1"
  2881. :package-version '(Org . "9.0")
  2882. :type 'symbol)
  2883. (defcustom org-preview-latex-process-alist
  2884. '((dvipng
  2885. :programs ("latex" "dvipng")
  2886. :description "dvi > png"
  2887. :message "you need to install the programs: latex and dvipng."
  2888. :image-input-type "dvi"
  2889. :image-output-type "png"
  2890. :image-size-adjust (1.0 . 1.0)
  2891. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2892. :image-converter ("dvipng -D %D -T tight -o %O %f"))
  2893. (dvisvgm
  2894. :programs ("latex" "dvisvgm")
  2895. :description "dvi > svg"
  2896. :message "you need to install the programs: latex and dvisvgm."
  2897. :image-input-type "dvi"
  2898. :image-output-type "svg"
  2899. :image-size-adjust (1.7 . 1.5)
  2900. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2901. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2902. (imagemagick
  2903. :programs ("latex" "convert")
  2904. :description "pdf > png"
  2905. :message "you need to install the programs: latex and imagemagick."
  2906. :image-input-type "pdf"
  2907. :image-output-type "png"
  2908. :image-size-adjust (1.0 . 1.0)
  2909. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2910. :image-converter
  2911. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2912. "Definitions of external processes for LaTeX previewing.
  2913. Org mode can use some external commands to generate TeX snippet's images for
  2914. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2915. `org-create-formula-image' how to call them.
  2916. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2917. PROPERTIES accepts the following attributes:
  2918. :programs list of strings, required programs.
  2919. :description string, describe the process.
  2920. :message string, message it when required programs cannot be found.
  2921. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2922. :image-output-type string, output file type of image converter (e.g., \"png\").
  2923. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2924. image size showed in buffer and the cdr element is for
  2925. HTML file. This option is only useful for process
  2926. developers, users should use variable
  2927. `org-format-latex-options' instead.
  2928. :post-clean list of strings, files matched are to be cleaned up once
  2929. the image is generated. When nil, the files with \".dvi\",
  2930. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2931. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2932. be cleaned up.
  2933. :latex-header list of strings, the LaTeX header of the snippet file.
  2934. When nil, the fallback value is used instead, which is
  2935. controlled by `org-format-latex-header',
  2936. `org-latex-default-packages-alist' and
  2937. `org-latex-packages-alist', which see.
  2938. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2939. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2940. replaced with values defined below.
  2941. :image-converter list of image converter commands strings. Each of them is
  2942. given to the shell and supports any of the following
  2943. place-holders defined below.
  2944. Place-holders used by `:image-converter' and `:latex-compiler':
  2945. %f input file name
  2946. %b base name of input file
  2947. %o base directory of input file
  2948. %O absolute output file name
  2949. Place-holders only used by `:image-converter':
  2950. %D dpi, which is used to adjust image size by some processing commands.
  2951. %S the image size scale ratio, which is used to adjust image size by some
  2952. processing commands."
  2953. :group 'org-latex
  2954. :version "26.1"
  2955. :package-version '(Org . "9.0")
  2956. :type '(alist :tag "LaTeX to image backends"
  2957. :value-type (plist)))
  2958. (defcustom org-preview-latex-image-directory "ltximg/"
  2959. "Path to store latex preview images.
  2960. A relative path here creates many directories relative to the
  2961. processed Org files paths. An absolute path puts all preview
  2962. images at the same place."
  2963. :group 'org-latex
  2964. :version "26.1"
  2965. :package-version '(Org . "9.0")
  2966. :type 'string)
  2967. (defun org-format-latex-mathml-available-p ()
  2968. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2969. (save-match-data
  2970. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2971. org-latex-to-mathml-convert-command)
  2972. (let ((executable (car (split-string
  2973. org-latex-to-mathml-convert-command))))
  2974. (when (executable-find executable)
  2975. (if (string-match
  2976. "%j" org-latex-to-mathml-convert-command)
  2977. (file-readable-p org-latex-to-mathml-jar-file)
  2978. t))))))
  2979. (defcustom org-format-latex-header "\\documentclass{article}
  2980. \\usepackage[usenames]{color}
  2981. \[PACKAGES]
  2982. \[DEFAULT-PACKAGES]
  2983. \\pagestyle{empty} % do not remove
  2984. % The settings below are copied from fullpage.sty
  2985. \\setlength{\\textwidth}{\\paperwidth}
  2986. \\addtolength{\\textwidth}{-3cm}
  2987. \\setlength{\\oddsidemargin}{1.5cm}
  2988. \\addtolength{\\oddsidemargin}{-2.54cm}
  2989. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2990. \\setlength{\\textheight}{\\paperheight}
  2991. \\addtolength{\\textheight}{-\\headheight}
  2992. \\addtolength{\\textheight}{-\\headsep}
  2993. \\addtolength{\\textheight}{-\\footskip}
  2994. \\addtolength{\\textheight}{-3cm}
  2995. \\setlength{\\topmargin}{1.5cm}
  2996. \\addtolength{\\topmargin}{-2.54cm}"
  2997. "The document header used for processing LaTeX fragments.
  2998. It is imperative that this header make sure that no page number
  2999. appears on the page. The package defined in the variables
  3000. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3001. will either replace the placeholder \"[PACKAGES]\" in this
  3002. header, or they will be appended."
  3003. :group 'org-latex
  3004. :type 'string)
  3005. (defun org-set-packages-alist (var val)
  3006. "Set the packages alist and make sure it has 3 elements per entry."
  3007. (set var (mapcar (lambda (x)
  3008. (if (and (consp x) (= (length x) 2))
  3009. (list (car x) (nth 1 x) t)
  3010. x))
  3011. val)))
  3012. (defun org-get-packages-alist (var)
  3013. "Get the packages alist and make sure it has 3 elements per entry."
  3014. (mapcar (lambda (x)
  3015. (if (and (consp x) (= (length x) 2))
  3016. (list (car x) (nth 1 x) t)
  3017. x))
  3018. (default-value var)))
  3019. (defcustom org-latex-default-packages-alist
  3020. '(("AUTO" "inputenc" t ("pdflatex"))
  3021. ("T1" "fontenc" t ("pdflatex"))
  3022. ("" "graphicx" t)
  3023. ("" "grffile" t)
  3024. ("" "longtable" nil)
  3025. ("" "wrapfig" nil)
  3026. ("" "rotating" nil)
  3027. ("normalem" "ulem" t)
  3028. ("" "amsmath" t)
  3029. ("" "textcomp" t)
  3030. ("" "amssymb" t)
  3031. ("" "capt-of" nil)
  3032. ("" "hyperref" nil))
  3033. "Alist of default packages to be inserted in the header.
  3034. Change this only if one of the packages here causes an
  3035. incompatibility with another package you are using.
  3036. The packages in this list are needed by one part or another of
  3037. Org mode to function properly:
  3038. - inputenc, fontenc: for basic font and character selection
  3039. - graphicx: for including images
  3040. - grffile: allow periods and spaces in graphics file names
  3041. - longtable: For multipage tables
  3042. - wrapfig: for figure placement
  3043. - rotating: for sideways figures and tables
  3044. - ulem: for underline and strike-through
  3045. - amsmath: for subscript and superscript and math environments
  3046. - textcomp, amssymb: for various symbols used
  3047. for interpreting the entities in `org-entities'. You can skip
  3048. some of these packages if you don't use any of their symbols.
  3049. - capt-of: for captions outside of floats
  3050. - hyperref: for cross references
  3051. Therefore you should not modify this variable unless you know
  3052. what you are doing. The one reason to change it anyway is that
  3053. you might be loading some other package that conflicts with one
  3054. of the default packages. Each element is either a cell or
  3055. a string.
  3056. A cell is of the format
  3057. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3058. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3059. when compiling LaTeX snippets into images for inclusion into
  3060. non-LaTeX output.
  3061. COMPILERS is a list of compilers that should include the package,
  3062. see `org-latex-compiler'. If the document compiler is not in the
  3063. list, and the list is non-nil, the package will not be inserted
  3064. in the final document.
  3065. A string will be inserted as-is in the header of the document."
  3066. :group 'org-latex
  3067. :group 'org-export-latex
  3068. :set 'org-set-packages-alist
  3069. :get 'org-get-packages-alist
  3070. :version "26.1"
  3071. :package-version '(Org . "8.3")
  3072. :type '(repeat
  3073. (choice
  3074. (list :tag "options/package pair"
  3075. (string :tag "options")
  3076. (string :tag "package")
  3077. (boolean :tag "Snippet")
  3078. (choice
  3079. (const :tag "For all compilers" nil)
  3080. (repeat :tag "Allowed compiler" string)))
  3081. (string :tag "A line of LaTeX"))))
  3082. (defcustom org-latex-packages-alist nil
  3083. "Alist of packages to be inserted in every LaTeX header.
  3084. These will be inserted after `org-latex-default-packages-alist'.
  3085. Each element is either a cell or a string.
  3086. A cell is of the format:
  3087. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3088. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3089. needed when turning LaTeX snippets into images for inclusion into
  3090. non-LaTeX output.
  3091. COMPILERS is a list of compilers that should include the package,
  3092. see `org-latex-compiler'. If the document compiler is not in the
  3093. list, and the list is non-nil, the package will not be inserted
  3094. in the final document.
  3095. A string will be inserted as-is in the header of the document.
  3096. Make sure that you only list packages here which:
  3097. - you want in every file;
  3098. - do not conflict with the setup in `org-format-latex-header';
  3099. - do not conflict with the default packages in
  3100. `org-latex-default-packages-alist'."
  3101. :group 'org-latex
  3102. :group 'org-export-latex
  3103. :set 'org-set-packages-alist
  3104. :get 'org-get-packages-alist
  3105. :type '(repeat
  3106. (choice
  3107. (list :tag "options/package pair"
  3108. (string :tag "options")
  3109. (string :tag "package")
  3110. (boolean :tag "Snippet"))
  3111. (string :tag "A line of LaTeX"))))
  3112. (defgroup org-appearance nil
  3113. "Settings for Org mode appearance."
  3114. :tag "Org Appearance"
  3115. :group 'org)
  3116. (defcustom org-level-color-stars-only nil
  3117. "Non-nil means fontify only the stars in each headline.
  3118. When nil, the entire headline is fontified.
  3119. Changing it requires restart of `font-lock-mode' to become effective
  3120. also in regions already fontified."
  3121. :group 'org-appearance
  3122. :type 'boolean)
  3123. (defcustom org-hide-leading-stars nil
  3124. "Non-nil means hide the first N-1 stars in a headline.
  3125. This works by using the face `org-hide' for these stars. This
  3126. face is white for a light background, and black for a dark
  3127. background. You may have to customize the face `org-hide' to
  3128. make this work.
  3129. Changing it requires restart of `font-lock-mode' to become effective
  3130. also in regions already fontified.
  3131. You may also set this on a per-file basis by adding one of the following
  3132. lines to the buffer:
  3133. #+STARTUP: hidestars
  3134. #+STARTUP: showstars"
  3135. :group 'org-appearance
  3136. :type 'boolean)
  3137. (defcustom org-hidden-keywords nil
  3138. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3139. For example, a value \\='(title) for this list makes the document's title
  3140. appear in the buffer without the initial \"#+TITLE:\" part."
  3141. :group 'org-appearance
  3142. :version "24.1"
  3143. :type '(set (const :tag "#+AUTHOR" author)
  3144. (const :tag "#+DATE" date)
  3145. (const :tag "#+EMAIL" email)
  3146. (const :tag "#+TITLE" title)))
  3147. (defcustom org-custom-properties nil
  3148. "List of properties (as strings) with a special meaning.
  3149. The default use of these custom properties is to let the user
  3150. hide them with `org-toggle-custom-properties-visibility'."
  3151. :group 'org-properties
  3152. :group 'org-appearance
  3153. :version "24.3"
  3154. :type '(repeat (string :tag "Property Name")))
  3155. (defcustom org-fontify-done-headline nil
  3156. "Non-nil means change the face of a headline if it is marked DONE.
  3157. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3158. When this is non-nil, the headline after the keyword is set to the
  3159. `org-headline-done' as an additional indication."
  3160. :group 'org-appearance
  3161. :type 'boolean)
  3162. (defcustom org-fontify-emphasized-text t
  3163. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3164. Changing this variable requires a restart of Emacs to take effect."
  3165. :group 'org-appearance
  3166. :type 'boolean)
  3167. (defcustom org-fontify-whole-heading-line nil
  3168. "Non-nil means fontify the whole line for headings.
  3169. This is useful when setting a background color for the
  3170. org-level-* faces."
  3171. :group 'org-appearance
  3172. :type 'boolean)
  3173. (defcustom org-fontify-whole-block-delimiter-line t
  3174. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3175. This is useful when setting a background color for the
  3176. org-block-begin-line and org-block-end-line faces."
  3177. :group 'org-appearance
  3178. :type 'boolean)
  3179. (defcustom org-highlight-latex-and-related nil
  3180. "Non-nil means highlight LaTeX related syntax in the buffer.
  3181. When non nil, the value should be a list containing any of the
  3182. following symbols:
  3183. `native' Highlight LaTeX snippets and environments natively.
  3184. `latex' Highlight LaTeX snippets and environments.
  3185. `script' Highlight subscript and superscript.
  3186. `entities' Highlight entities."
  3187. :group 'org-appearance
  3188. :version "24.4"
  3189. :package-version '(Org . "8.0")
  3190. :type '(choice
  3191. (const :tag "No highlighting" nil)
  3192. (set :greedy t :tag "Highlight"
  3193. (const :tag "LaTeX snippets and environments (native)" native)
  3194. (const :tag "LaTeX snippets and environments" latex)
  3195. (const :tag "Subscript and superscript" script)
  3196. (const :tag "Entities" entities))))
  3197. (defcustom org-hide-emphasis-markers nil
  3198. "Non-nil mean font-lock should hide the emphasis marker characters."
  3199. :group 'org-appearance
  3200. :type 'boolean
  3201. :safe #'booleanp)
  3202. (defcustom org-hide-macro-markers nil
  3203. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3204. :group 'org-appearance
  3205. :type 'boolean)
  3206. (defcustom org-pretty-entities nil
  3207. "Non-nil means show entities as UTF8 characters.
  3208. When nil, the \\name form remains in the buffer."
  3209. :group 'org-appearance
  3210. :version "24.1"
  3211. :type 'boolean)
  3212. (defcustom org-pretty-entities-include-sub-superscripts t
  3213. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3214. :group 'org-appearance
  3215. :version "24.1"
  3216. :type 'boolean)
  3217. (defvar org-emph-re nil
  3218. "Regular expression for matching emphasis.
  3219. After a match, the match groups contain these elements:
  3220. 0 The match of the full regular expression, including the characters
  3221. before and after the proper match
  3222. 1 The character before the proper match, or empty at beginning of line
  3223. 2 The proper match, including the leading and trailing markers
  3224. 3 The leading marker like * or /, indicating the type of highlighting
  3225. 4 The text between the emphasis markers, not including the markers
  3226. 5 The character after the match, empty at the end of a line")
  3227. (defvar org-verbatim-re nil
  3228. "Regular expression for matching verbatim text.")
  3229. (defvar org-emphasis-regexp-components) ; defined just below
  3230. (defvar org-emphasis-alist) ; defined just below
  3231. (defun org-set-emph-re (var val)
  3232. "Set variable and compute the emphasis regular expression."
  3233. (set var val)
  3234. (when (and (boundp 'org-emphasis-alist)
  3235. (boundp 'org-emphasis-regexp-components)
  3236. org-emphasis-alist org-emphasis-regexp-components)
  3237. (pcase-let*
  3238. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3239. (body (if (<= nl 0) body
  3240. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3241. (template
  3242. (format (concat "\\([%s]\\|^\\)" ;before markers
  3243. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3244. "\\([%s]\\|$\\)") ;after markers
  3245. pre border border body border post)))
  3246. (setq org-emph-re (format template "*/_+"))
  3247. (setq org-verbatim-re (format template "=~")))))
  3248. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3249. ;; set this option proved cumbersome. See this message/thread:
  3250. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3251. (defvar org-emphasis-regexp-components
  3252. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3253. "Components used to build the regular expression for emphasis.
  3254. This is a list with five entries. Terminology: In an emphasis string
  3255. like \" *strong word* \", we call the initial space PREMATCH, the final
  3256. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3257. and \"trong wor\" is the body. The different components in this variable
  3258. specify what is allowed/forbidden in each part:
  3259. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3260. post Chars allowed as postmatch. End of line will be allowed too.
  3261. border The chars *forbidden* as border characters.
  3262. body-regexp A regexp like \".\" to match a body character. Don't use
  3263. non-shy groups here, and don't allow newline here.
  3264. newline The maximum number of newlines allowed in an emphasis exp.
  3265. You need to reload Org or to restart Emacs after setting this.")
  3266. (defcustom org-emphasis-alist
  3267. '(("*" bold)
  3268. ("/" italic)
  3269. ("_" underline)
  3270. ("=" org-verbatim verbatim)
  3271. ("~" org-code verbatim)
  3272. ("+" (:strike-through t)))
  3273. "Alist of characters and faces to emphasize text.
  3274. Text starting and ending with a special character will be emphasized,
  3275. for example *bold*, _underlined_ and /italic/. This variable sets the
  3276. marker characters and the face to be used by font-lock for highlighting
  3277. in Org buffers.
  3278. You need to reload Org or to restart Emacs after customizing this."
  3279. :group 'org-appearance
  3280. :set 'org-set-emph-re
  3281. :version "24.4"
  3282. :package-version '(Org . "8.0")
  3283. :type '(repeat
  3284. (list
  3285. (string :tag "Marker character")
  3286. (choice
  3287. (face :tag "Font-lock-face")
  3288. (plist :tag "Face property list"))
  3289. (option (const verbatim)))))
  3290. (defvar org-protecting-blocks '("src" "example" "export")
  3291. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3292. This is needed for font-lock setup.")
  3293. ;;; Functions and variables from their packages
  3294. ;; Declared here to avoid compiler warnings
  3295. (defvar mark-active)
  3296. ;; Various packages
  3297. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3298. (declare-function calendar-forward-day "cal-move" (arg))
  3299. (declare-function calendar-goto-date "cal-move" (date))
  3300. (declare-function calendar-goto-today "cal-move" ())
  3301. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3302. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3303. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3304. (declare-function cdlatex-tab "ext:cdlatex" ())
  3305. (declare-function dired-get-filename
  3306. "dired"
  3307. (&optional localp no-error-if-not-filep))
  3308. (declare-function iswitchb-read-buffer
  3309. "iswitchb"
  3310. (prompt &optional
  3311. default require-match _predicate start matches-set))
  3312. (declare-function org-agenda-change-all-lines
  3313. "org-agenda"
  3314. (newhead hdmarker &optional fixface just-this))
  3315. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3316. "org-agenda"
  3317. (&optional end))
  3318. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3319. (declare-function org-agenda-format-item
  3320. "org-agenda"
  3321. (extra txt &optional level category tags dotime
  3322. remove-re habitp))
  3323. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3324. (declare-function org-agenda-save-markers-for-cut-and-paste
  3325. "org-agenda"
  3326. (beg end))
  3327. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3328. (declare-function org-agenda-skip "org-agenda" ())
  3329. (declare-function org-attach-expand "org-attach" (file))
  3330. (declare-function org-attach-reveal "org-attach" ())
  3331. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3332. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3333. (declare-function org-indent-mode "org-indent" (&optional arg))
  3334. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3335. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3336. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3337. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3338. (declare-function parse-time-string "parse-time" (string))
  3339. (defvar align-mode-rules-list)
  3340. (defvar calc-embedded-close-formula)
  3341. (defvar calc-embedded-open-formula)
  3342. (defvar calc-embedded-open-mode)
  3343. (defvar font-lock-unfontify-region-function)
  3344. (defvar iswitchb-temp-buflist)
  3345. (defvar org-agenda-tags-todo-honor-ignore-options)
  3346. (defvar remember-data-file)
  3347. (defvar texmathp-why)
  3348. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3349. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3350. (declare-function org-resolve-clocks "org-clock"
  3351. (&optional also-non-dangling-p prompt last-valid))
  3352. (defvar org-clock-start-time)
  3353. (defvar org-clock-marker (make-marker)
  3354. "Marker recording the last clock-in.")
  3355. (defvar org-clock-hd-marker (make-marker)
  3356. "Marker recording the last clock-in, but the headline position.")
  3357. (defvar org-clock-heading ""
  3358. "The heading of the current clock entry.")
  3359. (defun org-clock-is-active ()
  3360. "Return the buffer where the clock is currently running.
  3361. Return nil if no clock is running."
  3362. (marker-buffer org-clock-marker))
  3363. (defun org-check-running-clock ()
  3364. "Check if the current buffer contains the running clock.
  3365. If yes, offer to stop it and to save the buffer with the changes."
  3366. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3367. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3368. (buffer-name))))
  3369. (org-clock-out)
  3370. (when (y-or-n-p "Save changed buffer?")
  3371. (save-buffer))))
  3372. (defun org-clocktable-try-shift (dir n)
  3373. "Check if this line starts a clock table, if yes, shift the time block."
  3374. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3375. (org-clocktable-shift dir n)))
  3376. ;;;###autoload
  3377. (defun org-clock-persistence-insinuate ()
  3378. "Set up hooks for clock persistence."
  3379. (require 'org-clock)
  3380. (add-hook 'org-mode-hook 'org-clock-load)
  3381. (add-hook 'kill-emacs-hook 'org-clock-save))
  3382. (defgroup org-archive nil
  3383. "Options concerning archiving in Org mode."
  3384. :tag "Org Archive"
  3385. :group 'org-structure)
  3386. (defcustom org-archive-location "%s_archive::"
  3387. "The location where subtrees should be archived.
  3388. The value of this variable is a string, consisting of two parts,
  3389. separated by a double-colon. The first part is a filename and
  3390. the second part is a headline.
  3391. When the filename is omitted, archiving happens in the same file.
  3392. %s in the filename will be replaced by the current file
  3393. name (without the directory part). Archiving to a different file
  3394. is useful to keep archived entries from contributing to the
  3395. Org Agenda.
  3396. The archived entries will be filed as subtrees of the specified
  3397. headline. When the headline is omitted, the subtrees are simply
  3398. filed away at the end of the file, as top-level entries. Also in
  3399. the heading you can use %s to represent the file name, this can be
  3400. useful when using the same archive for a number of different files.
  3401. Here are a few examples:
  3402. \"%s_archive::\"
  3403. If the current file is Projects.org, archive in file
  3404. Projects.org_archive, as top-level trees. This is the default.
  3405. \"::* Archived Tasks\"
  3406. Archive in the current file, under the top-level headline
  3407. \"* Archived Tasks\".
  3408. \"~/org/archive.org::\"
  3409. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3410. \"~/org/archive.org::* From %s\"
  3411. Archive in file ~/org/archive.org (absolute path), under headlines
  3412. \"From FILENAME\" where file name is the current file name.
  3413. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3414. The \"datetree/\" string is special, signifying to archive
  3415. items to the datetree. Items are placed in either the CLOSED
  3416. date of the item, or the current date if there is no CLOSED date.
  3417. The heading will be a subentry to the current date. There doesn't
  3418. need to be a heading, but there always needs to be a slash after
  3419. datetree. For example, to store archived items directly in the
  3420. datetree, use \"~/org/datetree.org::datetree/\".
  3421. \"basement::** Finished Tasks\"
  3422. Archive in file ./basement (relative path), as level 3 trees
  3423. below the level 2 heading \"** Finished Tasks\".
  3424. You may set this option on a per-file basis by adding to the buffer a
  3425. line like
  3426. #+ARCHIVE: basement::** Finished Tasks
  3427. You may also define it locally for a subtree by setting an ARCHIVE property
  3428. in the entry. If such a property is found in an entry, or anywhere up
  3429. the hierarchy, it will be used."
  3430. :group 'org-archive
  3431. :type 'string)
  3432. (defcustom org-agenda-skip-archived-trees t
  3433. "Non-nil means the agenda will skip any items located in archived trees.
  3434. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3435. variable is no longer recommended, you should leave it at the value t.
  3436. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3437. :group 'org-archive
  3438. :group 'org-agenda-skip
  3439. :type 'boolean)
  3440. (defcustom org-columns-skip-archived-trees t
  3441. "Non-nil means ignore archived trees when creating column view."
  3442. :group 'org-archive
  3443. :group 'org-properties
  3444. :type 'boolean)
  3445. (defcustom org-cycle-open-archived-trees nil
  3446. "Non-nil means `org-cycle' will open archived trees.
  3447. An archived tree is a tree marked with the tag ARCHIVE.
  3448. When nil, archived trees will stay folded. You can still open them with
  3449. normal outline commands like `show-all', but not with the cycling commands."
  3450. :group 'org-archive
  3451. :group 'org-cycle
  3452. :type 'boolean)
  3453. (defcustom org-sparse-tree-open-archived-trees nil
  3454. "Non-nil means sparse tree construction shows matches in archived trees.
  3455. When nil, matches in these trees are highlighted, but the trees are kept in
  3456. collapsed state."
  3457. :group 'org-archive
  3458. :group 'org-sparse-trees
  3459. :type 'boolean)
  3460. (defcustom org-sparse-tree-default-date-type nil
  3461. "The default date type when building a sparse tree.
  3462. When this is nil, a date is a scheduled or a deadline timestamp.
  3463. Otherwise, these types are allowed:
  3464. all: all timestamps
  3465. active: only active timestamps (<...>)
  3466. inactive: only inactive timestamps ([...])
  3467. scheduled: only scheduled timestamps
  3468. deadline: only deadline timestamps"
  3469. :type '(choice (const :tag "Scheduled or deadline" nil)
  3470. (const :tag "All timestamps" all)
  3471. (const :tag "Only active timestamps" active)
  3472. (const :tag "Only inactive timestamps" inactive)
  3473. (const :tag "Only scheduled timestamps" scheduled)
  3474. (const :tag "Only deadline timestamps" deadline)
  3475. (const :tag "Only closed timestamps" closed))
  3476. :version "26.1"
  3477. :package-version '(Org . "8.3")
  3478. :group 'org-sparse-trees)
  3479. (defun org-cycle-hide-archived-subtrees (state)
  3480. "Re-hide all archived subtrees after a visibility state change.
  3481. STATE should be one of the symbols listed in the docstring of
  3482. `org-cycle-hook'."
  3483. (when (and (not org-cycle-open-archived-trees)
  3484. (not (memq state '(overview folded))))
  3485. (save-excursion
  3486. (let* ((globalp (memq state '(contents all)))
  3487. (beg (if globalp (point-min) (point)))
  3488. (end (if globalp (point-max) (org-end-of-subtree t))))
  3489. (org-hide-archived-subtrees beg end)
  3490. (goto-char beg)
  3491. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3492. (message "%s" (substitute-command-keys
  3493. "Subtree is archived and stays closed. Use \
  3494. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3495. (defun org-force-cycle-archived ()
  3496. "Cycle subtree even if it is archived."
  3497. (interactive)
  3498. (setq this-command 'org-cycle)
  3499. (let ((org-cycle-open-archived-trees t))
  3500. (call-interactively 'org-cycle)))
  3501. (defun org-hide-archived-subtrees (beg end)
  3502. "Re-hide all archived subtrees after a visibility state change."
  3503. (org-with-wide-buffer
  3504. (let ((case-fold-search nil)
  3505. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3506. (goto-char beg)
  3507. ;; Include headline point is currently on.
  3508. (beginning-of-line)
  3509. (while (and (< (point) end) (re-search-forward re end t))
  3510. (when (member org-archive-tag (org-get-tags nil t))
  3511. (org-flag-subtree t)
  3512. (org-end-of-subtree t))))))
  3513. (defun org-flag-subtree (flag)
  3514. (save-excursion
  3515. (org-back-to-heading t)
  3516. (org-flag-region (line-end-position)
  3517. (progn (org-end-of-subtree t) (point))
  3518. flag
  3519. 'outline)))
  3520. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3521. ;; Declare Column View Code
  3522. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3523. (declare-function org-columns-compute "org-colview" (property))
  3524. ;; Declare ID code
  3525. (declare-function org-id-store-link "org-id")
  3526. (declare-function org-id-locations-load "org-id")
  3527. (declare-function org-id-locations-save "org-id")
  3528. (defvar org-id-track-globally)
  3529. ;;; Variables for pre-computed regular expressions, all buffer local
  3530. (defvar-local org-todo-regexp nil
  3531. "Matches any of the TODO state keywords.
  3532. Since TODO keywords are case-sensitive, `case-fold-search' is
  3533. expected to be bound to nil when matching against this regexp.")
  3534. (defvar-local org-not-done-regexp nil
  3535. "Matches any of the TODO state keywords except the last one.
  3536. Since TODO keywords are case-sensitive, `case-fold-search' is
  3537. expected to be bound to nil when matching against this regexp.")
  3538. (defvar-local org-not-done-heading-regexp nil
  3539. "Matches a TODO headline that is not done.
  3540. Since TODO keywords are case-sensitive, `case-fold-search' is
  3541. expected to be bound to nil when matching against this regexp.")
  3542. (defvar-local org-todo-line-regexp nil
  3543. "Matches a headline and puts TODO state into group 2 if present.
  3544. Since TODO keywords are case-sensitive, `case-fold-search' is
  3545. expected to be bound to nil when matching against this regexp.")
  3546. (defvar-local org-complex-heading-regexp nil
  3547. "Matches a headline and puts everything into groups:
  3548. group 1: Stars
  3549. group 2: The TODO keyword, maybe
  3550. group 3: Priority cookie
  3551. group 4: True headline
  3552. group 5: Tags
  3553. Since TODO keywords are case-sensitive, `case-fold-search' is
  3554. expected to be bound to nil when matching against this regexp.")
  3555. (defvar-local org-complex-heading-regexp-format nil
  3556. "Printf format to make regexp to match an exact headline.
  3557. This regexp will match the headline of any node which has the
  3558. exact headline text that is put into the format, but may have any
  3559. TODO state, priority and tags.")
  3560. (defvar-local org-todo-line-tags-regexp nil
  3561. "Matches a headline and puts TODO state into group 2 if present.
  3562. Also put tags into group 4 if tags are present.")
  3563. (defconst org-plain-time-of-day-regexp
  3564. (concat
  3565. "\\(\\<[012]?[0-9]"
  3566. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3567. "\\(--?"
  3568. "\\(\\<[012]?[0-9]"
  3569. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3570. "\\)?")
  3571. "Regular expression to match a plain time or time range.
  3572. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3573. groups carry important information:
  3574. 0 the full match
  3575. 1 the first time, range or not
  3576. 8 the second time, if it is a range.")
  3577. (defconst org-plain-time-extension-regexp
  3578. (concat
  3579. "\\(\\<[012]?[0-9]"
  3580. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3581. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3582. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3583. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3584. groups carry important information:
  3585. 0 the full match
  3586. 7 hours of duration
  3587. 9 minutes of duration")
  3588. (defconst org-stamp-time-of-day-regexp
  3589. (concat
  3590. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3591. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  3592. "\\(--?"
  3593. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3594. "Regular expression to match a timestamp time or time range.
  3595. After a match, the following groups carry important information:
  3596. 0 the full match
  3597. 1 date plus weekday, for back referencing to make sure both times are on the same day
  3598. 2 the first time, range or not
  3599. 4 the second time, if it is a range.")
  3600. (defconst org-startup-options
  3601. '(("fold" org-startup-folded t)
  3602. ("overview" org-startup-folded t)
  3603. ("nofold" org-startup-folded nil)
  3604. ("showall" org-startup-folded nil)
  3605. ("showeverything" org-startup-folded showeverything)
  3606. ("content" org-startup-folded content)
  3607. ("indent" org-startup-indented t)
  3608. ("noindent" org-startup-indented nil)
  3609. ("hidestars" org-hide-leading-stars t)
  3610. ("showstars" org-hide-leading-stars nil)
  3611. ("odd" org-odd-levels-only t)
  3612. ("oddeven" org-odd-levels-only nil)
  3613. ("align" org-startup-align-all-tables t)
  3614. ("noalign" org-startup-align-all-tables nil)
  3615. ("shrink" org-startup-shrink-all-tables t)
  3616. ("inlineimages" org-startup-with-inline-images t)
  3617. ("noinlineimages" org-startup-with-inline-images nil)
  3618. ("latexpreview" org-startup-with-latex-preview t)
  3619. ("nolatexpreview" org-startup-with-latex-preview nil)
  3620. ("customtime" org-display-custom-times t)
  3621. ("logdone" org-log-done time)
  3622. ("lognotedone" org-log-done note)
  3623. ("nologdone" org-log-done nil)
  3624. ("lognoteclock-out" org-log-note-clock-out t)
  3625. ("nolognoteclock-out" org-log-note-clock-out nil)
  3626. ("logrepeat" org-log-repeat state)
  3627. ("lognoterepeat" org-log-repeat note)
  3628. ("logdrawer" org-log-into-drawer t)
  3629. ("nologdrawer" org-log-into-drawer nil)
  3630. ("logstatesreversed" org-log-states-order-reversed t)
  3631. ("nologstatesreversed" org-log-states-order-reversed nil)
  3632. ("nologrepeat" org-log-repeat nil)
  3633. ("logreschedule" org-log-reschedule time)
  3634. ("lognotereschedule" org-log-reschedule note)
  3635. ("nologreschedule" org-log-reschedule nil)
  3636. ("logredeadline" org-log-redeadline time)
  3637. ("lognoteredeadline" org-log-redeadline note)
  3638. ("nologredeadline" org-log-redeadline nil)
  3639. ("logrefile" org-log-refile time)
  3640. ("lognoterefile" org-log-refile note)
  3641. ("nologrefile" org-log-refile nil)
  3642. ("fninline" org-footnote-define-inline t)
  3643. ("nofninline" org-footnote-define-inline nil)
  3644. ("fnlocal" org-footnote-section nil)
  3645. ("fnauto" org-footnote-auto-label t)
  3646. ("fnprompt" org-footnote-auto-label nil)
  3647. ("fnconfirm" org-footnote-auto-label confirm)
  3648. ("fnplain" org-footnote-auto-label plain)
  3649. ("fnadjust" org-footnote-auto-adjust t)
  3650. ("nofnadjust" org-footnote-auto-adjust nil)
  3651. ("constcgs" constants-unit-system cgs)
  3652. ("constSI" constants-unit-system SI)
  3653. ("noptag" org-tag-persistent-alist nil)
  3654. ("hideblocks" org-hide-block-startup t)
  3655. ("nohideblocks" org-hide-block-startup nil)
  3656. ("beamer" org-startup-with-beamer-mode t)
  3657. ("entitiespretty" org-pretty-entities t)
  3658. ("entitiesplain" org-pretty-entities nil))
  3659. "Variable associated with STARTUP options for Org.
  3660. Each element is a list of three items: the startup options (as written
  3661. in the #+STARTUP line), the corresponding variable, and the value to set
  3662. this variable to if the option is found. An optional forth element PUSH
  3663. means to push this value onto the list in the variable.")
  3664. (defcustom org-group-tags t
  3665. "When non-nil (the default), use group tags.
  3666. This can be turned on/off through `org-toggle-tags-groups'."
  3667. :group 'org-tags
  3668. :group 'org-startup
  3669. :type 'boolean)
  3670. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3671. (defun org-toggle-tags-groups ()
  3672. "Toggle support for group tags.
  3673. Support for group tags is controlled by the option
  3674. `org-group-tags', which is non-nil by default."
  3675. (interactive)
  3676. (setq org-group-tags (not org-group-tags))
  3677. (cond ((and (derived-mode-p 'org-agenda-mode)
  3678. org-group-tags)
  3679. (org-agenda-redo))
  3680. ((derived-mode-p 'org-mode)
  3681. (let ((org-inhibit-startup t)) (org-mode))))
  3682. (message "Groups tags support has been turned %s"
  3683. (if org-group-tags "on" "off")))
  3684. (defun org--tag-add-to-alist (alist1 alist2)
  3685. "Merge tags from ALIST1 into ALIST2.
  3686. Duplicates tags outside a group are removed. Keywords and order
  3687. are preserved.
  3688. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3689. See `org-tag-alist' for their structure."
  3690. (cond
  3691. ((null alist2) alist1)
  3692. ((null alist1) alist2)
  3693. (t
  3694. (let ((to-add nil)
  3695. (group-flag nil))
  3696. (dolist (tag-pair alist1)
  3697. (pcase tag-pair
  3698. (`(,(or :startgrouptag :startgroup))
  3699. (setq group-flag t)
  3700. (push tag-pair to-add))
  3701. (`(,(or :endgrouptag :endgroup))
  3702. (setq group-flag nil)
  3703. (push tag-pair to-add))
  3704. (`(,(or :grouptags :newline))
  3705. (push tag-pair to-add))
  3706. (`(,tag . ,_)
  3707. ;; Remove duplicates from ALIST1, unless they are in
  3708. ;; a group. Indeed, it makes sense to have a tag appear in
  3709. ;; multiple groups.
  3710. (when (or group-flag (not (assoc tag alist2)))
  3711. (push tag-pair to-add)))
  3712. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3713. ;; Preserve order of ALIST1.
  3714. (append (nreverse to-add) alist2)))))
  3715. (defun org-set-regexps-and-options (&optional tags-only)
  3716. "Precompute regular expressions used in the current buffer.
  3717. When optional argument TAGS-ONLY is non-nil, only compute tags
  3718. related expressions."
  3719. (when (derived-mode-p 'org-mode)
  3720. (let ((alist (org--setup-collect-keywords
  3721. (org-make-options-regexp
  3722. (append '("FILETAGS" "TAGS" "SETUPFILE")
  3723. (and (not tags-only)
  3724. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3725. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3726. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  3727. ;; Startup options. Get this early since it does change
  3728. ;; behavior for other options (e.g., tags).
  3729. (let ((startup (cdr (assq 'startup alist))))
  3730. (dolist (option startup)
  3731. (let ((entry (assoc-string option org-startup-options t)))
  3732. (when entry
  3733. (let ((var (nth 1 entry))
  3734. (val (nth 2 entry)))
  3735. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  3736. (unless (listp (symbol-value var))
  3737. (set (make-local-variable var) nil))
  3738. (add-to-list var val)))))))
  3739. (setq-local org-file-tags
  3740. (mapcar #'org-add-prop-inherited
  3741. (cdr (assq 'filetags alist))))
  3742. (setq org-current-tag-alist
  3743. (org--tag-add-to-alist
  3744. org-tag-persistent-alist
  3745. (let ((tags (cdr (assq 'tags alist))))
  3746. (if tags (org-tag-string-to-alist tags)
  3747. org-tag-alist))))
  3748. (setq org-tag-groups-alist
  3749. (org-tag-alist-to-groups org-current-tag-alist))
  3750. (unless tags-only
  3751. ;; File properties.
  3752. (setq-local org-file-properties (cdr (assq 'property alist)))
  3753. ;; Archive location.
  3754. (let ((archive (cdr (assq 'archive alist))))
  3755. (when archive (setq-local org-archive-location archive)))
  3756. ;; Category.
  3757. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  3758. (when cat
  3759. (setq-local org-category (intern cat))
  3760. (setq-local org-file-properties
  3761. (org--update-property-plist
  3762. "CATEGORY" cat org-file-properties))))
  3763. ;; Columns.
  3764. (let ((column (cdr (assq 'columns alist))))
  3765. (when column (setq-local org-columns-default-format column)))
  3766. ;; Constants.
  3767. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  3768. ;; Link abbreviations.
  3769. (let ((links (cdr (assq 'link alist))))
  3770. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3771. ;; Priorities.
  3772. (let ((priorities (cdr (assq 'priorities alist))))
  3773. (when priorities
  3774. (setq-local org-highest-priority (nth 0 priorities))
  3775. (setq-local org-lowest-priority (nth 1 priorities))
  3776. (setq-local org-default-priority (nth 2 priorities))))
  3777. ;; Scripts.
  3778. (let ((scripts (assq 'scripts alist)))
  3779. (when scripts
  3780. (setq-local org-use-sub-superscripts (cdr scripts))))
  3781. ;; TODO keywords.
  3782. (setq-local org-todo-kwd-alist nil)
  3783. (setq-local org-todo-key-alist nil)
  3784. (setq-local org-todo-key-trigger nil)
  3785. (setq-local org-todo-keywords-1 nil)
  3786. (setq-local org-done-keywords nil)
  3787. (setq-local org-todo-heads nil)
  3788. (setq-local org-todo-sets nil)
  3789. (setq-local org-todo-log-states nil)
  3790. (let ((todo-sequences
  3791. (or (nreverse (cdr (assq 'todo alist)))
  3792. (let ((d (default-value 'org-todo-keywords)))
  3793. (if (not (stringp (car d))) d
  3794. ;; XXX: Backward compatibility code.
  3795. (list (cons org-todo-interpretation d)))))))
  3796. (dolist (sequence todo-sequences)
  3797. (let* ((sequence (or (run-hook-with-args-until-success
  3798. 'org-todo-setup-filter-hook sequence)
  3799. sequence))
  3800. (sequence-type (car sequence))
  3801. (keywords (cdr sequence))
  3802. (sep (member "|" keywords))
  3803. names alist)
  3804. (dolist (k (remove "|" keywords))
  3805. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3806. k)
  3807. (error "Invalid TODO keyword %s" k))
  3808. (let ((name (match-string 1 k))
  3809. (key (match-string 2 k))
  3810. (log (org-extract-log-state-settings k)))
  3811. (push name names)
  3812. (push (cons name (and key (string-to-char key))) alist)
  3813. (when log (push log org-todo-log-states))))
  3814. (let* ((names (nreverse names))
  3815. (done (if sep (org-remove-keyword-keys (cdr sep))
  3816. (last names)))
  3817. (head (car names))
  3818. (tail (list sequence-type head (car done) (org-last done))))
  3819. (add-to-list 'org-todo-heads head 'append)
  3820. (push names org-todo-sets)
  3821. (setq org-done-keywords (append org-done-keywords done nil))
  3822. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3823. (setq org-todo-key-alist
  3824. (append org-todo-key-alist
  3825. (and alist
  3826. (append '((:startgroup))
  3827. (nreverse alist)
  3828. '((:endgroup))))))
  3829. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3830. (setq org-todo-sets (nreverse org-todo-sets)
  3831. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3832. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3833. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3834. ;; Compute the regular expressions and other local variables.
  3835. ;; Using `org-outline-regexp-bol' would complicate them much,
  3836. ;; because of the fixed white space at the end of that string.
  3837. (unless org-done-keywords
  3838. (setq org-done-keywords
  3839. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3840. (setq org-not-done-keywords
  3841. (org-delete-all org-done-keywords
  3842. (copy-sequence org-todo-keywords-1))
  3843. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3844. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3845. org-not-done-heading-regexp
  3846. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3847. org-todo-line-regexp
  3848. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3849. org-complex-heading-regexp
  3850. (concat "^\\(\\*+\\)"
  3851. "\\(?: +" org-todo-regexp "\\)?"
  3852. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3853. "\\(?: +\\(.*?\\)\\)??"
  3854. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3855. "[ \t]*$")
  3856. org-complex-heading-regexp-format
  3857. (concat "^\\(\\*+\\)"
  3858. "\\(?: +" org-todo-regexp "\\)?"
  3859. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3860. "\\(?: +"
  3861. ;; Stats cookies can be stuck to body.
  3862. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3863. "\\(%s\\)"
  3864. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3865. "\\)"
  3866. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3867. "[ \t]*$")
  3868. org-todo-line-tags-regexp
  3869. (concat "^\\(\\*+\\)"
  3870. "\\(?: +" org-todo-regexp "\\)?"
  3871. "\\(?: +\\(.*?\\)\\)??"
  3872. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3873. "[ \t]*$"))
  3874. (org-compute-latex-and-related-regexp)))))
  3875. (defun org--setup-collect-keywords (regexp &optional files alist)
  3876. "Return setup keywords values as an alist.
  3877. REGEXP matches a subset of setup keywords. FILES is a list of
  3878. file names already visited. It is used to avoid circular setup
  3879. files. ALIST, when non-nil, is the alist computed so far.
  3880. Return value contains the following keys: `archive', `category',
  3881. `columns', `constants', `filetags', `link', `priorities',
  3882. `property', `scripts', `startup', `tags' and `todo'."
  3883. (org-with-wide-buffer
  3884. (goto-char (point-min))
  3885. (let ((case-fold-search t))
  3886. (while (re-search-forward regexp nil t)
  3887. (let ((element (org-element-at-point)))
  3888. (when (eq (org-element-type element) 'keyword)
  3889. (let ((key (org-element-property :key element))
  3890. (value (org-element-property :value element)))
  3891. (cond
  3892. ((equal key "ARCHIVE")
  3893. (when (org-string-nw-p value)
  3894. (push (cons 'archive value) alist)))
  3895. ((equal key "CATEGORY") (push (cons 'category value) alist))
  3896. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  3897. ((equal key "CONSTANTS")
  3898. (let* ((constants (assq 'constants alist))
  3899. (store (cdr constants)))
  3900. (dolist (pair (split-string value))
  3901. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  3902. pair)
  3903. (let* ((name (match-string 1 pair))
  3904. (value (match-string 2 pair))
  3905. (old (assoc name store)))
  3906. (if old (setcdr old value)
  3907. (push (cons name value) store)))))
  3908. (if constants (setcdr constants store)
  3909. (push (cons 'constants store) alist))))
  3910. ((equal key "FILETAGS")
  3911. (when (org-string-nw-p value)
  3912. (let ((old (assq 'filetags alist))
  3913. (new (apply #'nconc
  3914. (mapcar (lambda (x) (org-split-string x ":"))
  3915. (split-string value)))))
  3916. (if old (setcdr old (append new (cdr old)))
  3917. (push (cons 'filetags new) alist)))))
  3918. ((equal key "LINK")
  3919. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3920. (let ((links (assq 'link alist))
  3921. (pair (cons (match-string-no-properties 1 value)
  3922. (match-string-no-properties 2 value))))
  3923. (if links (push pair (cdr links))
  3924. (push (list 'link pair) alist)))))
  3925. ((equal key "OPTIONS")
  3926. (when (and (org-string-nw-p value)
  3927. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  3928. (push (cons 'scripts (read (match-string 1 value))) alist)))
  3929. ((equal key "PRIORITIES")
  3930. (push (cons 'priorities
  3931. (let ((prio (split-string value)))
  3932. (if (< (length prio) 3) '(?A ?C ?B)
  3933. (mapcar #'string-to-char prio))))
  3934. alist))
  3935. ((equal key "PROPERTY")
  3936. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3937. (let* ((property (assq 'property alist))
  3938. (value (org--update-property-plist
  3939. (match-string-no-properties 1 value)
  3940. (match-string-no-properties 2 value)
  3941. (cdr property))))
  3942. (if property (setcdr property value)
  3943. (push (cons 'property value) alist)))))
  3944. ((equal key "STARTUP")
  3945. (let ((startup (assq 'startup alist)))
  3946. (if startup
  3947. (setcdr startup
  3948. (append (cdr startup) (split-string value)))
  3949. (push (cons 'startup (split-string value)) alist))))
  3950. ((equal key "TAGS")
  3951. (let ((tag-cell (assq 'tags alist)))
  3952. (if tag-cell
  3953. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  3954. (push (cons 'tags value) alist))))
  3955. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  3956. (let ((todo (assq 'todo alist))
  3957. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  3958. (split-string value))))
  3959. (if todo (push value (cdr todo))
  3960. (push (list 'todo value) alist))))
  3961. ((equal key "SETUPFILE")
  3962. (unless buffer-read-only ; Do not check in Gnus messages.
  3963. (let ((f (and (org-string-nw-p value)
  3964. (expand-file-name (org-strip-quotes value)))))
  3965. (when (and f (file-readable-p f) (not (member f files)))
  3966. (with-temp-buffer
  3967. (setq default-directory (file-name-directory f))
  3968. (insert-file-contents f)
  3969. (setq alist
  3970. ;; Fake Org mode to benefit from cache
  3971. ;; without recurring needlessly.
  3972. (let ((major-mode 'org-mode))
  3973. (org--setup-collect-keywords
  3974. regexp (cons f files) alist)))))))))))))))
  3975. alist)
  3976. (defun org-tag-string-to-alist (s)
  3977. "Return tag alist associated to string S.
  3978. S is a value for TAGS keyword or produced with
  3979. `org-tag-alist-to-string'. Return value is an alist suitable for
  3980. `org-tag-alist' or `org-tag-persistent-alist'."
  3981. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3982. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3983. "\\(?:(\\(.\\))\\)?\\'"))
  3984. alist group-flag)
  3985. (dolist (tokens lines (cdr (nreverse alist)))
  3986. (push '(:newline) alist)
  3987. (while tokens
  3988. (let ((token (pop tokens)))
  3989. (pcase token
  3990. ("{"
  3991. (push '(:startgroup) alist)
  3992. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3993. ("}"
  3994. (push '(:endgroup) alist)
  3995. (setq group-flag nil))
  3996. ("["
  3997. (push '(:startgrouptag) alist)
  3998. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3999. ("]"
  4000. (push '(:endgrouptag) alist)
  4001. (setq group-flag nil))
  4002. (":"
  4003. (push '(:grouptags) alist))
  4004. ((guard (string-match tag-re token))
  4005. (let ((tag (match-string 1 token))
  4006. (key (and (match-beginning 2)
  4007. (string-to-char (match-string 2 token)))))
  4008. ;; Push all tags in groups, no matter if they already
  4009. ;; appear somewhere else in the list.
  4010. (when (or group-flag (not (assoc tag alist)))
  4011. (push (cons tag key) alist))))))))))
  4012. (defun org-tag-alist-to-string (alist &optional skip-key)
  4013. "Return tag string associated to ALIST.
  4014. ALIST is an alist, as defined in `org-tag-alist' or
  4015. `org-tag-persistent-alist', or produced with
  4016. `org-tag-string-to-alist'.
  4017. Return value is a string suitable as a value for \"TAGS\"
  4018. keyword.
  4019. When optional argument SKIP-KEY is non-nil, skip selection keys
  4020. next to tags."
  4021. (mapconcat (lambda (token)
  4022. (pcase token
  4023. (`(:startgroup) "{")
  4024. (`(:endgroup) "}")
  4025. (`(:startgrouptag) "[")
  4026. (`(:endgrouptag) "]")
  4027. (`(:grouptags) ":")
  4028. (`(:newline) "\\n")
  4029. ((and
  4030. (guard (not skip-key))
  4031. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4032. (format "%s(%c)" tag key))
  4033. (`(,(and tag (pred stringp)) . ,_) tag)
  4034. (_ (user-error "Invalid tag token: %S" token))))
  4035. alist
  4036. " "))
  4037. (defun org-tag-alist-to-groups (alist)
  4038. "Return group alist from tag ALIST.
  4039. ALIST is an alist, as defined in `org-tag-alist' or
  4040. `org-tag-persistent-alist', or produced with
  4041. `org-tag-string-to-alist'. Return value is an alist following
  4042. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4043. a string, summarizing TAGS, as a list of strings."
  4044. (let (groups group-status current-group)
  4045. (dolist (token alist (nreverse groups))
  4046. (pcase token
  4047. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4048. (`(,(or :endgroup :endgrouptag))
  4049. (when (eq group-status 'append)
  4050. (push (nreverse current-group) groups))
  4051. (setq group-status nil current-group nil))
  4052. (`(:grouptags) (setq group-status 'append))
  4053. ((and `(,tag . ,_) (guard group-status))
  4054. (if (eq group-status 'append) (push tag current-group)
  4055. (setq current-group (list tag))))
  4056. (_ nil)))))
  4057. (defvar org--file-cache (make-hash-table :test #'equal)
  4058. "Hash table to store contents of files referenced via a URL.
  4059. This is the cache of file URLs read using `org-file-contents'.")
  4060. (defun org-reset-file-cache ()
  4061. "Reset the cache of files downloaded by `org-file-contents'."
  4062. (clrhash org--file-cache))
  4063. (defun org-file-url-p (file)
  4064. "Non-nil if FILE is a URL."
  4065. (require 'ffap)
  4066. (string-match-p ffap-url-regexp file))
  4067. (defun org-file-contents (file &optional noerror nocache)
  4068. "Return the contents of FILE, as a string.
  4069. FILE can be a file name or URL.
  4070. If FILE is a URL, download the contents. If the URL contents are
  4071. already cached in the `org--file-cache' hash table, the download step
  4072. is skipped.
  4073. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4074. from file or URL.
  4075. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4076. is available. This option applies only if FILE is a URL."
  4077. (let* ((is-url (org-file-url-p file))
  4078. (cache (and is-url
  4079. (not nocache)
  4080. (gethash file org--file-cache))))
  4081. (cond
  4082. (cache)
  4083. (is-url
  4084. (with-current-buffer (url-retrieve-synchronously file)
  4085. (goto-char (point-min))
  4086. ;; Move point to after the url-retrieve header.
  4087. (search-forward "\n\n" nil :move)
  4088. ;; Search for the success code only in the url-retrieve header.
  4089. (if (save-excursion
  4090. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4091. ;; Update the cache `org--file-cache' and return contents.
  4092. (puthash file
  4093. (buffer-substring-no-properties (point) (point-max))
  4094. org--file-cache)
  4095. (funcall (if noerror #'message #'user-error)
  4096. "Unable to fetch file from %S"
  4097. file))))
  4098. (t
  4099. (with-temp-buffer
  4100. (condition-case nil
  4101. (progn
  4102. (insert-file-contents file)
  4103. (buffer-string))
  4104. (file-error
  4105. (funcall (if noerror #'message #'user-error)
  4106. "Unable to read file %S"
  4107. file))))))))
  4108. (defun org-extract-log-state-settings (x)
  4109. "Extract the log state setting from a TODO keyword string.
  4110. This will extract info from a string like \"WAIT(w@/!)\"."
  4111. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4112. (let ((kw (match-string 1 x))
  4113. (log1 (and (match-end 3) (match-string 3 x)))
  4114. (log2 (and (match-end 4) (match-string 4 x))))
  4115. (and (or log1 log2)
  4116. (list kw
  4117. (and log1 (if (equal log1 "!") 'time 'note))
  4118. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4119. (defun org-remove-keyword-keys (list)
  4120. "Remove a pair of parenthesis at the end of each string in LIST."
  4121. (mapcar (lambda (x)
  4122. (if (string-match "(.*)$" x)
  4123. (substring x 0 (match-beginning 0))
  4124. x))
  4125. list))
  4126. (defun org-assign-fast-keys (alist)
  4127. "Assign fast keys to a keyword-key alist.
  4128. Respect keys that are already there."
  4129. (let (new e (alt ?0))
  4130. (while (setq e (pop alist))
  4131. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4132. (cdr e)) ;; Key already assigned.
  4133. (push e new)
  4134. (let ((clist (string-to-list (downcase (car e))))
  4135. (used (append new alist)))
  4136. (when (= (car clist) ?@)
  4137. (pop clist))
  4138. (while (and clist (rassoc (car clist) used))
  4139. (pop clist))
  4140. (unless clist
  4141. (while (rassoc alt used)
  4142. (cl-incf alt)))
  4143. (push (cons (car e) (or (car clist) alt)) new))))
  4144. (nreverse new)))
  4145. ;;; Some variables used in various places
  4146. (defvar org-window-configuration nil
  4147. "Used in various places to store a window configuration.")
  4148. (defvar org-selected-window nil
  4149. "Used in various places to store a window configuration.")
  4150. (defvar org-finish-function nil
  4151. "Function to be called when `C-c C-c' is used.
  4152. This is for getting out of special buffers like capture.")
  4153. (defvar org-last-state)
  4154. ;; Defined somewhere in this file, but used before definition.
  4155. (defvar org-entities) ;; defined in org-entities.el
  4156. (defvar org-struct-menu)
  4157. (defvar org-org-menu)
  4158. (defvar org-tbl-menu)
  4159. ;;;; Define the Org mode
  4160. (defun org-before-change-function (_beg _end)
  4161. "Every change indicates that a table might need an update."
  4162. (setq org-table-may-need-update t))
  4163. (defvar org-mode-map)
  4164. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4165. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4166. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4167. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4168. (defvar bidi-paragraph-direction)
  4169. (defvar buffer-face-mode-face)
  4170. (require 'outline)
  4171. ;; Other stuff we need.
  4172. (require 'time-date)
  4173. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4174. (require 'easymenu)
  4175. (autoload 'easy-menu-add "easymenu")
  4176. (require 'overlay)
  4177. ;; (require 'org-macs) moved higher up in the file before it is first used
  4178. (require 'org-entities)
  4179. ;; (require 'org-compat) moved higher up in the file before it is first used
  4180. (require 'org-faces)
  4181. (require 'org-list)
  4182. (require 'org-pcomplete)
  4183. (require 'org-src)
  4184. (require 'org-footnote)
  4185. (require 'org-macro)
  4186. ;; babel
  4187. (require 'ob)
  4188. ;;;###autoload
  4189. (define-derived-mode org-mode outline-mode "Org"
  4190. "Outline-based notes management and organizer, alias
  4191. \"Carsten's outline-mode for keeping track of everything.\"
  4192. Org mode develops organizational tasks around a NOTES file which
  4193. contains information about projects as plain text. Org mode is
  4194. implemented on top of Outline mode, which is ideal to keep the content
  4195. of large files well structured. It supports ToDo items, deadlines and
  4196. time stamps, which magically appear in the diary listing of the Emacs
  4197. calendar. Tables are easily created with a built-in table editor.
  4198. Plain text URL-like links connect to websites, emails (VM), Usenet
  4199. messages (Gnus), BBDB entries, and any files related to the project.
  4200. For printing and sharing of notes, an Org file (or a part of it)
  4201. can be exported as a structured ASCII or HTML file.
  4202. The following commands are available:
  4203. \\{org-mode-map}"
  4204. (org-load-modules-maybe)
  4205. (org-install-agenda-files-menu)
  4206. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4207. (add-to-invisibility-spec '(org-hide-block . t))
  4208. (add-to-invisibility-spec '(org-hide-drawer . t))
  4209. (setq-local outline-regexp org-outline-regexp)
  4210. (setq-local outline-level 'org-outline-level)
  4211. (setq bidi-paragraph-direction 'left-to-right)
  4212. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4213. (unless org-display-table
  4214. (setq org-display-table (make-display-table)))
  4215. (set-display-table-slot
  4216. org-display-table 4
  4217. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4218. org-ellipsis)))
  4219. (setq buffer-display-table org-display-table))
  4220. (org-set-regexps-and-options)
  4221. (org-set-font-lock-defaults)
  4222. (when (and org-tag-faces (not org-tags-special-faces-re))
  4223. ;; tag faces set outside customize.... force initialization.
  4224. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4225. ;; Calc embedded
  4226. (setq-local calc-embedded-open-mode "# ")
  4227. ;; Modify a few syntax entries
  4228. (modify-syntax-entry ?\" "\"")
  4229. (modify-syntax-entry ?\\ "_")
  4230. (modify-syntax-entry ?~ "_")
  4231. (modify-syntax-entry ?< "(>")
  4232. (modify-syntax-entry ?> ")<")
  4233. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4234. ;; Activate before-change-function
  4235. (setq-local org-table-may-need-update t)
  4236. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4237. ;; Check for running clock before killing a buffer
  4238. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4239. ;; Initialize macros templates.
  4240. (org-macro-initialize-templates)
  4241. ;; Initialize radio targets.
  4242. (org-update-radio-target-regexp)
  4243. ;; Indentation.
  4244. (setq-local indent-line-function 'org-indent-line)
  4245. (setq-local indent-region-function 'org-indent-region)
  4246. ;; Filling and auto-filling.
  4247. (org-setup-filling)
  4248. ;; Comments.
  4249. (org-setup-comments-handling)
  4250. ;; Initialize cache.
  4251. (org-element-cache-reset)
  4252. ;; Beginning/end of defun
  4253. (setq-local beginning-of-defun-function 'org-backward-element)
  4254. (setq-local end-of-defun-function
  4255. (lambda ()
  4256. (if (not (org-at-heading-p))
  4257. (org-forward-element)
  4258. (org-forward-element)
  4259. (forward-char -1))))
  4260. ;; Next error for sparse trees
  4261. (setq-local next-error-function 'org-occur-next-match)
  4262. ;; Make commit log messages from Org documents easier.
  4263. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4264. ;; Make sure dependence stuff works reliably, even for users who set it
  4265. ;; too late :-(
  4266. (if org-enforce-todo-dependencies
  4267. (add-hook 'org-blocker-hook
  4268. 'org-block-todo-from-children-or-siblings-or-parent)
  4269. (remove-hook 'org-blocker-hook
  4270. 'org-block-todo-from-children-or-siblings-or-parent))
  4271. (if org-enforce-todo-checkbox-dependencies
  4272. (add-hook 'org-blocker-hook
  4273. 'org-block-todo-from-checkboxes)
  4274. (remove-hook 'org-blocker-hook
  4275. 'org-block-todo-from-checkboxes))
  4276. ;; Align options lines
  4277. (setq-local
  4278. align-mode-rules-list
  4279. '((org-in-buffer-settings
  4280. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4281. (modes . '(org-mode)))))
  4282. ;; Make isearch reveal context
  4283. (setq-local outline-isearch-open-invisible-function
  4284. (lambda (&rest _) (org-show-context 'isearch)))
  4285. ;; Setup the pcomplete hooks
  4286. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4287. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4288. (setq-local pcomplete-default-completion-function 'ignore)
  4289. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4290. (setq-local pcomplete-termination-string "")
  4291. (setq-local buffer-face-mode-face 'org-default)
  4292. ;; If empty file that did not turn on Org mode automatically, make
  4293. ;; it to.
  4294. (when (and org-insert-mode-line-in-empty-file
  4295. (called-interactively-p 'any)
  4296. (= (point-min) (point-max)))
  4297. (insert "# -*- mode: org -*-\n\n"))
  4298. (unless org-inhibit-startup
  4299. (org-unmodified
  4300. (when org-startup-with-beamer-mode (org-beamer-mode))
  4301. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4302. (org-table-map-tables
  4303. (cond ((and org-startup-align-all-tables
  4304. org-startup-shrink-all-tables)
  4305. (lambda () (org-table-align) (org-table-shrink)))
  4306. (org-startup-align-all-tables #'org-table-align)
  4307. (t #'org-table-shrink))
  4308. t))
  4309. (when org-startup-with-inline-images (org-display-inline-images))
  4310. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4311. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4312. (when org-startup-truncated (setq truncate-lines t))
  4313. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4314. ;; Try to set `org-hide' face correctly.
  4315. (let ((foreground (org-find-invisible-foreground)))
  4316. (when foreground
  4317. (set-face-foreground 'org-hide foreground))))
  4318. ;; Update `customize-package-emacs-version-alist'
  4319. (add-to-list 'customize-package-emacs-version-alist
  4320. '(Org ("8.0" . "24.4")
  4321. ("8.1" . "24.4")
  4322. ("8.2" . "24.4")
  4323. ("8.2.7" . "24.4")
  4324. ("8.3" . "26.1")
  4325. ("9.0" . "26.1")
  4326. ("9.1" . "26.1")
  4327. ("9.2" . "27.1")))
  4328. (defvar org-mode-transpose-word-syntax-table
  4329. (let ((st (make-syntax-table text-mode-syntax-table)))
  4330. (dolist (c org-emphasis-alist st)
  4331. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4332. (when (fboundp 'abbrev-table-put)
  4333. (abbrev-table-put org-mode-abbrev-table
  4334. :parents (list text-mode-abbrev-table)))
  4335. (defun org-find-invisible-foreground ()
  4336. (let ((candidates (remove
  4337. "unspecified-bg"
  4338. (nconc
  4339. (list (face-background 'default)
  4340. (face-background 'org-default))
  4341. (mapcar
  4342. (lambda (alist)
  4343. (when (boundp alist)
  4344. (cdr (assq 'background-color (symbol-value alist)))))
  4345. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4346. (list (face-foreground 'org-hide))))))
  4347. (car (remove nil candidates))))
  4348. (defun org-current-time (&optional rounding-minutes past)
  4349. "Current time, possibly rounded to ROUNDING-MINUTES.
  4350. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4351. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4352. the rounding returns a past time."
  4353. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4354. (car org-time-stamp-rounding-minutes)))
  4355. (time (decode-time)) res)
  4356. (if (< r 1)
  4357. (current-time)
  4358. (setq res
  4359. (apply 'encode-time
  4360. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4361. (nthcdr 2 time))))
  4362. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4363. (seconds-to-time (- (float-time res) (* r 60)))
  4364. res))))
  4365. (defun org-today ()
  4366. "Return today date, considering `org-extend-today-until'."
  4367. (time-to-days
  4368. (time-subtract (current-time)
  4369. (list 0 (* 3600 org-extend-today-until) 0))))
  4370. ;;;; Font-Lock stuff, including the activators
  4371. (require 'font-lock)
  4372. (defconst org-match-sexp-depth 3
  4373. "Number of stacked braces for sub/superscript matching.")
  4374. (defun org-create-multibrace-regexp (left right n)
  4375. "Create a regular expression which will match a balanced sexp.
  4376. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4377. as single character strings.
  4378. The regexp returned will match the entire expression including the
  4379. delimiters. It will also define a single group which contains the
  4380. match except for the outermost delimiters. The maximum depth of
  4381. stacked delimiters is N. Escaping delimiters is not possible."
  4382. (let* ((nothing (concat "[^" left right "]*?"))
  4383. (or "\\|")
  4384. (re nothing)
  4385. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4386. (while (> n 1)
  4387. (setq n (1- n)
  4388. re (concat re or next)
  4389. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4390. (concat left "\\(" re "\\)" right)))
  4391. (defconst org-match-substring-regexp
  4392. (concat
  4393. "\\(\\S-\\)\\([_^]\\)\\("
  4394. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4395. "\\|"
  4396. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4397. "\\|"
  4398. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4399. "The regular expression matching a sub- or superscript.")
  4400. (defconst org-match-substring-with-braces-regexp
  4401. (concat
  4402. "\\(\\S-\\)\\([_^]\\)"
  4403. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4404. "The regular expression matching a sub- or superscript, forcing braces.")
  4405. (defvar org-emph-face nil)
  4406. (defun org-do-emphasis-faces (limit)
  4407. "Run through the buffer and emphasize strings."
  4408. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4409. (car org-emphasis-regexp-components))))
  4410. (catch :exit
  4411. (while (re-search-forward quick-re limit t)
  4412. (let* ((marker (match-string 2))
  4413. (verbatim? (member marker '("~" "="))))
  4414. (when (save-excursion
  4415. (goto-char (match-beginning 0))
  4416. (and
  4417. ;; Do not match table hlines.
  4418. (not (and (equal marker "+")
  4419. (org-match-line
  4420. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4421. ;; Do not match headline stars. Do not consider
  4422. ;; stars of a headline as closing marker for bold
  4423. ;; markup either.
  4424. (not (and (equal marker "*")
  4425. (save-excursion
  4426. (forward-char)
  4427. (skip-chars-backward "*")
  4428. (looking-at-p org-outline-regexp-bol))))
  4429. ;; Match full emphasis markup regexp.
  4430. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4431. ;; Do not span over paragraph boundaries.
  4432. (not (string-match-p org-element-paragraph-separate
  4433. (match-string 2)))
  4434. ;; Do not span over cells in table rows.
  4435. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4436. (string-match-p "|" (match-string 4))))))
  4437. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  4438. (font-lock-prepend-text-property
  4439. (match-beginning 2) (match-end 2) 'face face)
  4440. (when verbatim?
  4441. (org-remove-flyspell-overlays-in
  4442. (match-beginning 0) (match-end 0))
  4443. (remove-text-properties (match-beginning 2) (match-end 2)
  4444. '(display t invisible t intangible t)))
  4445. (add-text-properties (match-beginning 2) (match-end 2)
  4446. '(font-lock-multiline t org-emphasis t))
  4447. (when org-hide-emphasis-markers
  4448. (add-text-properties (match-end 4) (match-beginning 5)
  4449. '(invisible org-link))
  4450. (add-text-properties (match-beginning 3) (match-end 3)
  4451. '(invisible org-link)))
  4452. (throw :exit t))))))))
  4453. (defun org-emphasize (&optional char)
  4454. "Insert or change an emphasis, i.e. a font like bold or italic.
  4455. If there is an active region, change that region to a new emphasis.
  4456. If there is no region, just insert the marker characters and position
  4457. the cursor between them.
  4458. CHAR should be the marker character. If it is a space, it means to
  4459. remove the emphasis of the selected region.
  4460. If CHAR is not given (for example in an interactive call) it will be
  4461. prompted for."
  4462. (interactive)
  4463. (let ((erc org-emphasis-regexp-components)
  4464. (string "") beg end move s)
  4465. (if (org-region-active-p)
  4466. (setq beg (region-beginning)
  4467. end (region-end)
  4468. string (buffer-substring beg end))
  4469. (setq move t))
  4470. (unless char
  4471. (message "Emphasis marker or tag: [%s]"
  4472. (mapconcat #'car org-emphasis-alist ""))
  4473. (setq char (read-char-exclusive)))
  4474. (if (equal char ?\s)
  4475. (setq s ""
  4476. move nil)
  4477. (unless (assoc (char-to-string char) org-emphasis-alist)
  4478. (user-error "No such emphasis marker: \"%c\"" char))
  4479. (setq s (char-to-string char)))
  4480. (while (and (> (length string) 1)
  4481. (equal (substring string 0 1) (substring string -1))
  4482. (assoc (substring string 0 1) org-emphasis-alist))
  4483. (setq string (substring string 1 -1)))
  4484. (setq string (concat s string s))
  4485. (when beg (delete-region beg end))
  4486. (unless (or (bolp)
  4487. (string-match (concat "[" (nth 0 erc) "\n]")
  4488. (char-to-string (char-before (point)))))
  4489. (insert " "))
  4490. (unless (or (eobp)
  4491. (string-match (concat "[" (nth 1 erc) "\n]")
  4492. (char-to-string (char-after (point)))))
  4493. (insert " ") (backward-char 1))
  4494. (insert string)
  4495. (and move (backward-char 1))))
  4496. (defconst org-nonsticky-props
  4497. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4498. (defsubst org-rear-nonsticky-at (pos)
  4499. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4500. (defun org-activate-links (limit)
  4501. "Add link properties to links.
  4502. This includes angle, plain, and bracket links."
  4503. (catch :exit
  4504. (while (re-search-forward org-link-any-re limit t)
  4505. (let* ((start (match-beginning 0))
  4506. (end (match-end 0))
  4507. (style (cond ((eq ?< (char-after start)) 'angle)
  4508. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4509. (t 'plain))))
  4510. (when (and (memq style org-highlight-links)
  4511. ;; Do not span over paragraph boundaries.
  4512. (not (string-match-p org-element-paragraph-separate
  4513. (match-string 0)))
  4514. ;; Do not confuse plain links with tags.
  4515. (not (and (eq style 'plain)
  4516. (let ((face (get-text-property
  4517. (max (1- start) (point-min)) 'face)))
  4518. (if (consp face) (memq 'org-tag face)
  4519. (eq 'org-tag face))))))
  4520. (let* ((link-object (save-excursion
  4521. (goto-char start)
  4522. (save-match-data (org-element-link-parser))))
  4523. (link (org-element-property :raw-link link-object))
  4524. (type (org-element-property :type link-object))
  4525. (path (org-element-property :path link-object))
  4526. (properties ;for link's visible part
  4527. (list
  4528. 'face (pcase (org-link-get-parameter type :face)
  4529. ((and (pred functionp) face) (funcall face path))
  4530. ((and (pred facep) face) face)
  4531. ((and (pred consp) face) face) ;anonymous
  4532. (_ 'org-link))
  4533. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4534. 'highlight)
  4535. 'keymap (or (org-link-get-parameter type :keymap)
  4536. org-mouse-map)
  4537. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4538. ((and (pred stringp) echo) echo)
  4539. ((and (pred functionp) echo) echo)
  4540. (_ (concat "LINK: " link)))
  4541. 'htmlize-link (pcase (org-link-get-parameter type
  4542. :htmlize-link)
  4543. ((and (pred functionp) f) (funcall f))
  4544. (_ `(:uri ,link)))
  4545. 'font-lock-multiline t)))
  4546. (org-remove-flyspell-overlays-in start end)
  4547. (org-rear-nonsticky-at end)
  4548. (if (not (eq 'bracket style))
  4549. (add-text-properties start end properties)
  4550. ;; Handle invisible parts in bracket links.
  4551. (remove-text-properties start end '(invisible nil))
  4552. (let ((hidden
  4553. (append `(invisible
  4554. ,(or (org-link-get-parameter type :display)
  4555. 'org-link))
  4556. properties))
  4557. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4558. (visible-end (or (match-end 3) (match-end 2))))
  4559. (add-text-properties start visible-start hidden)
  4560. (add-text-properties visible-start visible-end properties)
  4561. (add-text-properties visible-end end hidden)
  4562. (org-rear-nonsticky-at visible-start)
  4563. (org-rear-nonsticky-at visible-end)))
  4564. (let ((f (org-link-get-parameter type :activate-func)))
  4565. (when (functionp f)
  4566. (funcall f start end path (eq style 'bracket))))
  4567. (throw :exit t))))) ;signal success
  4568. nil))
  4569. (defun org-activate-code (limit)
  4570. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4571. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4572. (remove-text-properties (match-beginning 0) (match-end 0)
  4573. '(display t invisible t intangible t))
  4574. t))
  4575. (defcustom org-src-fontify-natively t
  4576. "When non-nil, fontify code in code blocks.
  4577. See also the `org-block' face."
  4578. :type 'boolean
  4579. :version "26.1"
  4580. :package-version '(Org . "8.3")
  4581. :group 'org-appearance
  4582. :group 'org-babel)
  4583. (defcustom org-allow-promoting-top-level-subtree nil
  4584. "When non-nil, allow promoting a top level subtree.
  4585. The leading star of the top level headline will be replaced
  4586. by a #."
  4587. :type 'boolean
  4588. :version "24.1"
  4589. :group 'org-appearance)
  4590. (defun org-fontify-meta-lines-and-blocks (limit)
  4591. (condition-case nil
  4592. (org-fontify-meta-lines-and-blocks-1 limit)
  4593. (error (message "Org mode fontification error in %S at %d"
  4594. (current-buffer)
  4595. (line-number-at-pos)))))
  4596. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4597. "Fontify #+ lines and blocks."
  4598. (let ((case-fold-search t))
  4599. (when (re-search-forward
  4600. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  4601. limit t)
  4602. (let ((beg (match-beginning 0))
  4603. (end-of-beginline (match-end 0))
  4604. (block-start (match-end 0)) ; includes the \n at end of #+begin line
  4605. (block-end nil) ; will include \n after end of block content
  4606. (lang (match-string 7)) ; the language, if it is an src block
  4607. (bol-after-beginline (line-beginning-position 2))
  4608. (dc1 (downcase (match-string 2)))
  4609. (dc3 (downcase (match-string 3)))
  4610. (whole-blockline org-fontify-whole-block-delimiter-line)
  4611. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4612. (cond
  4613. ((and (match-end 4) (equal dc3 "+begin"))
  4614. ;; Truly a block
  4615. (setq block-type (downcase (match-string 5))
  4616. quoting (member block-type org-protecting-blocks)) ; src, example, export, maybe more
  4617. (when (re-search-forward
  4618. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  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. (add-text-properties
  4658. beg-of-endline
  4659. (min (point-max) (if whole-blockline (min (point-max) (1+ end-of-endline)) end-of-endline))
  4660. '(face org-block-end-line))
  4661. t))
  4662. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  4663. (org-remove-flyspell-overlays-in
  4664. (match-beginning 0)
  4665. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4666. (add-text-properties
  4667. beg (match-end 3)
  4668. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4669. '(font-lock-fontified t invisible t)
  4670. '(font-lock-fontified t face org-document-info-keyword)))
  4671. (add-text-properties
  4672. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4673. (if (string-equal dc1 "+title:")
  4674. '(font-lock-fontified t face org-document-title)
  4675. '(font-lock-fontified t face org-document-info))))
  4676. ((string-prefix-p "+caption" dc1)
  4677. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4678. (remove-text-properties (match-beginning 0) (match-end 0)
  4679. '(display t invisible t intangible t))
  4680. ;; Handle short captions.
  4681. (save-excursion
  4682. (beginning-of-line)
  4683. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  4684. (add-text-properties (line-beginning-position) (match-end 1)
  4685. '(font-lock-fontified t face org-meta-line))
  4686. (add-text-properties (match-end 0) (line-end-position)
  4687. '(font-lock-fontified t face org-block))
  4688. t)
  4689. ((member dc3 '(" " ""))
  4690. ; Just a comment, the plus was not there
  4691. (org-remove-flyspell-overlays-in beg (match-end 0))
  4692. (add-text-properties
  4693. beg (match-end 0)
  4694. '(font-lock-fontified t face font-lock-comment-face)))
  4695. (t ;; just any other in-buffer setting, but not indented
  4696. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4697. (remove-text-properties (match-beginning 0) (match-end 0)
  4698. '(display t invisible t intangible t))
  4699. (add-text-properties beg (match-end 0)
  4700. '(font-lock-fontified t face org-meta-line))
  4701. t))))))
  4702. (defun org-fontify-drawers (limit)
  4703. "Fontify drawers."
  4704. (when (re-search-forward org-drawer-regexp limit t)
  4705. (add-text-properties
  4706. (match-beginning 0) (match-end 0)
  4707. '(font-lock-fontified t face org-special-keyword))
  4708. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4709. t))
  4710. (defun org-fontify-macros (limit)
  4711. "Fontify macros."
  4712. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4713. (let ((begin (match-beginning 0))
  4714. (opening-end (match-beginning 1)))
  4715. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4716. (match-string 1))
  4717. (let ((end (match-end 1))
  4718. (closing-start (match-beginning 1)))
  4719. (add-text-properties
  4720. begin end
  4721. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4722. (org-remove-flyspell-overlays-in begin end)
  4723. (when org-hide-macro-markers
  4724. (add-text-properties begin opening-end '(invisible t))
  4725. (add-text-properties closing-start end '(invisible t)))
  4726. t)))))
  4727. (defun org-fontify-extend-region (beg end _old-len)
  4728. (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4729. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4730. (extend (lambda (r1 r2 dir)
  4731. (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
  4732. (replace-regexp-in-string "[][]" r2
  4733. (match-string-no-properties 0)))))
  4734. (re-search-forward (regexp-quote re) nil t dir)))))
  4735. (save-match-data
  4736. (save-excursion
  4737. (goto-char beg)
  4738. (back-to-indentation)
  4739. (cond ((looking-at end-re)
  4740. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4741. ((looking-at begin-re)
  4742. (cons beg (or (funcall extend "end" "]" 1) end)))
  4743. (t (cons beg end)))))))
  4744. (defun org-activate-footnote-links (limit)
  4745. "Add text properties for footnotes."
  4746. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4747. (when fn
  4748. (let* ((beg (nth 1 fn))
  4749. (end (nth 2 fn))
  4750. (label (car fn))
  4751. (referencep (/= (line-beginning-position) beg)))
  4752. (when (and referencep (nth 3 fn))
  4753. (save-excursion
  4754. (goto-char beg)
  4755. (search-forward (or label "fn:"))
  4756. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4757. (add-text-properties beg end
  4758. (list 'mouse-face 'highlight
  4759. 'keymap org-mouse-map
  4760. 'help-echo
  4761. (if referencep "Footnote reference"
  4762. "Footnote definition")
  4763. 'font-lock-fontified t
  4764. 'font-lock-multiline t
  4765. 'face 'org-footnote))))))
  4766. (defun org-activate-dates (limit)
  4767. "Add text properties for dates."
  4768. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4769. (not (equal (char-before (match-beginning 0)) 91)))
  4770. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4771. (add-text-properties (match-beginning 0) (match-end 0)
  4772. (list 'mouse-face 'highlight
  4773. 'keymap org-mouse-map))
  4774. (org-rear-nonsticky-at (match-end 0))
  4775. (when org-display-custom-times
  4776. ;; If it's a date range, activate custom time for second date.
  4777. (when (match-end 3)
  4778. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4779. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4780. t))
  4781. (defun org-activate-target-links (limit)
  4782. "Add text properties for target matches."
  4783. (when org-target-link-regexp
  4784. (let ((case-fold-search t))
  4785. ;; `org-target-link-regexp' matches one character before the
  4786. ;; actual target.
  4787. (unless (bolp) (forward-char -1))
  4788. (when (re-search-forward org-target-link-regexp limit t)
  4789. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4790. (add-text-properties (match-beginning 1) (match-end 1)
  4791. (list 'mouse-face 'highlight
  4792. 'keymap org-mouse-map
  4793. 'help-echo "Radio target link"
  4794. 'org-linked-text t))
  4795. (org-rear-nonsticky-at (match-end 1))
  4796. t))))
  4797. (defvar org-latex-and-related-regexp nil
  4798. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4799. (defun org-compute-latex-and-related-regexp ()
  4800. "Compute regular expression for LaTeX, entities and sub/superscript.
  4801. Result depends on variable `org-highlight-latex-and-related'."
  4802. (let ((re-sub
  4803. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4804. ((eq org-use-sub-superscripts '{})
  4805. (list org-match-substring-with-braces-regexp))
  4806. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4807. (re-latex
  4808. (when (or (memq 'latex org-highlight-latex-and-related)
  4809. (memq 'native org-highlight-latex-and-related))
  4810. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4811. (delq nil
  4812. (mapcar (lambda (x)
  4813. (and (member (car x) matchers) (nth 1 x)))
  4814. org-latex-regexps)))))
  4815. (re-entities
  4816. (when (memq 'entities org-highlight-latex-and-related)
  4817. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4818. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4819. (setq-local org-latex-and-related-regexp
  4820. (mapconcat #'identity
  4821. (append re-latex re-entities re-sub)
  4822. "\\|"))))
  4823. (defun org-do-latex-and-related (_limit)
  4824. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4825. Stop at first highlighted object, if any. Return t if some
  4826. highlighting was done, nil otherwise."
  4827. (when (org-string-nw-p org-latex-and-related-regexp)
  4828. (catch 'found
  4829. (while (re-search-forward org-latex-and-related-regexp
  4830. nil t) ;; on purpose, we ignore LIMIT
  4831. (unless (cl-some (lambda (f) (memq f '(org-code org-verbatim underline
  4832. org-special-keyword)))
  4833. (save-excursion
  4834. (goto-char (1+ (match-beginning 0)))
  4835. (face-at-point nil t)))
  4836. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4837. '(?_ ?^))
  4838. 1
  4839. 0))
  4840. (start (+ offset (match-beginning 0)))
  4841. (end (match-end 0)))
  4842. (if (memq 'native org-highlight-latex-and-related)
  4843. (org-src-font-lock-fontify-block "latex" start end)
  4844. (font-lock-prepend-text-property start end
  4845. 'face 'org-latex-and-related))
  4846. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4847. '(font-lock-multiline t)))
  4848. (throw 'found t)))
  4849. nil)))
  4850. (defun org-restart-font-lock ()
  4851. "Restart `font-lock-mode', to force refontification."
  4852. (when (and (boundp 'font-lock-mode) font-lock-mode)
  4853. (font-lock-mode -1)
  4854. (font-lock-mode 1)))
  4855. (defun org-activate-tags (limit)
  4856. (when (re-search-forward org-tag-line-re limit t)
  4857. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4858. (add-text-properties (match-beginning 1) (match-end 1)
  4859. (list 'mouse-face 'highlight
  4860. 'keymap org-mouse-map))
  4861. (org-rear-nonsticky-at (match-end 1))
  4862. t))
  4863. (defun org-outline-level ()
  4864. "Compute the outline level of the heading at point.
  4865. If this is called at a normal headline, the level is the number
  4866. of stars. Use `org-reduced-level' to remove the effect of
  4867. `org-odd-levels'. Unlike to `org-current-level', this function
  4868. takes into consideration inlinetasks."
  4869. (org-with-wide-buffer
  4870. (end-of-line)
  4871. (if (re-search-backward org-outline-regexp-bol nil t)
  4872. (1- (- (match-end 0) (match-beginning 0)))
  4873. 0)))
  4874. (defvar org-font-lock-keywords nil)
  4875. (defsubst org-re-property (property &optional literal allow-null value)
  4876. "Return a regexp matching a PROPERTY line.
  4877. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4878. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4879. non-nil, match properties even without a value.
  4880. Match group 3 is set to the value when it exists. If there is no
  4881. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4882. With optional argument VALUE, match only property lines with
  4883. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4884. unless LITERAL is non-nil."
  4885. (concat
  4886. "^\\(?4:[ \t]*\\)"
  4887. (format "\\(?1::\\(?2:%s\\):\\)"
  4888. (if literal property (regexp-quote property)))
  4889. (cond (value
  4890. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4891. (if literal value (regexp-quote value))))
  4892. (allow-null
  4893. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4894. (t
  4895. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4896. (defconst org-property-re
  4897. (org-re-property "\\S-+" 'literal t)
  4898. "Regular expression matching a property line.
  4899. There are four matching groups:
  4900. 1: :PROPKEY: including the leading and trailing colon,
  4901. 2: PROPKEY without the leading and trailing colon,
  4902. 3: PROPVAL without leading or trailing spaces,
  4903. 4: the indentation of the current line,
  4904. 5: trailing whitespace.")
  4905. (defvar org-font-lock-hook nil
  4906. "Functions to be called for special font lock stuff.")
  4907. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4908. (defvar org-font-lock-set-keywords-hook nil
  4909. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4910. This is called after `org-font-lock-extra-keywords' is defined, but before
  4911. it is installed to be used by font lock. This can be useful if something
  4912. needs to be inserted at a specific position in the font-lock sequence.")
  4913. (defun org-font-lock-hook (limit)
  4914. "Run `org-font-lock-hook' within LIMIT."
  4915. (run-hook-with-args 'org-font-lock-hook limit))
  4916. (defun org-set-font-lock-defaults ()
  4917. "Set font lock defaults for the current buffer."
  4918. (let* ((em org-fontify-emphasized-text)
  4919. (lk org-highlight-links)
  4920. (org-font-lock-extra-keywords
  4921. (list
  4922. ;; Call the hook
  4923. '(org-font-lock-hook)
  4924. ;; Headlines
  4925. `(,(if org-fontify-whole-heading-line
  4926. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4927. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4928. (1 (org-get-level-face 1))
  4929. (2 (org-get-level-face 2))
  4930. (3 (org-get-level-face 3)))
  4931. ;; Table lines
  4932. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4933. (1 'org-table t))
  4934. ;; Table internals
  4935. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4936. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4937. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4938. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4939. ;; Drawers
  4940. '(org-fontify-drawers)
  4941. ;; Properties
  4942. (list org-property-re
  4943. '(1 'org-special-keyword t)
  4944. '(3 'org-property-value t))
  4945. ;; Link related fontification.
  4946. '(org-activate-links)
  4947. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  4948. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  4949. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  4950. (when (memq 'footnote lk) '(org-activate-footnote-links))
  4951. ;; Targets.
  4952. (list org-radio-target-regexp '(0 'org-target t))
  4953. (list org-target-regexp '(0 'org-target t))
  4954. ;; Diary sexps.
  4955. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  4956. ;; Macro
  4957. '(org-fontify-macros)
  4958. ;; TODO keyword
  4959. (list (format org-heading-keyword-regexp-format
  4960. org-todo-regexp)
  4961. '(2 (org-get-todo-face 2) t))
  4962. ;; DONE
  4963. (if org-fontify-done-headline
  4964. (list (format org-heading-keyword-regexp-format
  4965. (concat
  4966. "\\(?:"
  4967. (mapconcat 'regexp-quote org-done-keywords "\\|")
  4968. "\\)"))
  4969. '(2 'org-headline-done t))
  4970. nil)
  4971. ;; Priorities
  4972. '(org-font-lock-add-priority-faces)
  4973. ;; Tags
  4974. '(org-font-lock-add-tag-faces)
  4975. ;; Tags groups
  4976. (when (and org-group-tags org-tag-groups-alist)
  4977. (list (concat org-outline-regexp-bol ".+\\(:"
  4978. (regexp-opt (mapcar 'car org-tag-groups-alist))
  4979. ":\\).*$")
  4980. '(1 'org-tag-group prepend)))
  4981. ;; Special keywords
  4982. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  4983. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  4984. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  4985. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  4986. ;; Emphasis
  4987. (when em '(org-do-emphasis-faces))
  4988. ;; Checkboxes
  4989. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  4990. 1 'org-checkbox prepend)
  4991. (when (cdr (assq 'checkbox org-list-automatic-rules))
  4992. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  4993. (0 (org-get-checkbox-statistics-face) t)))
  4994. ;; Description list items
  4995. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  4996. 1 'org-list-dt prepend)
  4997. ;; ARCHIVEd headings
  4998. (list (concat
  4999. org-outline-regexp-bol
  5000. "\\(.*:" org-archive-tag ":.*\\)")
  5001. '(1 'org-archived prepend))
  5002. ;; Specials
  5003. '(org-do-latex-and-related)
  5004. '(org-fontify-entities)
  5005. '(org-raise-scripts)
  5006. ;; Code
  5007. '(org-activate-code (1 'org-code t))
  5008. ;; COMMENT
  5009. (list (format
  5010. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5011. org-todo-regexp
  5012. org-comment-string)
  5013. '(9 'org-special-keyword t))
  5014. ;; Blocks and meta lines
  5015. '(org-fontify-meta-lines-and-blocks))))
  5016. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5017. (run-hooks 'org-font-lock-set-keywords-hook)
  5018. ;; Now set the full font-lock-keywords
  5019. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5020. (setq-local font-lock-defaults
  5021. '(org-font-lock-keywords t nil nil backward-paragraph))
  5022. (setq-local font-lock-extend-after-change-region-function
  5023. #'org-fontify-extend-region)
  5024. (kill-local-variable 'font-lock-keywords)
  5025. nil))
  5026. (defun org-toggle-pretty-entities ()
  5027. "Toggle the composition display of entities as UTF8 characters."
  5028. (interactive)
  5029. (setq-local org-pretty-entities (not org-pretty-entities))
  5030. (org-restart-font-lock)
  5031. (if org-pretty-entities
  5032. (message "Entities are now displayed as UTF8 characters")
  5033. (save-restriction
  5034. (widen)
  5035. (decompose-region (point-min) (point-max))
  5036. (message "Entities are now displayed as plain text"))))
  5037. (defvar-local org-custom-properties-overlays nil
  5038. "List of overlays used for custom properties.")
  5039. (defun org-toggle-custom-properties-visibility ()
  5040. "Display or hide properties in `org-custom-properties'."
  5041. (interactive)
  5042. (if org-custom-properties-overlays
  5043. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5044. (setq org-custom-properties-overlays nil))
  5045. (when org-custom-properties
  5046. (org-with-wide-buffer
  5047. (goto-char (point-min))
  5048. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5049. (while (re-search-forward regexp nil t)
  5050. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5051. (when (and end (< (point) end))
  5052. ;; Hide first custom property in current drawer.
  5053. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5054. (overlay-put o 'invisible t)
  5055. (overlay-put o 'org-custom-property t)
  5056. (push o org-custom-properties-overlays))
  5057. ;; Hide additional custom properties in the same drawer.
  5058. (while (re-search-forward regexp end t)
  5059. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5060. (overlay-put o 'invisible t)
  5061. (overlay-put o 'org-custom-property t)
  5062. (push o org-custom-properties-overlays)))))
  5063. ;; Each entry is limited to a single property drawer.
  5064. (outline-next-heading)))))))
  5065. (defun org-fontify-entities (limit)
  5066. "Find an entity to fontify."
  5067. (let (ee)
  5068. (when org-pretty-entities
  5069. (catch 'match
  5070. ;; "\_ "-family is left out on purpose. Only the first one,
  5071. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5072. ;; confusing when adding a second white space character.
  5073. (while (re-search-forward
  5074. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5075. limit t)
  5076. (when (and (not (org-at-comment-p))
  5077. (setq ee (org-entity-get (match-string 1)))
  5078. (= (length (nth 6 ee)) 1))
  5079. (let* ((end (if (equal (match-string 2) "{}")
  5080. (match-end 2)
  5081. (match-end 1))))
  5082. (add-text-properties
  5083. (match-beginning 0) end
  5084. (list 'font-lock-fontified t))
  5085. (compose-region (match-beginning 0) end
  5086. (nth 6 ee) nil)
  5087. (backward-char 1)
  5088. (throw 'match t))))
  5089. nil))))
  5090. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5091. "Fontify string S like in Org mode."
  5092. (with-temp-buffer
  5093. (insert s)
  5094. (let ((org-odd-levels-only odd-levels))
  5095. (org-mode)
  5096. (org-font-lock-ensure)
  5097. (buffer-string))))
  5098. (defvar org-m nil)
  5099. (defvar org-l nil)
  5100. (defvar org-f nil)
  5101. (defun org-get-level-face (n)
  5102. "Get the right face for match N in font-lock matching of headlines."
  5103. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5104. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5105. (if org-cycle-level-faces
  5106. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5107. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5108. (cond
  5109. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5110. ((eq n 2) org-f)
  5111. (t (unless org-level-color-stars-only org-f))))
  5112. (defun org-face-from-face-or-color (context inherit face-or-color)
  5113. "Create a face list that inherits INHERIT, but sets the foreground color.
  5114. When FACE-OR-COLOR is not a string, just return it."
  5115. (if (stringp face-or-color)
  5116. (list :inherit inherit
  5117. (cdr (assoc context org-faces-easy-properties))
  5118. face-or-color)
  5119. face-or-color))
  5120. (defun org-get-todo-face (kwd)
  5121. "Get the right face for a TODO keyword KWD.
  5122. If KWD is a number, get the corresponding match group."
  5123. (when (numberp kwd) (setq kwd (match-string kwd)))
  5124. (or (org-face-from-face-or-color
  5125. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5126. (and (member kwd org-done-keywords) 'org-done)
  5127. 'org-todo))
  5128. (defun org-get-priority-face (priority)
  5129. "Get the right face for PRIORITY.
  5130. PRIORITY is a character."
  5131. (or (org-face-from-face-or-color
  5132. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5133. 'org-priority))
  5134. (defun org-get-tag-face (tag)
  5135. "Get the right face for TAG.
  5136. If TAG is a number, get the corresponding match group."
  5137. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5138. (or (org-face-from-face-or-color
  5139. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5140. 'org-tag)))
  5141. (defun org-font-lock-add-priority-faces (limit)
  5142. "Add the special priority faces."
  5143. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5144. (add-text-properties
  5145. (match-beginning 1) (match-end 1)
  5146. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5147. 'font-lock-fontified t))))
  5148. (defun org-font-lock-add-tag-faces (limit)
  5149. "Add the special tag faces."
  5150. (when (and org-tag-faces org-tags-special-faces-re)
  5151. (while (re-search-forward org-tags-special-faces-re limit t)
  5152. (add-text-properties (match-beginning 1) (match-end 1)
  5153. (list 'face (org-get-tag-face 1)
  5154. 'font-lock-fontified t))
  5155. (backward-char 1))))
  5156. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5157. "Remove fontification and activation overlays from links."
  5158. (font-lock-default-unfontify-region beg end)
  5159. (let* ((buffer-undo-list t)
  5160. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5161. (inhibit-modification-hooks t)
  5162. deactivate-mark buffer-file-name buffer-file-truename)
  5163. (decompose-region beg end)
  5164. (remove-text-properties beg end
  5165. '(mouse-face t keymap t org-linked-text t
  5166. invisible t intangible t
  5167. org-emphasis t))
  5168. (org-remove-font-lock-display-properties beg end)))
  5169. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5170. ((raise 0.3) (height 0.7))
  5171. ((raise -0.5))
  5172. ((raise 0.5)))
  5173. "Display properties for showing superscripts and subscripts.")
  5174. (defun org-remove-font-lock-display-properties (beg end)
  5175. "Remove specific display properties that have been added by font lock.
  5176. The will remove the raise properties that are used to show superscripts
  5177. and subscripts."
  5178. (let (next prop)
  5179. (while (< beg end)
  5180. (setq next (next-single-property-change beg 'display nil end)
  5181. prop (get-text-property beg 'display))
  5182. (when (member prop org-script-display)
  5183. (put-text-property beg next 'display nil))
  5184. (setq beg next))))
  5185. (defun org-raise-scripts (limit)
  5186. "Add raise properties to sub/superscripts."
  5187. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5188. (re-search-forward
  5189. (if (eq org-use-sub-superscripts t)
  5190. org-match-substring-regexp
  5191. org-match-substring-with-braces-regexp)
  5192. limit t))
  5193. (let* ((pos (point)) table-p comment-p
  5194. (mpos (match-beginning 3))
  5195. (emph-p (get-text-property mpos 'org-emphasis))
  5196. (link-p (get-text-property mpos 'mouse-face))
  5197. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5198. (goto-char (point-at-bol))
  5199. (setq table-p (looking-at-p org-table-dataline-regexp)
  5200. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5201. (goto-char pos)
  5202. ;; Handle a_b^c
  5203. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5204. (unless (or comment-p emph-p link-p keyw-p)
  5205. (put-text-property (match-beginning 3) (match-end 0)
  5206. 'display
  5207. (if (equal (char-after (match-beginning 2)) ?^)
  5208. (nth (if table-p 3 1) org-script-display)
  5209. (nth (if table-p 2 0) org-script-display)))
  5210. (add-text-properties (match-beginning 2) (match-end 2)
  5211. (list 'invisible t))
  5212. (when (and (eq (char-after (match-beginning 3)) ?{)
  5213. (eq (char-before (match-end 3)) ?}))
  5214. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5215. (list 'invisible t))
  5216. (add-text-properties (1- (match-end 3)) (match-end 3)
  5217. (list 'invisible t))))
  5218. t)))
  5219. (defun org-remove-empty-overlays-at (pos)
  5220. "Remove outline overlays that do not contain non-white stuff."
  5221. (dolist (o (overlays-at pos))
  5222. (and (eq 'outline (overlay-get o 'invisible))
  5223. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5224. (overlay-end o))))
  5225. (delete-overlay o))))
  5226. (defun org-show-empty-lines-in-parent ()
  5227. "Move to the parent and re-show empty lines before visible headlines."
  5228. (save-excursion
  5229. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5230. (org-cycle-show-empty-lines context))))
  5231. (defun org-files-list ()
  5232. "Return `org-agenda-files' list, plus all open Org files.
  5233. This is useful for operations that need to scan all of a user's
  5234. open and agenda-wise Org files."
  5235. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5236. (dolist (buf (buffer-list))
  5237. (with-current-buffer buf
  5238. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5239. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5240. :test #'equal))))
  5241. files))
  5242. (defsubst org-entry-beginning-position ()
  5243. "Return the beginning position of the current entry."
  5244. (save-excursion (org-back-to-heading t) (point)))
  5245. (defsubst org-entry-end-position ()
  5246. "Return the end position of the current entry."
  5247. (save-excursion (outline-next-heading) (point)))
  5248. (defun org-subtree-end-visible-p ()
  5249. "Is the end of the current subtree visible?"
  5250. (pos-visible-in-window-p
  5251. (save-excursion (org-end-of-subtree t) (point))))
  5252. (defun org-first-headline-recenter ()
  5253. "Move cursor to the first headline and recenter the headline."
  5254. (let ((window (get-buffer-window)))
  5255. (when window
  5256. (goto-char (point-min))
  5257. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5258. (set-window-start window (line-beginning-position))))))
  5259. ;;; Visibility (headlines, blocks, drawers)
  5260. ;;;; Headlines visibility
  5261. (defun org-show-entry ()
  5262. "Show the body directly following this heading.
  5263. Show the heading too, if it is currently invisible."
  5264. (interactive)
  5265. (save-excursion
  5266. (ignore-errors
  5267. (org-back-to-heading t)
  5268. (org-flag-region
  5269. (line-end-position 0)
  5270. (save-excursion
  5271. (if (re-search-forward
  5272. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5273. (match-beginning 1)
  5274. (point-max)))
  5275. nil
  5276. 'outline))))
  5277. (defun org-show-children (&optional level)
  5278. "Show all direct subheadings of this heading.
  5279. Prefix arg LEVEL is how many levels below the current level
  5280. should be shown. Default is enough to cause the following
  5281. heading to appear."
  5282. (interactive "p")
  5283. (save-excursion
  5284. (org-back-to-heading t)
  5285. (let* ((current-level (funcall outline-level))
  5286. (max-level (org-get-valid-level
  5287. current-level
  5288. (if level (prefix-numeric-value level) 1)))
  5289. (end (save-excursion (org-end-of-subtree t t)))
  5290. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5291. (past-first-child nil)
  5292. ;; Make sure to skip inlinetasks.
  5293. (re (format regexp-fmt
  5294. current-level
  5295. (cond
  5296. ((not (featurep 'org-inlinetask)) "")
  5297. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5298. 3))
  5299. (t (1- org-inlinetask-min-level))))))
  5300. ;; Display parent heading.
  5301. (org-flag-heading nil)
  5302. (forward-line)
  5303. ;; Display children. First child may be deeper than expected
  5304. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5305. ;; MAX-LEVEL accordingly.
  5306. (while (re-search-forward re end t)
  5307. (unless past-first-child
  5308. (setq re (format regexp-fmt
  5309. current-level
  5310. (max (funcall outline-level) max-level)))
  5311. (setq past-first-child t))
  5312. (org-flag-heading nil)))))
  5313. (defun org-show-subtree ()
  5314. "Show everything after this heading at deeper levels."
  5315. (interactive)
  5316. (org-flag-region
  5317. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5318. ;;;; Blocks visibility
  5319. (defun org-hide-block-toggle-maybe ()
  5320. "Toggle visibility of block at point.
  5321. Unlike to `org-hide-block-toggle', this function does not throw
  5322. an error. Return a non-nil value when toggling is successful."
  5323. (interactive)
  5324. (ignore-errors (org-hide-block-toggle)))
  5325. (defun org-hide-block-toggle (&optional force)
  5326. "Toggle the visibility of the current block.
  5327. When optional argument FORCE is `off', make block visible. If it
  5328. is non-nil, hide it unconditionally. Throw an error when not at
  5329. a block. Return a non-nil value when toggling is successful."
  5330. (interactive)
  5331. (let ((element (org-element-at-point)))
  5332. (unless (memq (org-element-type element)
  5333. '(center-block comment-block dynamic-block example-block
  5334. export-block quote-block special-block
  5335. src-block verse-block))
  5336. (user-error "Not at a block"))
  5337. (let* ((post (org-element-property :post-affiliated element))
  5338. (start (save-excursion
  5339. (goto-char post)
  5340. (line-end-position)))
  5341. (end (save-excursion
  5342. (goto-char (org-element-property :end element))
  5343. (skip-chars-backward " \t\n")
  5344. (line-end-position))))
  5345. ;; Do nothing when not before or at the block opening line or at
  5346. ;; the block closing line.
  5347. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5348. (cond ((eq force 'off)
  5349. (org-flag-region start end nil 'org-hide-block))
  5350. (force
  5351. (org-flag-region start end t 'org-hide-block))
  5352. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5353. (org-flag-region start end nil 'org-hide-block))
  5354. (t
  5355. (org-flag-region start end t 'org-hide-block)))
  5356. ;; When the block is hidden away, make sure point is left in
  5357. ;; a visible part of the buffer.
  5358. (when (invisible-p (max (1- (point)) (point-min)))
  5359. (goto-char post))
  5360. ;; Signal success.
  5361. t))))
  5362. (defun org-hide-block-toggle-all ()
  5363. "Toggle the visibility of all blocks in the current buffer."
  5364. (org-block-map 'org-hide-block-toggle))
  5365. (defun org-hide-block-all ()
  5366. "Fold all blocks in the current buffer."
  5367. (interactive)
  5368. (org-show-all '(blocks))
  5369. (org-block-map 'org-hide-block-toggle-maybe))
  5370. ;;;; Drawers visibility
  5371. (defun org-cycle-hide-drawers (state &optional exceptions)
  5372. "Re-hide all drawers after a visibility state change.
  5373. STATE should be one of the symbols listed in the docstring of
  5374. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5375. a list of strings specifying which drawers should not be hidden."
  5376. (when (and (derived-mode-p 'org-mode)
  5377. (not (memq state '(overview folded contents))))
  5378. (save-excursion
  5379. (let* ((globalp (eq state 'all))
  5380. (beg (if globalp (point-min) (point)))
  5381. (end (if globalp (point-max)
  5382. (if (eq state 'children)
  5383. (save-excursion (outline-next-heading) (point))
  5384. (org-end-of-subtree t)))))
  5385. (goto-char beg)
  5386. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5387. (unless (member-ignore-case (match-string 1) exceptions)
  5388. (let ((drawer (org-element-at-point)))
  5389. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5390. (org-flag-drawer t drawer)
  5391. ;; Make sure to skip drawer entirely or we might flag
  5392. ;; it another time when matching its ending line with
  5393. ;; `org-drawer-regexp'.
  5394. (goto-char (org-element-property :end drawer))))))))))
  5395. (defun org-flag-drawer (flag &optional element beg end)
  5396. "When FLAG is non-nil, hide the drawer we are at.
  5397. Otherwise make it visible.
  5398. When optional argument ELEMENT is a parsed drawer, as returned by
  5399. `org-element-at-point', hide or show that drawer instead.
  5400. When buffer positions BEG and END are provided, hide or show that
  5401. region as a drawer without further ado."
  5402. (if (and beg end) (org-flag-region beg end flag 'org-hide-drawer)
  5403. (let ((drawer (or element
  5404. (and (save-excursion
  5405. (beginning-of-line)
  5406. (looking-at-p org-drawer-regexp))
  5407. (org-element-at-point)))))
  5408. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5409. (let ((post (org-element-property :post-affiliated drawer)))
  5410. (org-flag-region
  5411. (save-excursion (goto-char post) (line-end-position))
  5412. (save-excursion (goto-char (org-element-property :end drawer))
  5413. (skip-chars-backward " \t\n")
  5414. (line-end-position))
  5415. flag 'org-hide-drawer)
  5416. ;; When the drawer is hidden away, make sure point lies in
  5417. ;; a visible part of the buffer.
  5418. (when (invisible-p (max (1- (point)) (point-min)))
  5419. (goto-char post)))))))
  5420. ;;;; Visibility cycling
  5421. (defvar-local org-cycle-global-status nil)
  5422. (put 'org-cycle-global-status 'org-state t)
  5423. (defvar-local org-cycle-subtree-status nil)
  5424. (put 'org-cycle-subtree-status 'org-state t)
  5425. (defun org-show-all (&optional types)
  5426. "Show all contents in the visible part of the buffer.
  5427. By default, the function expands headings, blocks and drawers.
  5428. When optional argument TYPE is a list of symbols among `blocks',
  5429. `drawers' and `headings', to only expand one specific type."
  5430. (interactive)
  5431. (dolist (type (or types '(blocks drawers headings)))
  5432. (org-flag-region (point-min) (point-max) nil
  5433. (pcase type
  5434. (`blocks 'org-hide-block)
  5435. (`drawers 'org-hide-drawer)
  5436. (`headings 'outline)
  5437. (_ (error "Invalid type: %S" type))))))
  5438. ;;;###autoload
  5439. (defun org-cycle (&optional arg)
  5440. "TAB-action and visibility cycling for Org mode.
  5441. This is the command invoked in Org mode by the `TAB' key. Its main
  5442. purpose is outline visibility cycling, but it also invokes other actions
  5443. in special contexts.
  5444. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5445. the entire
  5446. buffer through 3 states (global cycling)
  5447. 1. OVERVIEW: Show only top-level headlines.
  5448. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5449. 3. SHOW ALL: Show everything.
  5450. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5451. switch to the startup visibility,
  5452. determined by the variable `org-startup-folded', and by any VISIBILITY
  5453. properties in the buffer.
  5454. With a `\\[universal-argument] \\[universal-argument] \
  5455. \\[universal-argument]' prefix argument, show the entire buffer, including
  5456. any drawers.
  5457. When inside a table, re-align the table and move to the next field.
  5458. When point is at the beginning of a headline, rotate the subtree started
  5459. by this line through 3 different states (local cycling)
  5460. 1. FOLDED: Only the main headline is shown.
  5461. 2. CHILDREN: The main headline and the direct children are shown.
  5462. From this state, you can move to one of the children
  5463. and zoom in further.
  5464. 3. SUBTREE: Show the entire subtree, including body text.
  5465. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5466. When point is at the beginning of an empty headline and the variable
  5467. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5468. of the headline by demoting and promoting it to likely levels. This
  5469. speeds up creation document structure by pressing `TAB' once or several
  5470. times right after creating a new headline.
  5471. When there is a numeric prefix, go up to a heading with level ARG, do
  5472. a `show-subtree' and return to the previous cursor position. If ARG
  5473. is negative, go up that many levels.
  5474. When point is not at the beginning of a headline, execute the global
  5475. binding for `TAB', which is re-indenting the line. See the option
  5476. `org-cycle-emulate-tab' for details.
  5477. As a special case, if point is at the beginning of the buffer and there is
  5478. no headline in line 1, this function will act as if called with prefix arg
  5479. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5480. prefix arg, but only
  5481. if the variable `org-cycle-global-at-bob' is t."
  5482. (interactive "P")
  5483. (org-load-modules-maybe)
  5484. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5485. (and org-cycle-level-after-item/entry-creation
  5486. (or (org-cycle-level)
  5487. (org-cycle-item-indentation))))
  5488. (let* ((limit-level
  5489. (or org-cycle-max-level
  5490. (and (boundp 'org-inlinetask-min-level)
  5491. org-inlinetask-min-level
  5492. (1- org-inlinetask-min-level))))
  5493. (nstars (and limit-level
  5494. (if org-odd-levels-only
  5495. (and limit-level (1- (* limit-level 2)))
  5496. limit-level)))
  5497. (org-outline-regexp
  5498. (if (not (derived-mode-p 'org-mode))
  5499. outline-regexp
  5500. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5501. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5502. (not (looking-at org-outline-regexp))))
  5503. (org-cycle-hook
  5504. (if bob-special
  5505. (delq 'org-optimize-window-after-visibility-change
  5506. (copy-sequence org-cycle-hook))
  5507. org-cycle-hook))
  5508. (pos (point)))
  5509. (cond
  5510. ((equal arg '(16))
  5511. (setq last-command 'dummy)
  5512. (org-set-startup-visibility)
  5513. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5514. ((equal arg '(64))
  5515. (org-show-all)
  5516. (org-unlogged-message "Entire buffer visible, including drawers"))
  5517. ((equal arg '(4)) (org-cycle-internal-global))
  5518. ;; Try hiding block at point.
  5519. ((org-hide-block-toggle-maybe))
  5520. ;; Try cdlatex TAB completion
  5521. ((org-try-cdlatex-tab))
  5522. ;; Table: enter it or move to the next field.
  5523. ((org-at-table-p 'any)
  5524. (if (org-at-table.el-p)
  5525. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5526. Use `\\[org-edit-special]' to edit table.el tables"))
  5527. (if arg (org-table-edit-field t)
  5528. (org-table-justify-field-maybe)
  5529. (call-interactively 'org-table-next-field))))
  5530. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5531. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5532. (bob-special (org-cycle-internal-global))
  5533. ;; Drawers: delegate to `org-flag-drawer'.
  5534. ((save-excursion
  5535. (beginning-of-line 1)
  5536. (looking-at org-drawer-regexp))
  5537. (org-flag-drawer ; toggle block visibility
  5538. (not (get-char-property (match-end 0) 'invisible))))
  5539. ;; Show-subtree, ARG levels up from here.
  5540. ((integerp arg)
  5541. (save-excursion
  5542. (org-back-to-heading)
  5543. (outline-up-heading (if (< arg 0) (- arg)
  5544. (- (funcall outline-level) arg)))
  5545. (org-show-subtree)))
  5546. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5547. ((and (featurep 'org-inlinetask)
  5548. (org-inlinetask-at-task-p)
  5549. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5550. (org-inlinetask-toggle-visibility))
  5551. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5552. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5553. (save-excursion (move-beginning-of-line 1)
  5554. (looking-at org-outline-regexp)))
  5555. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5556. (org-cycle-internal-local))
  5557. ;; From there: TAB emulation and template completion.
  5558. (buffer-read-only (org-back-to-heading))
  5559. ((run-hook-with-args-until-success
  5560. 'org-tab-after-check-for-cycling-hook))
  5561. ((run-hook-with-args-until-success
  5562. 'org-tab-before-tab-emulation-hook))
  5563. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5564. (or (not (bolp))
  5565. (not (looking-at org-outline-regexp))))
  5566. (call-interactively (global-key-binding "\t")))
  5567. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5568. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5569. (or (and (eq org-cycle-emulate-tab 'white)
  5570. (= (match-end 0) (point-at-eol)))
  5571. (and (eq org-cycle-emulate-tab 'whitestart)
  5572. (>= (match-end 0) pos))))
  5573. t
  5574. (eq org-cycle-emulate-tab t))
  5575. (call-interactively (global-key-binding "\t")))
  5576. (t (save-excursion
  5577. (org-back-to-heading)
  5578. (org-cycle)))))))
  5579. (defun org-cycle-internal-global ()
  5580. "Do the global cycling action."
  5581. ;; Hack to avoid display of messages for .org attachments in Gnus
  5582. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5583. (cond
  5584. ((and (eq last-command this-command)
  5585. (eq org-cycle-global-status 'overview))
  5586. ;; We just created the overview - now do table of contents
  5587. ;; This can be slow in very large buffers, so indicate action
  5588. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5589. (unless ga (org-unlogged-message "CONTENTS..."))
  5590. (org-content)
  5591. (unless ga (org-unlogged-message "CONTENTS...done"))
  5592. (setq org-cycle-global-status 'contents)
  5593. (run-hook-with-args 'org-cycle-hook 'contents))
  5594. ((and (eq last-command this-command)
  5595. (eq org-cycle-global-status 'contents))
  5596. ;; We just showed the table of contents - now show everything
  5597. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5598. (org-show-all '(headings blocks))
  5599. (unless ga (org-unlogged-message "SHOW ALL"))
  5600. (setq org-cycle-global-status 'all)
  5601. (run-hook-with-args 'org-cycle-hook 'all))
  5602. (t
  5603. ;; Default action: go to overview
  5604. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5605. (org-overview)
  5606. (unless ga (org-unlogged-message "OVERVIEW"))
  5607. (setq org-cycle-global-status 'overview)
  5608. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5609. (defvar org-called-with-limited-levels nil
  5610. "Non-nil when `org-with-limited-levels' is currently active.")
  5611. (defun org-cycle-internal-local ()
  5612. "Do the local cycling action."
  5613. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5614. ;; First, determine end of headline (EOH), end of subtree or item
  5615. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5616. (save-excursion
  5617. (if (org-at-item-p)
  5618. (progn
  5619. (beginning-of-line)
  5620. (setq struct (org-list-struct))
  5621. (setq eoh (point-at-eol))
  5622. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5623. (setq has-children (org-list-has-child-p (point) struct)))
  5624. (org-back-to-heading)
  5625. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5626. (setq eos (save-excursion (org-end-of-subtree t t)
  5627. (when (bolp) (backward-char)) (point)))
  5628. (setq has-children
  5629. (or (save-excursion
  5630. (let ((level (funcall outline-level)))
  5631. (outline-next-heading)
  5632. (and (org-at-heading-p t)
  5633. (> (funcall outline-level) level))))
  5634. (save-excursion
  5635. (org-list-search-forward (org-item-beginning-re) eos t)))))
  5636. ;; Determine end invisible part of buffer (EOL)
  5637. (beginning-of-line 2)
  5638. (while (and (not (eobp)) ;This is like `next-line'.
  5639. (get-char-property (1- (point)) 'invisible))
  5640. (goto-char (next-single-char-property-change (point) 'invisible))
  5641. (and (eolp) (beginning-of-line 2)))
  5642. (setq eol (point)))
  5643. ;; Find out what to do next and set `this-command'
  5644. (cond
  5645. ((= eos eoh)
  5646. ;; Nothing is hidden behind this heading
  5647. (unless (org-before-first-heading-p)
  5648. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5649. (org-unlogged-message "EMPTY ENTRY")
  5650. (setq org-cycle-subtree-status nil)
  5651. (save-excursion
  5652. (goto-char eos)
  5653. (outline-next-heading)
  5654. (when (org-invisible-p) (org-flag-heading nil))))
  5655. ((and (or (>= eol eos)
  5656. (not (string-match "\\S-" (buffer-substring eol eos))))
  5657. (or has-children
  5658. (not (setq children-skipped
  5659. org-cycle-skip-children-state-if-no-children))))
  5660. ;; Entire subtree is hidden in one line: children view
  5661. (unless (org-before-first-heading-p)
  5662. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5663. (if (org-at-item-p)
  5664. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5665. (org-show-entry)
  5666. (org-with-limited-levels (org-show-children))
  5667. (org-show-set-visibility 'canonical)
  5668. ;; Fold every list in subtree to top-level items.
  5669. (when (eq org-cycle-include-plain-lists 'integrate)
  5670. (save-excursion
  5671. (org-back-to-heading)
  5672. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5673. (beginning-of-line 1)
  5674. (let* ((struct (org-list-struct))
  5675. (prevs (org-list-prevs-alist struct))
  5676. (end (org-list-get-bottom-point struct)))
  5677. (dolist (e (org-list-get-all-items (point) struct prevs))
  5678. (org-list-set-item-visibility e struct 'folded))
  5679. (goto-char (if (< end eos) end eos)))))))
  5680. (org-unlogged-message "CHILDREN")
  5681. (save-excursion
  5682. (goto-char eos)
  5683. (outline-next-heading)
  5684. (when (org-invisible-p) (org-flag-heading nil)))
  5685. (setq org-cycle-subtree-status 'children)
  5686. (unless (org-before-first-heading-p)
  5687. (run-hook-with-args 'org-cycle-hook 'children)))
  5688. ((or children-skipped
  5689. (and (eq last-command this-command)
  5690. (eq org-cycle-subtree-status 'children)))
  5691. ;; We just showed the children, or no children are there,
  5692. ;; now show everything.
  5693. (unless (org-before-first-heading-p)
  5694. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5695. (org-flag-region eoh eos nil 'outline)
  5696. (org-unlogged-message
  5697. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5698. (setq org-cycle-subtree-status 'subtree)
  5699. (unless (org-before-first-heading-p)
  5700. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5701. (t
  5702. ;; Default action: hide the subtree.
  5703. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5704. (org-flag-region eoh eos t 'outline)
  5705. (org-unlogged-message "FOLDED")
  5706. (setq org-cycle-subtree-status 'folded)
  5707. (unless (org-before-first-heading-p)
  5708. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5709. ;;;###autoload
  5710. (defun org-global-cycle (&optional arg)
  5711. "Cycle the global visibility. For details see `org-cycle'.
  5712. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5713. With a numeric prefix, show all headlines up to that level."
  5714. (interactive "P")
  5715. (let ((org-cycle-include-plain-lists
  5716. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  5717. (cond
  5718. ((integerp arg)
  5719. (org-show-all '(headings blocks))
  5720. (outline-hide-sublevels arg)
  5721. (setq org-cycle-global-status 'contents))
  5722. ((equal arg '(4))
  5723. (org-set-startup-visibility)
  5724. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5725. (t
  5726. (org-cycle '(4))))))
  5727. (defun org-set-startup-visibility ()
  5728. "Set the visibility required by startup options and properties."
  5729. (cond
  5730. ((eq org-startup-folded t)
  5731. (org-overview))
  5732. ((eq org-startup-folded 'content)
  5733. (org-content))
  5734. ((or (eq org-startup-folded 'showeverything)
  5735. (eq org-startup-folded nil))
  5736. (org-show-all)))
  5737. (unless (eq org-startup-folded 'showeverything)
  5738. (when org-hide-block-startup (org-hide-block-all))
  5739. (org-set-visibility-according-to-property)
  5740. (org-cycle-hide-archived-subtrees 'all)
  5741. (org-cycle-hide-drawers 'all)
  5742. (org-cycle-show-empty-lines t)))
  5743. (defun org-set-visibility-according-to-property ()
  5744. "Switch subtree visibility according to VISIBILITY property."
  5745. (interactive)
  5746. (let ((regexp (org-re-property "VISIBILITY")))
  5747. (org-with-point-at 1
  5748. (while (re-search-forward regexp nil t)
  5749. (let ((state (match-string 3)))
  5750. (if (not (org-at-property-p)) (outline-next-heading)
  5751. (save-excursion
  5752. (org-back-to-heading t)
  5753. (org-flag-subtree t)
  5754. (org-reveal)
  5755. (pcase state
  5756. ("folded"
  5757. (org-flag-subtree t))
  5758. ("children"
  5759. (org-show-hidden-entry)
  5760. (org-show-children))
  5761. ("content"
  5762. (save-excursion
  5763. (save-restriction
  5764. (org-narrow-to-subtree)
  5765. (org-content))))
  5766. ((or "all" "showall")
  5767. (outline-show-subtree))
  5768. (_ nil)))
  5769. (org-end-of-subtree)))))))
  5770. (defun org-overview ()
  5771. "Switch to overview mode, showing only top-level headlines.
  5772. This shows all headlines with a level equal or greater than the level
  5773. of the first headline in the buffer. This is important, because if the
  5774. first headline is not level one, then (hide-sublevels 1) gives confusing
  5775. results."
  5776. (interactive)
  5777. (save-excursion
  5778. (let ((level
  5779. (save-excursion
  5780. (goto-char (point-min))
  5781. (when (re-search-forward org-outline-regexp-bol nil t)
  5782. (goto-char (match-beginning 0))
  5783. (funcall outline-level)))))
  5784. (and level (outline-hide-sublevels level)))))
  5785. (defun org-content (&optional arg)
  5786. "Show all headlines in the buffer, like a table of contents.
  5787. With numerical argument N, show content up to level N."
  5788. (interactive "P")
  5789. (org-overview)
  5790. (save-excursion
  5791. ;; Visit all headings and show their offspring
  5792. (and (integerp arg) (org-overview))
  5793. (goto-char (point-max))
  5794. (catch 'exit
  5795. (while (and (progn (condition-case nil
  5796. (outline-previous-visible-heading 1)
  5797. (error (goto-char (point-min))))
  5798. t)
  5799. (looking-at org-outline-regexp))
  5800. (if (integerp arg)
  5801. (org-show-children (1- arg))
  5802. (outline-show-branches))
  5803. (when (bobp) (throw 'exit nil))))))
  5804. (defun org-optimize-window-after-visibility-change (state)
  5805. "Adjust the window after a change in outline visibility.
  5806. This function is the default value of the hook `org-cycle-hook'."
  5807. (when (get-buffer-window (current-buffer))
  5808. (cond
  5809. ((eq state 'content) nil)
  5810. ((eq state 'all) nil)
  5811. ((eq state 'folded) nil)
  5812. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  5813. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  5814. (defun org-clean-visibility-after-subtree-move ()
  5815. "Fix visibility issues after moving a subtree."
  5816. ;; First, find a reasonable region to look at:
  5817. ;; Start two siblings above, end three below
  5818. (let* ((beg (save-excursion
  5819. (and (org-get-last-sibling)
  5820. (org-get-last-sibling))
  5821. (point)))
  5822. (end (save-excursion
  5823. (and (org-get-next-sibling)
  5824. (org-get-next-sibling)
  5825. (org-get-next-sibling))
  5826. (if (org-at-heading-p)
  5827. (point-at-eol)
  5828. (point))))
  5829. (level (looking-at "\\*+"))
  5830. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5831. (save-excursion
  5832. (save-restriction
  5833. (narrow-to-region beg end)
  5834. (when re
  5835. ;; Properly fold already folded siblings
  5836. (goto-char (point-min))
  5837. (while (re-search-forward re nil t)
  5838. (when (and (not (org-invisible-p))
  5839. (org-invisible-p (line-end-position)))
  5840. (outline-hide-entry))))
  5841. (org-cycle-hide-drawers 'all)
  5842. (org-cycle-show-empty-lines 'overview)))))
  5843. (defun org-cycle-show-empty-lines (state)
  5844. "Show empty lines above all visible headlines.
  5845. The region to be covered depends on STATE when called through
  5846. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5847. entire buffer covered. Note that an empty line is only shown if there
  5848. are at least `org-cycle-separator-lines' empty lines before the headline."
  5849. (when (/= org-cycle-separator-lines 0)
  5850. (save-excursion
  5851. (let* ((n (abs org-cycle-separator-lines))
  5852. (re (cond
  5853. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5854. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5855. (t (let ((ns (number-to-string (- n 2))))
  5856. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5857. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5858. beg end)
  5859. (cond
  5860. ((memq state '(overview contents t))
  5861. (setq beg (point-min) end (point-max)))
  5862. ((memq state '(children folded))
  5863. (setq beg (point)
  5864. end (progn (org-end-of-subtree t t)
  5865. (line-beginning-position 2)))))
  5866. (when beg
  5867. (goto-char beg)
  5868. (while (re-search-forward re end t)
  5869. (unless (get-char-property (match-end 1) 'invisible)
  5870. (let ((e (match-end 1))
  5871. (b (if (>= org-cycle-separator-lines 0)
  5872. (match-beginning 1)
  5873. (save-excursion
  5874. (goto-char (match-beginning 0))
  5875. (skip-chars-backward " \t\n")
  5876. (line-end-position)))))
  5877. (org-flag-region b e nil 'outline))))))))
  5878. ;; Never hide empty lines at the end of the file.
  5879. (save-excursion
  5880. (goto-char (point-max))
  5881. (outline-previous-heading)
  5882. (outline-end-of-heading)
  5883. (when (and (looking-at "[ \t\n]+")
  5884. (= (match-end 0) (point-max)))
  5885. (org-flag-region (point) (match-end 0) nil 'outline))))
  5886. ;;;; Reveal point location
  5887. (defun org-show-context (&optional key)
  5888. "Make sure point and context are visible.
  5889. Optional argument KEY, when non-nil, is a symbol. See
  5890. `org-show-context-detail' for allowed values and how much is to
  5891. be shown."
  5892. (org-show-set-visibility
  5893. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  5894. ((cdr (assq key org-show-context-detail)))
  5895. (t (cdr (assq 'default org-show-context-detail))))))
  5896. (defun org-show-set-visibility (detail)
  5897. "Set visibility around point according to DETAIL.
  5898. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  5899. `tree', `canonical' or t. See `org-show-context-detail' for more
  5900. information."
  5901. ;; Show current heading and possibly its entry, following headline
  5902. ;; or all children.
  5903. (if (and (org-at-heading-p) (not (eq detail 'local)))
  5904. (org-flag-heading nil)
  5905. (org-show-entry)
  5906. ;; If point is hidden within a drawer or a block, make sure to
  5907. ;; expose it.
  5908. (dolist (o (overlays-at (point)))
  5909. (when (memq (overlay-get o 'invisible)
  5910. '(org-hide-block org-hide-drawer outline))
  5911. (delete-overlay o)))
  5912. (unless (org-before-first-heading-p)
  5913. (org-with-limited-levels
  5914. (cl-case detail
  5915. ((tree canonical t) (org-show-children))
  5916. ((nil minimal ancestors))
  5917. (t (save-excursion
  5918. (outline-next-heading)
  5919. (org-flag-heading nil)))))))
  5920. ;; Show all siblings.
  5921. (when (eq detail 'lineage) (org-show-siblings))
  5922. ;; Show ancestors, possibly with their children.
  5923. (when (memq detail '(ancestors lineage tree canonical t))
  5924. (save-excursion
  5925. (while (org-up-heading-safe)
  5926. (org-flag-heading nil)
  5927. (when (memq detail '(canonical t)) (org-show-entry))
  5928. (when (memq detail '(tree canonical t)) (org-show-children))))))
  5929. (defvar org-reveal-start-hook nil
  5930. "Hook run before revealing a location.")
  5931. (defun org-reveal (&optional siblings)
  5932. "Show current entry, hierarchy above it, and the following headline.
  5933. This can be used to show a consistent set of context around
  5934. locations exposed with `org-show-context'.
  5935. With optional argument SIBLINGS, on each level of the hierarchy all
  5936. siblings are shown. This repairs the tree structure to what it would
  5937. look like when opened with hierarchical calls to `org-cycle'.
  5938. With a \\[universal-argument] \\[universal-argument] prefix, \
  5939. go to the parent and show the entire tree."
  5940. (interactive "P")
  5941. (run-hooks 'org-reveal-start-hook)
  5942. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  5943. ((equal siblings '(16))
  5944. (save-excursion
  5945. (when (org-up-heading-safe)
  5946. (org-show-subtree)
  5947. (run-hook-with-args 'org-cycle-hook 'subtree))))
  5948. (t (org-show-set-visibility 'lineage))))
  5949. ;;; Indirect buffer display of subtrees
  5950. (defvar org-indirect-dedicated-frame nil
  5951. "This is the frame being used for indirect tree display.")
  5952. (defvar org-last-indirect-buffer nil)
  5953. (defun org-tree-to-indirect-buffer (&optional arg)
  5954. "Create indirect buffer and narrow it to current subtree.
  5955. With a numerical prefix ARG, go up to this level and then take that tree.
  5956. If ARG is negative, go up that many levels.
  5957. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  5958. indirect buffer previously made with this command, to avoid proliferation of
  5959. indirect buffers. However, when you call the command with a \
  5960. `\\[universal-argument]' prefix, or
  5961. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  5962. so that you can work with several indirect buffers at the same time. If
  5963. `org-indirect-buffer-display' is `dedicated-frame', the \
  5964. `\\[universal-argument]' prefix also
  5965. requests that a new frame be made for the new buffer, so that the dedicated
  5966. frame is not changed."
  5967. (interactive "P")
  5968. (let ((cbuf (current-buffer))
  5969. (cwin (selected-window))
  5970. (pos (point))
  5971. beg end level heading ibuf)
  5972. (save-excursion
  5973. (org-back-to-heading t)
  5974. (when (numberp arg)
  5975. (setq level (org-outline-level))
  5976. (when (< arg 0) (setq arg (+ level arg)))
  5977. (while (> (setq level (org-outline-level)) arg)
  5978. (org-up-heading-safe)))
  5979. (setq beg (point)
  5980. heading (org-get-heading 'no-tags))
  5981. (org-end-of-subtree t t)
  5982. (when (org-at-heading-p) (backward-char 1))
  5983. (setq end (point)))
  5984. (when (and (buffer-live-p org-last-indirect-buffer)
  5985. (not (eq org-indirect-buffer-display 'new-frame))
  5986. (not arg))
  5987. (kill-buffer org-last-indirect-buffer))
  5988. (setq ibuf (org-get-indirect-buffer cbuf heading)
  5989. org-last-indirect-buffer ibuf)
  5990. (cond
  5991. ((or (eq org-indirect-buffer-display 'new-frame)
  5992. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  5993. (select-frame (make-frame))
  5994. (delete-other-windows)
  5995. (pop-to-buffer-same-window ibuf)
  5996. (org-set-frame-title heading))
  5997. ((eq org-indirect-buffer-display 'dedicated-frame)
  5998. (raise-frame
  5999. (select-frame (or (and org-indirect-dedicated-frame
  6000. (frame-live-p org-indirect-dedicated-frame)
  6001. org-indirect-dedicated-frame)
  6002. (setq org-indirect-dedicated-frame (make-frame)))))
  6003. (delete-other-windows)
  6004. (pop-to-buffer-same-window ibuf)
  6005. (org-set-frame-title (concat "Indirect: " heading)))
  6006. ((eq org-indirect-buffer-display 'current-window)
  6007. (pop-to-buffer-same-window ibuf))
  6008. ((eq org-indirect-buffer-display 'other-window)
  6009. (pop-to-buffer ibuf))
  6010. (t (error "Invalid value")))
  6011. (narrow-to-region beg end)
  6012. (org-show-all '(headings blocks))
  6013. (goto-char pos)
  6014. (run-hook-with-args 'org-cycle-hook 'all)
  6015. (and (window-live-p cwin) (select-window cwin))))
  6016. (defun org-get-indirect-buffer (&optional buffer heading)
  6017. (setq buffer (or buffer (current-buffer)))
  6018. (let ((n 1) (base (buffer-name buffer)) bname)
  6019. (while (buffer-live-p
  6020. (get-buffer
  6021. (setq bname
  6022. (concat base "-"
  6023. (if heading (concat heading "-" (number-to-string n))
  6024. (number-to-string n))))))
  6025. (setq n (1+ n)))
  6026. (condition-case nil
  6027. (make-indirect-buffer buffer bname 'clone)
  6028. (error (make-indirect-buffer buffer bname)))))
  6029. (defun org-set-frame-title (title)
  6030. "Set the title of the current frame to the string TITLE."
  6031. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6032. ;;;; Structure editing
  6033. ;;; Inserting headlines
  6034. (defun org--line-empty-p (n)
  6035. "Is the Nth next line empty?
  6036. Counts the current line as N = 1 and the previous line as N = 0;
  6037. see `beginning-of-line'."
  6038. (save-excursion
  6039. (and (not (bobp))
  6040. (or (beginning-of-line n) t)
  6041. (save-match-data
  6042. (looking-at "[ \t]*$")))))
  6043. (defun org-previous-line-empty-p ()
  6044. "Is the previous line a blank line?
  6045. When NEXT is non-nil, check the next line instead."
  6046. (org--line-empty-p 0))
  6047. (defun org-next-line-empty-p ()
  6048. "Is the previous line a blank line?
  6049. When NEXT is non-nil, check the next line instead."
  6050. (org--line-empty-p 2))
  6051. (defun org--blank-before-heading-p (&optional parent)
  6052. "Non-nil when an empty line should precede a new heading here.
  6053. When optional argument PARENT is non-nil, consider parent
  6054. headline instead of current one."
  6055. (pcase (assq 'heading org-blank-before-new-entry)
  6056. (`(heading . auto)
  6057. (save-excursion
  6058. (org-with-limited-levels
  6059. (unless (and (org-before-first-heading-p)
  6060. (not (outline-next-heading)))
  6061. (org-back-to-heading t)
  6062. (when parent (org-up-heading-safe))
  6063. (cond ((not (bobp))
  6064. (org-previous-line-empty-p))
  6065. ((outline-next-heading)
  6066. (org-previous-line-empty-p))
  6067. ;; Ignore trailing spaces on last buffer line.
  6068. ((progn (skip-chars-backward " \t") (bolp))
  6069. (org-previous-line-empty-p))
  6070. (t nil))))))
  6071. (`(heading . ,value) value)
  6072. (_ nil)))
  6073. (defun org-insert-heading (&optional arg invisible-ok top)
  6074. "Insert a new heading or an item with the same depth at point.
  6075. If point is at the beginning of a heading, insert a new heading
  6076. or a new headline above the current one. When at the beginning
  6077. of a regular line of text, turn it into a heading.
  6078. If point is in the middle of a line, split it and create a new
  6079. headline with the text in the current line after point (see
  6080. `org-M-RET-may-split-line' on how to modify this behavior). As
  6081. a special case, on a headline, splitting can only happen on the
  6082. title itself. E.g., this excludes breaking stars or tags.
  6083. With a `\\[universal-argument]' prefix, set \
  6084. `org-insert-heading-respect-content' to
  6085. a non-nil value for the duration of the command. This forces the
  6086. insertion of a heading after the current subtree, independently
  6087. on the location of point.
  6088. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6089. insert the heading at the end of the tree
  6090. above the current heading. For example, if point is within a
  6091. 2nd-level heading, then it will insert a 2nd-level heading at
  6092. the end of the 1st-level parent subtree.
  6093. When INVISIBLE-OK is set, stop at invisible headlines when going
  6094. back. This is important for non-interactive uses of the
  6095. command.
  6096. When optional argument TOP is non-nil, insert a level 1 heading,
  6097. unconditionally."
  6098. (interactive "P")
  6099. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6100. (level (org-current-level))
  6101. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6102. (cond
  6103. ((or org-insert-heading-respect-content
  6104. (member arg '((4) (16)))
  6105. (and (not invisible-ok)
  6106. (invisible-p (max (1- (point)) (point-min)))))
  6107. ;; Position point at the location of insertion. Make sure we
  6108. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6109. (org-with-limited-levels
  6110. (if (not level) (outline-next-heading) ;before first headline
  6111. (org-back-to-heading invisible-ok)
  6112. (when (equal arg '(16)) (org-up-heading-safe))
  6113. (org-end-of-subtree)))
  6114. (unless (bolp) (insert "\n"))
  6115. (unless (and blank? (org-previous-line-empty-p))
  6116. (org-N-empty-lines-before-current (if blank? 1 0)))
  6117. (insert stars " ")
  6118. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6119. ;; is visible.
  6120. (unless invisible-ok
  6121. (pcase (get-char-property-and-overlay (point) 'invisible)
  6122. (`(outline . ,o)
  6123. (move-overlay o (overlay-start o) (line-end-position 0)))
  6124. (_ nil))))
  6125. ;; At a headline...
  6126. ((org-at-heading-p)
  6127. (cond ((bolp)
  6128. (when blank? (save-excursion (insert "\n")))
  6129. (save-excursion (insert stars " \n"))
  6130. (unless (and blank? (org-previous-line-empty-p))
  6131. (org-N-empty-lines-before-current (if blank? 1 0)))
  6132. (end-of-line))
  6133. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6134. (org-match-line org-complex-heading-regexp)
  6135. (org-pos-in-match-range (point) 4))
  6136. ;; Grab the text that should moved to the new headline.
  6137. ;; Preserve tags.
  6138. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6139. (if (looking-at "[ \t]*$") (replace-match "")
  6140. (org-align-tags))
  6141. (end-of-line)
  6142. (when blank? (insert "\n"))
  6143. (insert "\n" stars " ")
  6144. (when (org-string-nw-p split) (insert split))))
  6145. (t
  6146. (end-of-line)
  6147. (when blank? (insert "\n"))
  6148. (insert "\n" stars " "))))
  6149. ;; On regular text, turn line into a headline or split, if
  6150. ;; appropriate.
  6151. ((bolp)
  6152. (insert stars " ")
  6153. (unless (and blank? (org-previous-line-empty-p))
  6154. (org-N-empty-lines-before-current (if blank? 1 0))))
  6155. (t
  6156. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6157. (end-of-line))
  6158. (insert "\n" stars " ")
  6159. (unless (and blank? (org-previous-line-empty-p))
  6160. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6161. (run-hooks 'org-insert-heading-hook))
  6162. (defun org-N-empty-lines-before-current (n)
  6163. "Make the number of empty lines before current exactly N.
  6164. So this will delete or add empty lines."
  6165. (let ((column (current-column)))
  6166. (beginning-of-line)
  6167. (unless (bobp)
  6168. (let ((start (save-excursion
  6169. (skip-chars-backward " \r\t\n")
  6170. (line-end-position))))
  6171. (delete-region start (line-end-position 0))))
  6172. (insert (make-string n ?\n))
  6173. (move-to-column column)))
  6174. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6175. "Return the heading of the current entry, without the stars.
  6176. When NO-TAGS is non-nil, don't include tags.
  6177. When NO-TODO is non-nil, don't include TODO keywords.
  6178. When NO-PRIORITY is non-nil, don't include priority cookie.
  6179. When NO-COMMENT is non-nil, don't include COMMENT string.
  6180. Return nil before first heading."
  6181. (unless (org-before-first-heading-p)
  6182. (save-excursion
  6183. (org-back-to-heading t)
  6184. (let ((case-fold-search nil))
  6185. (looking-at org-complex-heading-regexp)
  6186. (let ((todo (and (not no-todo) (match-string 2)))
  6187. (priority (and (not no-priority) (match-string 3)))
  6188. (headline (pcase (match-string 4)
  6189. (`nil "")
  6190. ((and (guard no-comment) h)
  6191. (replace-regexp-in-string
  6192. (eval-when-compile
  6193. (format "\\`%s[ \t]+" org-comment-string))
  6194. "" h))
  6195. (h h)))
  6196. (tags (and (not no-tags) (match-string 5))))
  6197. (mapconcat #'identity
  6198. (delq nil (list todo priority headline tags))
  6199. " "))))))
  6200. (defun org-heading-components ()
  6201. "Return the components of the current heading.
  6202. This is a list with the following elements:
  6203. - the level as an integer
  6204. - the reduced level, different if `org-odd-levels-only' is set.
  6205. - the TODO keyword, or nil
  6206. - the priority character, like ?A, or nil if no priority is given
  6207. - the headline text itself, or the tags string if no headline text
  6208. - the tags string, or nil."
  6209. (save-excursion
  6210. (org-back-to-heading t)
  6211. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6212. (list (length (match-string 1))
  6213. (org-reduced-level (length (match-string 1)))
  6214. (match-string-no-properties 2)
  6215. (and (match-end 3) (aref (match-string 3) 2))
  6216. (match-string-no-properties 4)
  6217. (match-string-no-properties 5)))))
  6218. (defun org-get-entry ()
  6219. "Get the entry text, after heading, entire subtree."
  6220. (save-excursion
  6221. (org-back-to-heading t)
  6222. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6223. (defun org-edit-headline (&optional heading)
  6224. "Edit the current headline.
  6225. Set it to HEADING when provided."
  6226. (interactive)
  6227. (org-with-wide-buffer
  6228. (org-back-to-heading t)
  6229. (let ((case-fold-search nil))
  6230. (when (looking-at org-complex-heading-regexp)
  6231. (let* ((old (match-string-no-properties 4))
  6232. (new (save-match-data
  6233. (org-trim (or heading (read-string "Edit: " old))))))
  6234. (unless (equal old new)
  6235. (if old (replace-match new t t nil 4)
  6236. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6237. (insert " " new))
  6238. (org-align-tags)
  6239. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6240. (defun org-insert-heading-after-current ()
  6241. "Insert a new heading with same level as current, after current subtree."
  6242. (interactive)
  6243. (org-back-to-heading)
  6244. (org-insert-heading)
  6245. (org-move-subtree-down)
  6246. (end-of-line 1))
  6247. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6248. "Insert heading with `org-insert-heading-respect-content' set to t."
  6249. (interactive)
  6250. (org-insert-heading '(4) invisible-ok))
  6251. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6252. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6253. (interactive)
  6254. (org-insert-todo-heading force-state '(4)))
  6255. (defun org-insert-todo-heading (arg &optional force-heading)
  6256. "Insert a new heading with the same level and TODO state as current heading.
  6257. If the heading has no TODO state, or if the state is DONE, use
  6258. the first state (TODO by default). Also with one prefix arg,
  6259. force first state. With two prefix args, force inserting at the
  6260. end of the parent subtree.
  6261. When called at a plain list item, insert a new item with an
  6262. unchecked check box."
  6263. (interactive "P")
  6264. (when (or force-heading (not (org-insert-item 'checkbox)))
  6265. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6266. force-heading))
  6267. (save-excursion
  6268. (org-forward-heading-same-level -1)
  6269. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6270. (let* ((new-mark-x
  6271. (if (or (equal arg '(4))
  6272. (not (match-beginning 2))
  6273. (member (match-string 2) org-done-keywords))
  6274. (car org-todo-keywords-1)
  6275. (match-string 2)))
  6276. (new-mark
  6277. (or
  6278. (run-hook-with-args-until-success
  6279. 'org-todo-get-default-hook new-mark-x nil)
  6280. new-mark-x)))
  6281. (beginning-of-line 1)
  6282. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6283. (if org-treat-insert-todo-heading-as-state-change
  6284. (org-todo new-mark)
  6285. (insert new-mark " "))))
  6286. (when org-provide-todo-statistics
  6287. (org-update-parent-todo-statistics))))
  6288. (defun org-insert-subheading (arg)
  6289. "Insert a new subheading and demote it.
  6290. Works for outline headings and for plain lists alike."
  6291. (interactive "P")
  6292. (org-insert-heading arg)
  6293. (cond
  6294. ((org-at-heading-p) (org-do-demote))
  6295. ((org-at-item-p) (org-indent-item))))
  6296. (defun org-insert-todo-subheading (arg)
  6297. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6298. Works for outline headings and for plain lists alike."
  6299. (interactive "P")
  6300. (org-insert-todo-heading arg)
  6301. (cond
  6302. ((org-at-heading-p) (org-do-demote))
  6303. ((org-at-item-p) (org-indent-item))))
  6304. ;;; Promotion and Demotion
  6305. (defvar org-after-demote-entry-hook nil
  6306. "Hook run after an entry has been demoted.
  6307. The cursor will be at the beginning of the entry.
  6308. When a subtree is being demoted, the hook will be called for each node.")
  6309. (defvar org-after-promote-entry-hook nil
  6310. "Hook run after an entry has been promoted.
  6311. The cursor will be at the beginning of the entry.
  6312. When a subtree is being promoted, the hook will be called for each node.")
  6313. (defun org-promote-subtree ()
  6314. "Promote the entire subtree.
  6315. See also `org-promote'."
  6316. (interactive)
  6317. (save-excursion
  6318. (org-with-limited-levels (org-map-tree 'org-promote)))
  6319. (org-fix-position-after-promote))
  6320. (defun org-demote-subtree ()
  6321. "Demote the entire subtree.
  6322. See `org-demote' and `org-promote'."
  6323. (interactive)
  6324. (save-excursion
  6325. (org-with-limited-levels (org-map-tree 'org-demote)))
  6326. (org-fix-position-after-promote))
  6327. (defun org-do-promote ()
  6328. "Promote the current heading higher up the tree.
  6329. If the region is active in `transient-mark-mode', promote all
  6330. headings in the region."
  6331. (interactive)
  6332. (save-excursion
  6333. (if (org-region-active-p)
  6334. (org-map-region 'org-promote (region-beginning) (region-end))
  6335. (org-promote)))
  6336. (org-fix-position-after-promote))
  6337. (defun org-do-demote ()
  6338. "Demote the current heading lower down the tree.
  6339. If the region is active in `transient-mark-mode', demote all
  6340. headings in the region."
  6341. (interactive)
  6342. (save-excursion
  6343. (if (org-region-active-p)
  6344. (org-map-region 'org-demote (region-beginning) (region-end))
  6345. (org-demote)))
  6346. (org-fix-position-after-promote))
  6347. (defun org-fix-position-after-promote ()
  6348. "Fix cursor position and indentation after demoting/promoting."
  6349. (let ((pos (point)))
  6350. (when (save-excursion
  6351. (beginning-of-line)
  6352. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6353. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6354. (cond ((eobp) (insert " "))
  6355. ((eolp) (insert " "))
  6356. ((equal (char-after) ?\s) (forward-char 1))))))
  6357. (defun org-current-level ()
  6358. "Return the level of the current entry, or nil if before the first headline.
  6359. The level is the number of stars at the beginning of the
  6360. headline. Use `org-reduced-level' to remove the effect of
  6361. `org-odd-levels'. Unlike to `org-outline-level', this function
  6362. ignores inlinetasks."
  6363. (let ((level (org-with-limited-levels (org-outline-level))))
  6364. (and (> level 0) level)))
  6365. (defun org-get-previous-line-level ()
  6366. "Return the outline depth of the last headline before the current line.
  6367. Returns 0 for the first headline in the buffer, and nil if before the
  6368. first headline."
  6369. (and (org-current-level)
  6370. (or (and (/= (line-beginning-position) (point-min))
  6371. (save-excursion (beginning-of-line 0) (org-current-level)))
  6372. 0)))
  6373. (defun org-reduced-level (l)
  6374. "Compute the effective level of a heading.
  6375. This takes into account the setting of `org-odd-levels-only'."
  6376. (cond
  6377. ((zerop l) 0)
  6378. (org-odd-levels-only (1+ (floor (/ l 2))))
  6379. (t l)))
  6380. (defun org-level-increment ()
  6381. "Return the number of stars that will be added or removed at a
  6382. time to headlines when structure editing, based on the value of
  6383. `org-odd-levels-only'."
  6384. (if org-odd-levels-only 2 1))
  6385. (defun org-get-valid-level (level &optional change)
  6386. "Rectify a level change under the influence of `org-odd-levels-only'.
  6387. LEVEL is a current level, CHANGE is by how much the level should
  6388. be modified. Even if CHANGE is nil, LEVEL may be returned
  6389. modified because even level numbers will become the next higher
  6390. odd number. Returns values greater than 0."
  6391. (if org-odd-levels-only
  6392. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6393. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6394. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6395. (max 1 (+ level (or change 0)))))
  6396. (defun org-promote ()
  6397. "Promote the current heading higher up the tree."
  6398. (org-with-wide-buffer
  6399. (org-back-to-heading t)
  6400. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6401. after-change-functions))
  6402. (level (save-match-data (funcall outline-level)))
  6403. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6404. (diff (abs (- level (length up-head) -1))))
  6405. (cond
  6406. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6407. (replace-match "# " nil t))
  6408. ((= level 1)
  6409. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6410. (t (replace-match up-head nil t)))
  6411. (unless (= level 1)
  6412. (when org-auto-align-tags (org-align-tags))
  6413. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6414. (run-hooks 'org-after-promote-entry-hook))))
  6415. (defun org-demote ()
  6416. "Demote the current heading lower down the tree."
  6417. (org-with-wide-buffer
  6418. (org-back-to-heading t)
  6419. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6420. after-change-functions))
  6421. (level (save-match-data (funcall outline-level)))
  6422. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6423. (diff (abs (- level (length down-head) -1))))
  6424. (replace-match down-head nil t)
  6425. (when org-auto-align-tags (org-align-tags))
  6426. (when org-adapt-indentation (org-fixup-indentation diff))
  6427. (run-hooks 'org-after-demote-entry-hook))))
  6428. (defun org-cycle-level ()
  6429. "Cycle the level of an empty headline through possible states.
  6430. This goes first to child, then to parent, level, then up the hierarchy.
  6431. After top level, it switches back to sibling level."
  6432. (interactive)
  6433. (let ((org-adapt-indentation nil))
  6434. (when (org-point-at-end-of-empty-headline)
  6435. (setq this-command 'org-cycle-level) ; Only needed for caching
  6436. (let ((cur-level (org-current-level))
  6437. (prev-level (org-get-previous-line-level)))
  6438. (cond
  6439. ;; If first headline in file, promote to top-level.
  6440. ((= prev-level 0)
  6441. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6442. do (org-do-promote)))
  6443. ;; If same level as prev, demote one.
  6444. ((= prev-level cur-level)
  6445. (org-do-demote))
  6446. ;; If parent is top-level, promote to top level if not already.
  6447. ((= prev-level 1)
  6448. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6449. do (org-do-promote)))
  6450. ;; If top-level, return to prev-level.
  6451. ((= cur-level 1)
  6452. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6453. do (org-do-demote)))
  6454. ;; If less than prev-level, promote one.
  6455. ((< cur-level prev-level)
  6456. (org-do-promote))
  6457. ;; If deeper than prev-level, promote until higher than
  6458. ;; prev-level.
  6459. ((> cur-level prev-level)
  6460. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6461. do (org-do-promote))))
  6462. t))))
  6463. (defun org-map-tree (fun)
  6464. "Call FUN for every heading underneath the current one."
  6465. (org-back-to-heading t)
  6466. (let ((level (funcall outline-level)))
  6467. (save-excursion
  6468. (funcall fun)
  6469. (while (and (progn
  6470. (outline-next-heading)
  6471. (> (funcall outline-level) level))
  6472. (not (eobp)))
  6473. (funcall fun)))))
  6474. (defun org-map-region (fun beg end)
  6475. "Call FUN for every heading between BEG and END."
  6476. (let ((org-ignore-region t))
  6477. (save-excursion
  6478. (setq end (copy-marker end))
  6479. (goto-char beg)
  6480. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6481. (< (point) end))
  6482. (funcall fun))
  6483. (while (and (progn
  6484. (outline-next-heading)
  6485. (< (point) end))
  6486. (not (eobp)))
  6487. (funcall fun)))))
  6488. (defun org-fixup-indentation (diff)
  6489. "Change the indentation in the current entry by DIFF.
  6490. DIFF is an integer. Indentation is done according to the
  6491. following rules:
  6492. - Planning information and property drawers are always indented
  6493. according to the new level of the headline;
  6494. - Footnote definitions and their contents are ignored;
  6495. - Inlinetasks' boundaries are not shifted;
  6496. - Empty lines are ignored;
  6497. - Other lines' indentation are shifted by DIFF columns, unless
  6498. it would introduce a structural change in the document, in
  6499. which case no shifting is done at all.
  6500. Assume point is at a heading or an inlinetask beginning."
  6501. (org-with-wide-buffer
  6502. (narrow-to-region (line-beginning-position)
  6503. (save-excursion
  6504. (if (org-with-limited-levels (org-at-heading-p))
  6505. (org-with-limited-levels (outline-next-heading))
  6506. (org-inlinetask-goto-end))
  6507. (point)))
  6508. (forward-line)
  6509. ;; Indent properly planning info and property drawer.
  6510. (when (looking-at-p org-planning-line-re)
  6511. (org-indent-line)
  6512. (forward-line))
  6513. (when (looking-at org-property-drawer-re)
  6514. (goto-char (match-end 0))
  6515. (forward-line)
  6516. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  6517. (catch 'no-shift
  6518. (when (zerop diff) (throw 'no-shift nil))
  6519. ;; If DIFF is negative, first check if a shift is possible at all
  6520. ;; (e.g., it doesn't break structure). This can only happen if
  6521. ;; some contents are not properly indented.
  6522. (let ((case-fold-search t))
  6523. (when (< diff 0)
  6524. (let ((diff (- diff))
  6525. (forbidden-re (concat org-outline-regexp
  6526. "\\|"
  6527. (substring org-footnote-definition-re 1))))
  6528. (save-excursion
  6529. (while (not (eobp))
  6530. (cond
  6531. ((looking-at-p "[ \t]*$") (forward-line))
  6532. ((and (looking-at-p org-footnote-definition-re)
  6533. (let ((e (org-element-at-point)))
  6534. (and (eq (org-element-type e) 'footnote-definition)
  6535. (goto-char (org-element-property :end e))))))
  6536. ((looking-at-p org-outline-regexp) (forward-line))
  6537. ;; Give up if shifting would move before column 0 or
  6538. ;; if it would introduce a headline or a footnote
  6539. ;; definition.
  6540. (t
  6541. (skip-chars-forward " \t")
  6542. (let ((ind (current-column)))
  6543. (when (or (< ind diff)
  6544. (and (= ind diff) (looking-at-p forbidden-re)))
  6545. (throw 'no-shift nil)))
  6546. ;; Ignore contents of example blocks and source
  6547. ;; blocks if their indentation is meant to be
  6548. ;; preserved. Jump to block's closing line.
  6549. (beginning-of-line)
  6550. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6551. (let ((e (org-element-at-point)))
  6552. (and (memq (org-element-type e)
  6553. '(example-block src-block))
  6554. (or org-src-preserve-indentation
  6555. (org-element-property :preserve-indent e))
  6556. (goto-char (org-element-property :end e))
  6557. (progn (skip-chars-backward " \r\t\n")
  6558. (beginning-of-line)
  6559. t))))
  6560. (forward-line))))))))
  6561. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6562. ;; by DIFF. Also skip contents of source or example blocks
  6563. ;; when indentation is meant to be preserved.
  6564. (while (not (eobp))
  6565. (cond
  6566. ((and (looking-at-p org-footnote-definition-re)
  6567. (let ((e (org-element-at-point)))
  6568. (and (eq (org-element-type e) 'footnote-definition)
  6569. (goto-char (org-element-property :end e))))))
  6570. ((looking-at-p org-outline-regexp) (forward-line))
  6571. ((looking-at-p "[ \t]*$") (forward-line))
  6572. (t
  6573. (indent-line-to (+ (current-indentation) diff))
  6574. (beginning-of-line)
  6575. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6576. (let ((e (org-element-at-point)))
  6577. (and (memq (org-element-type e)
  6578. '(example-block src-block))
  6579. (or org-src-preserve-indentation
  6580. (org-element-property :preserve-indent e))
  6581. (goto-char (org-element-property :end e))
  6582. (progn (skip-chars-backward " \r\t\n")
  6583. (beginning-of-line)
  6584. t))))
  6585. (forward-line)))))))))
  6586. (defun org-convert-to-odd-levels ()
  6587. "Convert an Org file with all levels allowed to one with odd levels.
  6588. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6589. level 5 etc."
  6590. (interactive)
  6591. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6592. (let ((outline-level 'org-outline-level)
  6593. (org-odd-levels-only nil) n)
  6594. (save-excursion
  6595. (goto-char (point-min))
  6596. (while (re-search-forward "^\\*\\*+ " nil t)
  6597. (setq n (- (length (match-string 0)) 2))
  6598. (while (>= (setq n (1- n)) 0)
  6599. (org-demote))
  6600. (end-of-line 1))))))
  6601. (defun org-convert-to-oddeven-levels ()
  6602. "Convert an Org file with only odd levels to one with odd/even levels.
  6603. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6604. file contains a section with an even level, conversion would
  6605. destroy the structure of the file. An error is signaled in this
  6606. case."
  6607. (interactive)
  6608. (goto-char (point-min))
  6609. ;; First check if there are no even levels
  6610. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6611. (org-show-set-visibility 'canonical)
  6612. (error "Not all levels are odd in this file. Conversion not possible"))
  6613. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6614. (let ((outline-regexp org-outline-regexp)
  6615. (outline-level 'org-outline-level)
  6616. (org-odd-levels-only nil) n)
  6617. (save-excursion
  6618. (goto-char (point-min))
  6619. (while (re-search-forward "^\\*\\*+ " nil t)
  6620. (setq n (/ (1- (length (match-string 0))) 2))
  6621. (while (>= (setq n (1- n)) 0)
  6622. (org-promote))
  6623. (end-of-line 1))))))
  6624. (defun org-tr-level (n)
  6625. "Make N odd if required."
  6626. (if org-odd-levels-only (1+ (/ n 2)) n))
  6627. ;;; Vertical tree motion, cutting and pasting of subtrees
  6628. (defun org-move-subtree-up (&optional arg)
  6629. "Move the current subtree up past ARG headlines of the same level."
  6630. (interactive "p")
  6631. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6632. (defun org-move-subtree-down (&optional arg)
  6633. "Move the current subtree down past ARG headlines of the same level."
  6634. (interactive "p")
  6635. (setq arg (prefix-numeric-value arg))
  6636. (org-preserve-local-variables
  6637. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6638. 'org-get-last-sibling))
  6639. (ins-point (make-marker))
  6640. (cnt (abs arg))
  6641. (col (current-column))
  6642. beg end txt folded)
  6643. ;; Select the tree
  6644. (org-back-to-heading)
  6645. (setq beg (point))
  6646. (save-match-data
  6647. (save-excursion (outline-end-of-heading)
  6648. (setq folded (org-invisible-p)))
  6649. (progn (org-end-of-subtree nil t)
  6650. (unless (eobp) (backward-char))))
  6651. (outline-next-heading)
  6652. (setq end (point))
  6653. (goto-char beg)
  6654. ;; Find insertion point, with error handling
  6655. (while (> cnt 0)
  6656. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6657. (goto-char beg)
  6658. (user-error "Cannot move past superior level or buffer limit"))
  6659. (setq cnt (1- cnt)))
  6660. (when (> arg 0)
  6661. ;; Moving forward - still need to move over subtree
  6662. (org-end-of-subtree t t)
  6663. (save-excursion
  6664. (org-back-over-empty-lines)
  6665. (or (bolp) (newline))))
  6666. (move-marker ins-point (point))
  6667. (setq txt (buffer-substring beg end))
  6668. (org-save-markers-in-region beg end)
  6669. (delete-region beg end)
  6670. (org-remove-empty-overlays-at beg)
  6671. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6672. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6673. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6674. (let ((bbb (point)))
  6675. (insert-before-markers txt)
  6676. (org-reinstall-markers-in-region bbb)
  6677. (move-marker ins-point bbb))
  6678. (or (bolp) (insert "\n"))
  6679. (goto-char ins-point)
  6680. (org-skip-whitespace)
  6681. (move-marker ins-point nil)
  6682. (if folded
  6683. (org-flag-subtree t)
  6684. (org-show-entry)
  6685. (org-show-children))
  6686. (org-clean-visibility-after-subtree-move)
  6687. ;; move back to the initial column we were at
  6688. (move-to-column col))))
  6689. (defvar org-subtree-clip ""
  6690. "Clipboard for cut and paste of subtrees.
  6691. This is actually only a copy of the kill, because we use the normal kill
  6692. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6693. (defvar org-subtree-clip-folded nil
  6694. "Was the last copied subtree folded?
  6695. This is used to fold the tree back after pasting.")
  6696. (defun org-cut-subtree (&optional n)
  6697. "Cut the current subtree into the clipboard.
  6698. With prefix arg N, cut this many sequential subtrees.
  6699. This is a short-hand for marking the subtree and then cutting it."
  6700. (interactive "p")
  6701. (org-copy-subtree n 'cut))
  6702. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6703. "Copy the current subtree into the clipboard.
  6704. With prefix arg N, copy this many sequential subtrees.
  6705. This is a short-hand for marking the subtree and then copying it.
  6706. If CUT is non-nil, actually cut the subtree.
  6707. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6708. of some markers in the region, even if CUT is non-nil. This is
  6709. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6710. (interactive "p")
  6711. (org-preserve-local-variables
  6712. (let (beg end folded (beg0 (point)))
  6713. (if (called-interactively-p 'any)
  6714. (org-back-to-heading nil) ; take what looks like a subtree
  6715. (org-back-to-heading t)) ; take what is really there
  6716. (setq beg (point))
  6717. (skip-chars-forward " \t\r\n")
  6718. (save-match-data
  6719. (if nosubtrees
  6720. (outline-next-heading)
  6721. (save-excursion (outline-end-of-heading)
  6722. (setq folded (org-invisible-p)))
  6723. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6724. (org-end-of-subtree t t)))
  6725. ;; Include the end of an inlinetask
  6726. (when (and (featurep 'org-inlinetask)
  6727. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6728. "END[ \t]*$")))
  6729. (end-of-line))
  6730. (setq end (point))
  6731. (goto-char beg0)
  6732. (when (> end beg)
  6733. (setq org-subtree-clip-folded folded)
  6734. (when (or cut force-store-markers)
  6735. (org-save-markers-in-region beg end))
  6736. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6737. (setq org-subtree-clip (current-kill 0))
  6738. (message "%s: Subtree(s) with %d characters"
  6739. (if cut "Cut" "Copied")
  6740. (length org-subtree-clip))))))
  6741. (defun org-paste-subtree (&optional level tree for-yank remove)
  6742. "Paste the clipboard as a subtree, with modification of headline level.
  6743. The entire subtree is promoted or demoted in order to match a new headline
  6744. level.
  6745. If the cursor is at the beginning of a headline, the same level as
  6746. that headline is used to paste the tree.
  6747. If not, the new level is derived from the *visible* headings
  6748. before and after the insertion point, and taken to be the inferior headline
  6749. level of the two. So if the previous visible heading is level 3 and the
  6750. next is level 4 (or vice versa), level 4 will be used for insertion.
  6751. This makes sure that the subtree remains an independent subtree and does
  6752. not swallow low level entries.
  6753. You can also force a different level, either by using a numeric prefix
  6754. argument, or by inserting the heading marker by hand. For example, if the
  6755. cursor is after \"*****\", then the tree will be shifted to level 5.
  6756. If optional TREE is given, use this text instead of the kill ring.
  6757. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6758. move back over whitespace before inserting, and move point to the end of
  6759. the inserted text when done.
  6760. When REMOVE is non-nil, remove the subtree from the clipboard."
  6761. (interactive "P")
  6762. (setq tree (or tree (and kill-ring (current-kill 0))))
  6763. (unless (org-kill-is-subtree-p tree)
  6764. (user-error
  6765. (substitute-command-keys
  6766. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6767. (org-with-limited-levels
  6768. (let* ((visp (not (org-invisible-p)))
  6769. (txt tree)
  6770. (old-level (if (string-match org-outline-regexp-bol txt)
  6771. (- (match-end 0) (match-beginning 0) 1)
  6772. -1))
  6773. (force-level
  6774. (cond
  6775. (level (prefix-numeric-value level))
  6776. ;; When point is after the stars in an otherwise empty
  6777. ;; headline, use the number of stars as the forced level.
  6778. ((and (org-match-line "^\\*+[ \t]*$")
  6779. (not (eq ?* (char-after))))
  6780. (org-outline-level))
  6781. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6782. (previous-level
  6783. (save-excursion
  6784. (org-previous-visible-heading 1)
  6785. (if (org-at-heading-p) (org-outline-level) 1)))
  6786. (next-level
  6787. (save-excursion
  6788. (if (org-at-heading-p) (org-outline-level)
  6789. (org-next-visible-heading 1)
  6790. (if (org-at-heading-p) (org-outline-level) 1))))
  6791. (new-level (or force-level (max previous-level next-level)))
  6792. (shift (if (or (= old-level -1)
  6793. (= new-level -1)
  6794. (= old-level new-level))
  6795. 0
  6796. (- new-level old-level)))
  6797. (delta (if (> shift 0) -1 1))
  6798. (func (if (> shift 0) #'org-demote #'org-promote))
  6799. (org-odd-levels-only nil)
  6800. beg end newend)
  6801. ;; Remove the forced level indicator.
  6802. (when (and force-level (not level))
  6803. (delete-region (line-beginning-position) (point)))
  6804. ;; Paste before the next visible heading or at end of buffer,
  6805. ;; unless point is at the beginning of a headline.
  6806. (unless (and (bolp) (org-at-heading-p))
  6807. (org-next-visible-heading 1)
  6808. (unless (bolp) (insert "\n")))
  6809. (setq beg (point))
  6810. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6811. (insert-before-markers txt)
  6812. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6813. (setq newend (point))
  6814. (org-reinstall-markers-in-region beg)
  6815. (setq end (point))
  6816. (goto-char beg)
  6817. (skip-chars-forward " \t\n\r")
  6818. (setq beg (point))
  6819. (when (and (org-invisible-p) visp)
  6820. (save-excursion (outline-show-heading)))
  6821. ;; Shift if necessary.
  6822. (unless (= shift 0)
  6823. (save-restriction
  6824. (narrow-to-region beg end)
  6825. (while (not (= shift 0))
  6826. (org-map-region func (point-min) (point-max))
  6827. (setq shift (+ delta shift)))
  6828. (goto-char (point-min))
  6829. (setq newend (point-max))))
  6830. (when (or for-yank (called-interactively-p 'interactive))
  6831. (message "Clipboard pasted as level %d subtree" new-level))
  6832. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6833. kill-ring
  6834. (equal org-subtree-clip (current-kill 0))
  6835. org-subtree-clip-folded)
  6836. ;; The tree was folded before it was killed/copied
  6837. (org-flag-subtree t))
  6838. (when for-yank (goto-char newend))
  6839. (when remove (pop kill-ring)))))
  6840. (defun org-kill-is-subtree-p (&optional txt)
  6841. "Check if the current kill is an outline subtree, or a set of trees.
  6842. Returns nil if kill does not start with a headline, or if the first
  6843. headline level is not the largest headline level in the tree.
  6844. So this will actually accept several entries of equal levels as well,
  6845. which is OK for `org-paste-subtree'.
  6846. If optional TXT is given, check this string instead of the current kill."
  6847. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6848. (re (org-get-limited-outline-regexp))
  6849. (^re (concat "^" re))
  6850. (start-level (and kill
  6851. (string-match
  6852. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6853. kill)
  6854. (- (match-end 2) (match-beginning 2) 1)))
  6855. (start (1+ (or (match-beginning 2) -1))))
  6856. (if (not start-level)
  6857. (progn
  6858. nil) ;; does not even start with a heading
  6859. (catch 'exit
  6860. (while (setq start (string-match ^re kill (1+ start)))
  6861. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6862. (throw 'exit nil)))
  6863. t))))
  6864. (defvar org-markers-to-move nil
  6865. "Markers that should be moved with a cut-and-paste operation.
  6866. Those markers are stored together with their positions relative to
  6867. the start of the region.")
  6868. (defun org-save-markers-in-region (beg end)
  6869. "Check markers in region.
  6870. If these markers are between BEG and END, record their position relative
  6871. to BEG, so that after moving the block of text, we can put the markers back
  6872. into place.
  6873. This function gets called just before an entry or tree gets cut from the
  6874. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6875. called immediately, to move the markers with the entries."
  6876. (setq org-markers-to-move nil)
  6877. (when (featurep 'org-clock)
  6878. (org-clock-save-markers-for-cut-and-paste beg end))
  6879. (when (featurep 'org-agenda)
  6880. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6881. (defun org-check-and-save-marker (marker beg end)
  6882. "Check if MARKER is between BEG and END.
  6883. If yes, remember the marker and the distance to BEG."
  6884. (when (and (marker-buffer marker)
  6885. (equal (marker-buffer marker) (current-buffer))
  6886. (>= marker beg) (< marker end))
  6887. (push (cons marker (- marker beg)) org-markers-to-move)))
  6888. (defun org-reinstall-markers-in-region (beg)
  6889. "Move all remembered markers to their position relative to BEG."
  6890. (dolist (x org-markers-to-move)
  6891. (move-marker (car x) (+ beg (cdr x))))
  6892. (setq org-markers-to-move nil))
  6893. (defun org-narrow-to-subtree ()
  6894. "Narrow buffer to the current subtree."
  6895. (interactive)
  6896. (save-excursion
  6897. (save-match-data
  6898. (org-with-limited-levels
  6899. (narrow-to-region
  6900. (progn (org-back-to-heading t) (point))
  6901. (progn (org-end-of-subtree t t)
  6902. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6903. (point)))))))
  6904. (defun org-toggle-narrow-to-subtree ()
  6905. "Narrow to the subtree at point or widen a narrowed buffer."
  6906. (interactive)
  6907. (if (buffer-narrowed-p)
  6908. (widen)
  6909. (org-narrow-to-subtree)))
  6910. (defun org-narrow-to-block ()
  6911. "Narrow buffer to the current block."
  6912. (interactive)
  6913. (let* ((case-fold-search t)
  6914. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6915. "^[ \t]*#\\+end_.*")))
  6916. (if blockp
  6917. (narrow-to-region (car blockp) (cdr blockp))
  6918. (user-error "Not in a block"))))
  6919. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6920. "Clone the task (subtree) at point N times.
  6921. The clones will be inserted as siblings.
  6922. In interactive use, the user will be prompted for the number of
  6923. clones to be produced. If the entry has a timestamp, the user
  6924. will also be prompted for a time shift, which may be a repeater
  6925. as used in time stamps, for example `+3d'. To disable this,
  6926. you can call the function with a universal prefix argument.
  6927. When a valid repeater is given and the entry contains any time
  6928. stamps, the clones will become a sequence in time, with time
  6929. stamps in the subtree shifted for each clone produced. If SHIFT
  6930. is nil or the empty string, time stamps will be left alone. The
  6931. ID property of the original subtree is removed.
  6932. In each clone, all the CLOCK entries will be removed. This
  6933. prevents Org from considering that the clocked times overlap.
  6934. If the original subtree did contain time stamps with a repeater,
  6935. the following will happen:
  6936. - the repeater will be removed in each clone
  6937. - an additional clone will be produced, with the current, unshifted
  6938. date(s) in the entry.
  6939. - the original entry will be placed *after* all the clones, with
  6940. repeater intact.
  6941. - the start days in the repeater in the original entry will be shifted
  6942. to past the last clone.
  6943. In this way you can spell out a number of instances of a repeating task,
  6944. and still retain the repeater to cover future instances of the task.
  6945. As described above, N+1 clones are produced when the original
  6946. subtree has a repeater. Setting N to 0, then, can be used to
  6947. remove the repeater from a subtree and create a shifted clone
  6948. with the original repeater."
  6949. (interactive "nNumber of clones to produce: ")
  6950. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  6951. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  6952. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  6953. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  6954. (shift
  6955. (or shift
  6956. (if (and (not (equal current-prefix-arg '(4)))
  6957. (save-excursion
  6958. (goto-char beg)
  6959. (re-search-forward org-ts-regexp-both end-of-tree t)))
  6960. (read-from-minibuffer
  6961. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  6962. ""))) ;No time shift
  6963. (doshift
  6964. (and (org-string-nw-p shift)
  6965. (or (string-match "\\`[ \t]*\\([\\+\\-]?[0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  6966. shift)
  6967. (user-error "Invalid shift specification %s" shift)))))
  6968. (goto-char end-of-tree)
  6969. (unless (bolp) (insert "\n"))
  6970. (let* ((end (point))
  6971. (template (buffer-substring beg end))
  6972. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  6973. (shift-what (pcase (and doshift (match-string 2 shift))
  6974. (`nil nil)
  6975. ("d" 'day)
  6976. ("w" (setq shift-n (* 7 shift-n)) 'day)
  6977. ("m" 'month)
  6978. ("y" 'year)
  6979. (_ (error "Unsupported time unit"))))
  6980. (nmin 1)
  6981. (nmax n)
  6982. (n-no-remove -1)
  6983. (idprop (org-entry-get nil "ID")))
  6984. (when (and doshift
  6985. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  6986. template))
  6987. (delete-region beg end)
  6988. (setq end beg)
  6989. (setq nmin 0)
  6990. (setq nmax (1+ nmax))
  6991. (setq n-no-remove nmax))
  6992. (goto-char end)
  6993. (cl-loop for n from nmin to nmax do
  6994. (insert
  6995. ;; Prepare clone.
  6996. (with-temp-buffer
  6997. (insert template)
  6998. (org-mode)
  6999. (goto-char (point-min))
  7000. (org-show-subtree)
  7001. (and idprop (if org-clone-delete-id
  7002. (org-entry-delete nil "ID")
  7003. (org-id-get-create t)))
  7004. (unless (= n 0)
  7005. (while (re-search-forward org-clock-line-re nil t)
  7006. (delete-region (line-beginning-position)
  7007. (line-beginning-position 2)))
  7008. (goto-char (point-min))
  7009. (while (re-search-forward org-drawer-regexp nil t)
  7010. (org-remove-empty-drawer-at (point))))
  7011. (goto-char (point-min))
  7012. (when doshift
  7013. (while (re-search-forward org-ts-regexp-both nil t)
  7014. (org-timestamp-change (* n shift-n) shift-what))
  7015. (unless (= n n-no-remove)
  7016. (goto-char (point-min))
  7017. (while (re-search-forward org-ts-regexp nil t)
  7018. (save-excursion
  7019. (goto-char (match-beginning 0))
  7020. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7021. (delete-region (match-beginning 1) (match-end 1)))))))
  7022. (buffer-string)))))
  7023. (goto-char beg)))
  7024. ;;; Outline Sorting
  7025. (defun org-sort (&optional with-case)
  7026. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7027. Optional argument WITH-CASE means sort case-sensitively."
  7028. (interactive "P")
  7029. (org-call-with-arg
  7030. (cond ((org-at-table-p) #'org-table-sort-lines)
  7031. ((org-at-item-p) #'org-sort-list)
  7032. (t #'org-sort-entries))
  7033. with-case))
  7034. (defun org-sort-remove-invisible (s)
  7035. "Remove invisible part of links and emphasis markers from string S."
  7036. (remove-text-properties 0 (length s) org-rm-props s)
  7037. (replace-regexp-in-string
  7038. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7039. (replace-regexp-in-string
  7040. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7041. (org-link-display-format s)
  7042. t t) t t))
  7043. (defvar org-priority-regexp) ; defined later in the file
  7044. (defvar org-after-sorting-entries-or-items-hook nil
  7045. "Hook that is run after a bunch of entries or items have been sorted.
  7046. When children are sorted, the cursor is in the parent line when this
  7047. hook gets called. When a region or a plain list is sorted, the cursor
  7048. will be in the first entry of the sorted region/list.")
  7049. (defun org-sort-entries
  7050. (&optional with-case sorting-type getkey-func compare-func property
  7051. interactive?)
  7052. "Sort entries on a certain level of an outline tree.
  7053. If there is an active region, the entries in the region are sorted.
  7054. Else, if the cursor is before the first entry, sort the top-level items.
  7055. Else, the children of the entry at point are sorted.
  7056. Sorting can be alphabetically, numerically, by date/time as given by
  7057. a time stamp, by a property, by priority order, or by a custom function.
  7058. The command prompts for the sorting type unless it has been given to the
  7059. function through the SORTING-TYPE argument, which needs to be a character,
  7060. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7061. the precise meaning of each character:
  7062. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7063. c By creation time, which is assumed to be the first inactive time stamp
  7064. at the beginning of a line.
  7065. d By deadline date/time.
  7066. k By clocking time.
  7067. n Numerically, by converting the beginning of the entry/item to a number.
  7068. o By order of TODO keywords.
  7069. p By priority according to the cookie.
  7070. r By the value of a property.
  7071. s By scheduled date/time.
  7072. t By date/time, either the first active time stamp in the entry, or, if
  7073. none exist, by the first inactive one.
  7074. Capital letters will reverse the sort order.
  7075. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7076. called with point at the beginning of the record. It must return a
  7077. value that is compatible with COMPARE-FUNC, the function used to
  7078. compare entries.
  7079. Comparing entries ignores case by default. However, with an optional argument
  7080. WITH-CASE, the sorting considers case as well.
  7081. Sorting is done against the visible part of the headlines, it ignores hidden
  7082. links.
  7083. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7084. A non-nil value for INTERACTIVE? is used to signal that this
  7085. function is being called interactively."
  7086. (interactive (list current-prefix-arg nil nil nil nil t))
  7087. (let ((case-func (if with-case 'identity 'downcase))
  7088. start beg end stars re re2
  7089. txt what tmp)
  7090. ;; Find beginning and end of region to sort
  7091. (cond
  7092. ((org-region-active-p)
  7093. ;; we will sort the region
  7094. (setq end (region-end)
  7095. what "region")
  7096. (goto-char (region-beginning))
  7097. (unless (org-at-heading-p) (outline-next-heading))
  7098. (setq start (point)))
  7099. ((or (org-at-heading-p)
  7100. (ignore-errors (progn (org-back-to-heading) t)))
  7101. ;; we will sort the children of the current headline
  7102. (org-back-to-heading)
  7103. (setq start (point)
  7104. end (progn (org-end-of-subtree t t)
  7105. (or (bolp) (insert "\n"))
  7106. (when (>= (org-back-over-empty-lines) 1)
  7107. (forward-line 1))
  7108. (point))
  7109. what "children")
  7110. (goto-char start)
  7111. (outline-show-subtree)
  7112. (outline-next-heading))
  7113. (t
  7114. ;; we will sort the top-level entries in this file
  7115. (goto-char (point-min))
  7116. (or (org-at-heading-p) (outline-next-heading))
  7117. (setq start (point))
  7118. (goto-char (point-max))
  7119. (beginning-of-line 1)
  7120. (when (looking-at ".*?\\S-")
  7121. ;; File ends in a non-white line
  7122. (end-of-line 1)
  7123. (insert "\n"))
  7124. (setq end (point-max))
  7125. (setq what "top-level")
  7126. (goto-char start)
  7127. (org-show-all '(headings blocks))))
  7128. (setq beg (point))
  7129. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7130. (looking-at "\\(\\*+\\)")
  7131. (setq stars (match-string 1)
  7132. re (concat "^" (regexp-quote stars) " +")
  7133. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7134. txt (buffer-substring beg end))
  7135. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7136. (when (and (not (equal stars "*")) (string-match re2 txt))
  7137. (user-error "Region to sort contains a level above the first entry"))
  7138. (unless sorting-type
  7139. (message
  7140. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7141. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7142. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7143. what)
  7144. (setq sorting-type (read-char-exclusive)))
  7145. (unless getkey-func
  7146. (and (= (downcase sorting-type) ?f)
  7147. (setq getkey-func
  7148. (or (and interactive?
  7149. (org-read-function
  7150. "Function for extracting keys: "))
  7151. (error "Missing key extractor")))))
  7152. (and (= (downcase sorting-type) ?r)
  7153. (not property)
  7154. (setq property
  7155. (completing-read "Property: "
  7156. (mapcar #'list (org-buffer-property-keys t))
  7157. nil t)))
  7158. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7159. (message "Sorting entries...")
  7160. (save-restriction
  7161. (narrow-to-region start end)
  7162. (let ((restore-clock?
  7163. ;; The clock marker is lost when using `sort-subr'; mark
  7164. ;; the clock with temporary `:org-clock-marker-backup'
  7165. ;; text property.
  7166. (when (and (eq (org-clock-is-active) (current-buffer))
  7167. (<= start (marker-position org-clock-marker))
  7168. (>= end (marker-position org-clock-marker)))
  7169. (with-silent-modifications
  7170. (put-text-property (1- org-clock-marker) org-clock-marker
  7171. :org-clock-marker-backup t))
  7172. t))
  7173. (dcst (downcase sorting-type))
  7174. (case-fold-search nil)
  7175. (now (current-time)))
  7176. (org-preserve-local-variables
  7177. (sort-subr
  7178. (/= dcst sorting-type)
  7179. ;; This function moves to the beginning character of the
  7180. ;; "record" to be sorted.
  7181. (lambda nil
  7182. (if (re-search-forward re nil t)
  7183. (goto-char (match-beginning 0))
  7184. (goto-char (point-max))))
  7185. ;; This function moves to the last character of the "record" being
  7186. ;; sorted.
  7187. (lambda nil
  7188. (save-match-data
  7189. (condition-case nil
  7190. (outline-forward-same-level 1)
  7191. (error
  7192. (goto-char (point-max))))))
  7193. ;; This function returns the value that gets sorted against.
  7194. (lambda ()
  7195. (cond
  7196. ((= dcst ?n)
  7197. (string-to-number
  7198. (org-sort-remove-invisible (org-get-heading t t t t))))
  7199. ((= dcst ?a)
  7200. (funcall case-func
  7201. (org-sort-remove-invisible (org-get-heading t t t t))))
  7202. ((= dcst ?k)
  7203. (or (get-text-property (point) :org-clock-minutes) 0))
  7204. ((= dcst ?t)
  7205. (let ((end (save-excursion (outline-next-heading) (point))))
  7206. (if (or (re-search-forward org-ts-regexp end t)
  7207. (re-search-forward org-ts-regexp-both end t))
  7208. (org-time-string-to-seconds (match-string 0))
  7209. (float-time now))))
  7210. ((= dcst ?c)
  7211. (let ((end (save-excursion (outline-next-heading) (point))))
  7212. (if (re-search-forward
  7213. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7214. end t)
  7215. (org-time-string-to-seconds (match-string 0))
  7216. (float-time now))))
  7217. ((= dcst ?s)
  7218. (let ((end (save-excursion (outline-next-heading) (point))))
  7219. (if (re-search-forward org-scheduled-time-regexp end t)
  7220. (org-time-string-to-seconds (match-string 1))
  7221. (float-time now))))
  7222. ((= dcst ?d)
  7223. (let ((end (save-excursion (outline-next-heading) (point))))
  7224. (if (re-search-forward org-deadline-time-regexp end t)
  7225. (org-time-string-to-seconds (match-string 1))
  7226. (float-time now))))
  7227. ((= dcst ?p)
  7228. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7229. (string-to-char (match-string 2))
  7230. org-default-priority))
  7231. ((= dcst ?r)
  7232. (or (org-entry-get nil property) ""))
  7233. ((= dcst ?o)
  7234. (when (looking-at org-complex-heading-regexp)
  7235. (let* ((m (match-string 2))
  7236. (s (if (member m org-done-keywords) '- '+)))
  7237. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7238. ((= dcst ?f)
  7239. (if getkey-func
  7240. (progn
  7241. (setq tmp (funcall getkey-func))
  7242. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7243. tmp)
  7244. (error "Invalid key function `%s'" getkey-func)))
  7245. (t (error "Invalid sorting type `%c'" sorting-type))))
  7246. nil
  7247. (cond
  7248. ((= dcst ?a) 'org-string-collate-lessp)
  7249. ((= dcst ?f)
  7250. (or compare-func
  7251. (and interactive?
  7252. (org-read-function
  7253. (concat "Function for comparing keys "
  7254. "(empty for default `sort-subr' predicate): ")
  7255. 'allow-empty))))
  7256. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7257. (org-cycle-hide-drawers 'all)
  7258. (when restore-clock?
  7259. (move-marker org-clock-marker
  7260. (1+ (next-single-property-change
  7261. start :org-clock-marker-backup)))
  7262. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7263. '(:org-clock-marker-backup t)))))
  7264. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7265. (message "Sorting entries...done")))
  7266. (defun org-contextualize-keys (alist contexts)
  7267. "Return valid elements in ALIST depending on CONTEXTS.
  7268. `org-agenda-custom-commands' or `org-capture-templates' are the
  7269. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7270. or `org-capture-templates-contexts' are the associated contexts
  7271. definitions."
  7272. (let ((contexts
  7273. ;; normalize contexts
  7274. (mapcar
  7275. (lambda(c) (cond ((listp (cadr c))
  7276. (list (car c) (car c) (nth 1 c)))
  7277. ((string= "" (cadr c))
  7278. (list (car c) (car c) (nth 2 c)))
  7279. (t c)))
  7280. contexts))
  7281. (a alist) r s)
  7282. ;; loop over all commands or templates
  7283. (dolist (c a)
  7284. (let (vrules repl)
  7285. (cond
  7286. ((not (assoc (car c) contexts))
  7287. (push c r))
  7288. ((and (assoc (car c) contexts)
  7289. (setq vrules (org-contextualize-validate-key
  7290. (car c) contexts)))
  7291. (mapc (lambda (vr)
  7292. (unless (equal (car vr) (cadr vr))
  7293. (setq repl vr)))
  7294. vrules)
  7295. (if (not repl) (push c r)
  7296. (push (cadr repl) s)
  7297. (push
  7298. (cons (car c)
  7299. (cdr (or (assoc (cadr repl) alist)
  7300. (error "Undefined key `%s' as contextual replacement for `%s'"
  7301. (cadr repl) (car c)))))
  7302. r))))))
  7303. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7304. (delq
  7305. nil
  7306. (delete-dups
  7307. (mapcar (lambda (x)
  7308. (let ((tpl (car x)))
  7309. (unless (delq
  7310. nil
  7311. (mapcar (lambda (y)
  7312. (equal y tpl))
  7313. s))
  7314. x)))
  7315. (reverse r))))))
  7316. (defun org-contextualize-validate-key (key contexts)
  7317. "Check CONTEXTS for agenda or capture KEY."
  7318. (let (res)
  7319. (dolist (r contexts)
  7320. (dolist (rr (car (last r)))
  7321. (when
  7322. (and (equal key (car r))
  7323. (if (functionp rr) (funcall rr)
  7324. (or (and (eq (car rr) 'in-file)
  7325. (buffer-file-name)
  7326. (string-match (cdr rr) (buffer-file-name)))
  7327. (and (eq (car rr) 'in-mode)
  7328. (string-match (cdr rr) (symbol-name major-mode)))
  7329. (and (eq (car rr) 'in-buffer)
  7330. (string-match (cdr rr) (buffer-name)))
  7331. (when (and (eq (car rr) 'not-in-file)
  7332. (buffer-file-name))
  7333. (not (string-match (cdr rr) (buffer-file-name))))
  7334. (when (eq (car rr) 'not-in-mode)
  7335. (not (string-match (cdr rr) (symbol-name major-mode))))
  7336. (when (eq (car rr) 'not-in-buffer)
  7337. (not (string-match (cdr rr) (buffer-name)))))))
  7338. (push r res))))
  7339. (delete-dups (delq nil res))))
  7340. ;; Defined to provide a value for defcustom, since there is no
  7341. ;; string-collate-greaterp in Emacs.
  7342. (defun org-string-collate-greaterp (s1 s2)
  7343. "Return non-nil if S1 is greater than S2 in collation order."
  7344. (not (org-string-collate-lessp s1 s2)))
  7345. ;;;###autoload
  7346. (defun org-run-like-in-org-mode (cmd)
  7347. "Run a command, pretending that the current buffer is in Org mode.
  7348. This will temporarily bind local variables that are typically bound in
  7349. Org mode to the values they have in Org mode, and then interactively
  7350. call CMD."
  7351. (org-load-modules-maybe)
  7352. (let (binds)
  7353. (dolist (var (org-get-local-variables))
  7354. (when (or (not (boundp (car var)))
  7355. (eq (symbol-value (car var))
  7356. (default-value (car var))))
  7357. (push (list (car var) `(quote ,(cadr var))) binds)))
  7358. (eval `(let ,binds
  7359. (call-interactively (quote ,cmd))))))
  7360. (defun org-get-category (&optional pos force-refresh)
  7361. "Get the category applying to position POS."
  7362. (save-match-data
  7363. (when force-refresh (org-refresh-category-properties))
  7364. (let ((pos (or pos (point))))
  7365. (or (get-text-property pos 'org-category)
  7366. (progn (org-refresh-category-properties)
  7367. (get-text-property pos 'org-category))))))
  7368. ;;; Refresh properties
  7369. (defun org-refresh-properties (dprop tprop)
  7370. "Refresh buffer text properties.
  7371. DPROP is the drawer property and TPROP is either the
  7372. corresponding text property to set, or an alist with each element
  7373. being a text property (as a symbol) and a function to apply to
  7374. the value of the drawer property."
  7375. (let* ((case-fold-search t)
  7376. (inhibit-read-only t)
  7377. (inherit? (org-property-inherit-p dprop))
  7378. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7379. (global (and inherit? (org--property-global-value dprop nil))))
  7380. (with-silent-modifications
  7381. (org-with-point-at 1
  7382. ;; Set global values (e.g., values defined through
  7383. ;; "#+PROPERTY:" keywords) to the whole buffer.
  7384. (when global (put-text-property (point-min) (point-max) tprop global))
  7385. ;; Set local values.
  7386. (while (re-search-forward property-re nil t)
  7387. (when (org-at-property-p)
  7388. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7389. (outline-next-heading))))))
  7390. (defun org-refresh-property (tprop p &optional inherit)
  7391. "Refresh the buffer text property TPROP from the drawer property P.
  7392. The refresh happens only for the current headline, or the whole
  7393. sub-tree if optional argument INHERIT is non-nil."
  7394. (unless (org-before-first-heading-p)
  7395. (save-excursion
  7396. (org-back-to-heading t)
  7397. (let ((start (point))
  7398. (end (save-excursion
  7399. (if inherit (org-end-of-subtree t t)
  7400. (or (outline-next-heading) (point-max))))))
  7401. (if (symbolp tprop)
  7402. ;; TPROP is a text property symbol.
  7403. (put-text-property start end tprop p)
  7404. ;; TPROP is an alist with (property . function) elements.
  7405. (pcase-dolist (`(,prop . ,f) tprop)
  7406. (put-text-property start end prop (funcall f p))))))))
  7407. (defun org-refresh-category-properties ()
  7408. "Refresh category text properties in the buffer."
  7409. (let ((case-fold-search t)
  7410. (inhibit-read-only t)
  7411. (default-category
  7412. (cond ((null org-category)
  7413. (if buffer-file-name
  7414. (file-name-sans-extension
  7415. (file-name-nondirectory buffer-file-name))
  7416. "???"))
  7417. ((symbolp org-category) (symbol-name org-category))
  7418. (t org-category))))
  7419. (with-silent-modifications
  7420. (org-with-wide-buffer
  7421. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  7422. ;; This is the default category for the buffer. If none is
  7423. ;; found, fall-back to `org-category' or buffer file name.
  7424. (put-text-property
  7425. (point-min) (point-max)
  7426. 'org-category
  7427. (catch 'buffer-category
  7428. (goto-char (point-max))
  7429. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7430. (let ((element (org-element-at-point)))
  7431. (when (eq (org-element-type element) 'keyword)
  7432. (throw 'buffer-category
  7433. (org-element-property :value element)))))
  7434. default-category))
  7435. ;; Set sub-tree specific categories.
  7436. (goto-char (point-min))
  7437. (let ((regexp (org-re-property "CATEGORY")))
  7438. (while (re-search-forward regexp nil t)
  7439. (let ((value (match-string-no-properties 3)))
  7440. (when (org-at-property-p)
  7441. (put-text-property
  7442. (save-excursion (org-back-to-heading t) (point))
  7443. (save-excursion (org-end-of-subtree t t) (point))
  7444. 'org-category
  7445. value)))))))))
  7446. (defun org-refresh-stats-properties ()
  7447. "Refresh stats text properties in the buffer."
  7448. (with-silent-modifications
  7449. (org-with-point-at 1
  7450. (let ((regexp (concat org-outline-regexp-bol
  7451. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7452. (while (re-search-forward regexp nil t)
  7453. (let* ((numerator (string-to-number (match-string 1)))
  7454. (denominator (and (match-end 2)
  7455. (string-to-number (match-string 2))))
  7456. (stats (cond ((not denominator) numerator) ;percent
  7457. ((= denominator 0) 0)
  7458. (t (/ (* numerator 100) denominator)))))
  7459. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7460. 'org-stats stats)))))))
  7461. (defun org-refresh-effort-properties ()
  7462. "Refresh effort properties"
  7463. (org-refresh-properties
  7464. org-effort-property
  7465. '((effort . identity)
  7466. (effort-minutes . org-duration-to-minutes))))
  7467. (defun org-find-file-at-mouse (ev)
  7468. "Open file link or URL at mouse."
  7469. (interactive "e")
  7470. (mouse-set-point ev)
  7471. (org-open-at-point 'in-emacs))
  7472. (defun org-open-at-mouse (ev)
  7473. "Open file link or URL at mouse.
  7474. See the docstring of `org-open-file' for details."
  7475. (interactive "e")
  7476. (mouse-set-point ev)
  7477. (when (eq major-mode 'org-agenda-mode)
  7478. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7479. (org-open-at-point))
  7480. (defvar org-window-config-before-follow-link nil
  7481. "The window configuration before following a link.
  7482. This is saved in case the need arises to restore it.")
  7483. (defun org--file-default-apps ()
  7484. "Return the default applications for this operating system."
  7485. (pcase system-type
  7486. (`darwin org-file-apps-macos)
  7487. (`windows-nt org-file-apps-windowsnt)
  7488. (_ org-file-apps-gnu)))
  7489. (defun org--file-apps-entry-dlink-p (entry)
  7490. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7491. It assumes that is the case when the entry uses a regular
  7492. expression which has at least one grouping construct and the
  7493. action is either a Lisp form or a command string containing
  7494. \"%1\", i.e., using at least one subexpression match as
  7495. a parameter."
  7496. (pcase entry
  7497. (`(,selector . ,action)
  7498. (and (stringp selector)
  7499. (> (regexp-opt-depth selector) 0)
  7500. (or (and (stringp action)
  7501. (string-match "%[0-9]" action))
  7502. (consp action))))
  7503. (_ nil)))
  7504. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7505. "Convert extensions to regular expressions in the cars of LIST.
  7506. Also, weed out any non-string entries, because the return value
  7507. is used only for regexp matching.
  7508. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7509. point to the symbol `emacs', indicating that the file should be
  7510. opened in Emacs."
  7511. (append
  7512. (delq nil
  7513. (mapcar (lambda (x)
  7514. (unless (not (stringp (car x)))
  7515. (if (string-match "\\W" (car x))
  7516. x
  7517. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7518. list))
  7519. (when add-auto-mode
  7520. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7521. ;;;###autoload
  7522. (defun org-open-file (path &optional in-emacs line search)
  7523. "Open the file at PATH.
  7524. First, this expands any special file name abbreviations. Then the
  7525. configuration variable `org-file-apps' is checked if it contains an
  7526. entry for this file type, and if yes, the corresponding command is launched.
  7527. If no application is found, Emacs simply visits the file.
  7528. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7529. With a double \\[universal-argument] \\[universal-argument] \
  7530. prefix arg, Org tries to avoid opening in Emacs
  7531. and to use an external application to visit the file.
  7532. Optional LINE specifies a line to go to, optional SEARCH a string
  7533. to search for. If LINE or SEARCH is given, the file will be
  7534. opened in Emacs, unless an entry from `org-file-apps' that makes
  7535. use of groups in a regexp matches.
  7536. If you want to change the way frames are used when following a
  7537. link, please customize `org-link-frame-setup'.
  7538. If the file does not exist, throw an error."
  7539. (let* ((file (if (equal path "") buffer-file-name
  7540. (substitute-in-file-name (expand-file-name path))))
  7541. (file-apps (append org-file-apps (org--file-default-apps)))
  7542. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7543. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7544. file-apps))
  7545. (remp (and (assq 'remote apps) (file-remote-p file)))
  7546. (dirp (unless remp (file-directory-p file)))
  7547. (file (if (and dirp org-open-directory-means-index-dot-org)
  7548. (concat (file-name-as-directory file) "index.org")
  7549. file))
  7550. (a-m-a-p (assq 'auto-mode apps))
  7551. (dfile (downcase file))
  7552. ;; Reconstruct the original link from the PATH, LINE and
  7553. ;; SEARCH args.
  7554. (link (cond (line (concat file "::" (number-to-string line)))
  7555. (search (concat file "::" search))
  7556. (t file)))
  7557. (dlink (downcase link))
  7558. (ext
  7559. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7560. (match-string 1 dfile)))
  7561. (save-position-maybe
  7562. (let ((old-buffer (current-buffer))
  7563. (old-pos (point))
  7564. (old-mode major-mode))
  7565. (lambda ()
  7566. (and (derived-mode-p 'org-mode)
  7567. (eq old-mode 'org-mode)
  7568. (or (not (eq old-buffer (current-buffer)))
  7569. (not (eq old-pos (point))))
  7570. (org-mark-ring-push old-pos old-buffer)))))
  7571. cmd link-match-data)
  7572. (cond
  7573. ((member in-emacs '((16) system))
  7574. (setq cmd (cdr (assq 'system apps))))
  7575. (in-emacs (setq cmd 'emacs))
  7576. (t
  7577. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7578. (and dirp (cdr (assq 'directory apps)))
  7579. ;; First, try matching against apps-dlink if we
  7580. ;; get a match here, store the match data for
  7581. ;; later.
  7582. (let ((match (assoc-default dlink apps-dlink
  7583. 'string-match)))
  7584. (if match
  7585. (progn (setq link-match-data (match-data))
  7586. match)
  7587. (progn (setq in-emacs (or in-emacs line search))
  7588. nil))) ; if we have no match in apps-dlink,
  7589. ; always open the file in emacs if line or search
  7590. ; is given (for backwards compatibility)
  7591. (assoc-default dfile
  7592. (org--file-apps-regexp-alist apps a-m-a-p)
  7593. 'string-match)
  7594. (cdr (assoc ext apps))
  7595. (cdr (assq t apps))))))
  7596. (when (eq cmd 'system)
  7597. (setq cmd (cdr (assq 'system apps))))
  7598. (when (eq cmd 'default)
  7599. (setq cmd (cdr (assoc t apps))))
  7600. (when (eq cmd 'mailcap)
  7601. (require 'mailcap)
  7602. (mailcap-parse-mailcaps)
  7603. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7604. (command (mailcap-mime-info mime-type)))
  7605. (if (stringp command)
  7606. (setq cmd command)
  7607. (setq cmd 'emacs))))
  7608. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7609. (not (file-exists-p file))
  7610. (not org-open-non-existing-files))
  7611. (user-error "No such file: %s" file))
  7612. (cond
  7613. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7614. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7615. (while (string-match "['\"]%s['\"]" cmd)
  7616. (setq cmd (replace-match "%s" t t cmd)))
  7617. (setq cmd (replace-regexp-in-string
  7618. "%s"
  7619. (shell-quote-argument (convert-standard-filename file))
  7620. cmd
  7621. nil t))
  7622. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7623. (save-match-data
  7624. (let ((match-index 1)
  7625. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7626. (set-match-data link-match-data)
  7627. (while (<= match-index number-of-groups)
  7628. (let ((regex (concat "%" (number-to-string match-index)))
  7629. (replace-with (match-string match-index dlink)))
  7630. (while (string-match regex cmd)
  7631. (setq cmd (replace-match replace-with t t cmd))))
  7632. (setq match-index (+ match-index 1)))))
  7633. (save-window-excursion
  7634. (message "Running %s...done" cmd)
  7635. (start-process-shell-command cmd nil cmd)
  7636. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7637. ((or (stringp cmd)
  7638. (eq cmd 'emacs))
  7639. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7640. (widen)
  7641. (cond (line (org-goto-line line)
  7642. (when (derived-mode-p 'org-mode) (org-reveal)))
  7643. (search (condition-case err
  7644. (org-link-search search)
  7645. ;; Save position before error-ing out so user
  7646. ;; can easily move back to the original buffer.
  7647. (error (funcall save-position-maybe)
  7648. (error (nth 1 err)))))))
  7649. ((functionp cmd)
  7650. (save-match-data
  7651. (set-match-data link-match-data)
  7652. (condition-case nil
  7653. (funcall cmd file link)
  7654. ;; FIXME: Remove this check when most default installations
  7655. ;; of Emacs have at least Org 9.0.
  7656. ((debug wrong-number-of-arguments wrong-type-argument
  7657. invalid-function)
  7658. (user-error "Please see Org News for version 9.0 about \
  7659. `org-file-apps'--Lisp error: %S" cmd)))))
  7660. ((consp cmd)
  7661. ;; FIXME: Remove this check when most default installations of
  7662. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7663. ;; fall back to `org-link-frame-setup' for an old usage of
  7664. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7665. (user-error "Please see Org News for version 9.0 about \
  7666. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7667. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7668. (funcall save-position-maybe)))
  7669. ;;;###autoload
  7670. (defun org-open-at-point-global ()
  7671. "Follow a link or a time-stamp like Org mode does.
  7672. Also follow links and emails as seen by `thing-at-point'.
  7673. This command can be called in any mode to follow an external
  7674. link or a time-stamp that has Org mode syntax. Its behavior
  7675. is undefined when called on internal links like fuzzy links.
  7676. Raise a user error when there is nothing to follow."
  7677. (interactive)
  7678. (let ((tap-url (thing-at-point 'url))
  7679. (tap-email (thing-at-point 'email)))
  7680. (cond ((org-in-regexp org-link-any-re)
  7681. (org-link-open-from-string (match-string-no-properties 0)))
  7682. ((or (org-in-regexp org-ts-regexp-both nil t)
  7683. (org-in-regexp org-tsr-regexp-both nil t))
  7684. (org-follow-timestamp-link))
  7685. (tap-url (org-link-open-from-string tap-url))
  7686. (tap-email (org-link-open-from-string
  7687. (concat "mailto:" tap-email)))
  7688. (t (user-error "No link found")))))
  7689. (defvar org-open-at-point-functions nil
  7690. "Hook that is run when following a link at point.
  7691. Functions in this hook must return t if they identify and follow
  7692. a link at point. If they don't find anything interesting at point,
  7693. they must return nil.")
  7694. (defun org-open-at-point (&optional arg)
  7695. "Open link, timestamp, footnote or tags at point.
  7696. When point is on a link, follow it. Normally, files will be
  7697. opened by an appropriate application. If the optional prefix
  7698. argument ARG is non-nil, Emacs will visit the file. With
  7699. a double prefix argument, try to open outside of Emacs, in the
  7700. application the system uses for this file type.
  7701. When point is on a timestamp, open the agenda at the day
  7702. specified.
  7703. When point is a footnote definition, move to the first reference
  7704. found. If it is on a reference, move to the associated
  7705. definition.
  7706. When point is on a headline, display a list of every link in the
  7707. entry, so it is possible to pick one, or all, of them. If point
  7708. is on a tag, call `org-tags-view' instead.
  7709. On top of syntactically correct links, this function also tries
  7710. to open links and time-stamps in comments, node properties, and
  7711. keywords if point is on something looking like a timestamp or
  7712. a link."
  7713. (interactive "P")
  7714. (org-load-modules-maybe)
  7715. (setq org-window-config-before-follow-link (current-window-configuration))
  7716. (org-remove-occur-highlights nil nil t)
  7717. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7718. (let* ((context
  7719. ;; Only consider supported types, even if they are not the
  7720. ;; closest one.
  7721. (org-element-lineage
  7722. (org-element-context)
  7723. '(clock comment comment-block footnote-definition
  7724. footnote-reference headline inline-src-block inlinetask
  7725. keyword link node-property planning src-block timestamp)
  7726. t))
  7727. (type (org-element-type context))
  7728. (value (org-element-property :value context)))
  7729. (cond
  7730. ((not type) (user-error "No link found"))
  7731. ;; No valid link at point. For convenience, look if something
  7732. ;; looks like a link under point in some specific places.
  7733. ((memq type '(comment comment-block node-property keyword))
  7734. (call-interactively #'org-open-at-point-global))
  7735. ;; On a headline or an inlinetask, but not on a timestamp,
  7736. ;; a link, a footnote reference.
  7737. ((memq type '(headline inlinetask))
  7738. (org-match-line org-complex-heading-regexp)
  7739. (if (and (match-beginning 5)
  7740. (>= (point) (match-beginning 5))
  7741. (< (point) (match-end 5)))
  7742. ;; On tags.
  7743. (org-tags-view
  7744. arg
  7745. (save-excursion
  7746. (let* ((beg (match-beginning 5))
  7747. (end (match-end 5))
  7748. (beg-tag (or (search-backward ":" beg 'at-limit) (point)))
  7749. (end-tag (search-forward ":" end nil 2)))
  7750. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7751. ;; Not on tags.
  7752. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7753. (`(nil . ,_)
  7754. (require 'org-attach)
  7755. (message "Opening attachment-dir")
  7756. (if (equal arg '(4))
  7757. (org-attach-reveal-in-emacs)
  7758. (org-attach-reveal)))
  7759. (`(,links . ,links-end)
  7760. (dolist (link (if (stringp links) (list links) links))
  7761. (search-forward link nil links-end)
  7762. (goto-char (match-beginning 0))
  7763. (org-open-at-point arg))))))
  7764. ;; On a footnote reference or at definition's label.
  7765. ((or (eq type 'footnote-reference)
  7766. (and (eq type 'footnote-definition)
  7767. (save-excursion
  7768. ;; Do not validate action when point is on the
  7769. ;; spaces right after the footnote label, in order
  7770. ;; to be on par with behavior on links.
  7771. (skip-chars-forward " \t")
  7772. (let ((begin
  7773. (org-element-property :contents-begin context)))
  7774. (if begin (< (point) begin)
  7775. (= (org-element-property :post-affiliated context)
  7776. (line-beginning-position)))))))
  7777. (org-footnote-action))
  7778. ;; On a planning line. Check if we are really on a timestamp.
  7779. ((and (eq type 'planning)
  7780. (org-in-regexp org-ts-regexp-both nil t))
  7781. (org-follow-timestamp-link))
  7782. ;; On a clock line, make sure point is on the timestamp
  7783. ;; before opening it.
  7784. ((and (eq type 'clock)
  7785. value
  7786. (>= (point) (org-element-property :begin value))
  7787. (<= (point) (org-element-property :end value)))
  7788. (org-follow-timestamp-link))
  7789. ((eq type 'src-block) (org-babel-open-src-block-result))
  7790. ;; Do nothing on white spaces after an object.
  7791. ((>= (point)
  7792. (save-excursion
  7793. (goto-char (org-element-property :end context))
  7794. (skip-chars-backward " \t")
  7795. (point)))
  7796. (user-error "No link found"))
  7797. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7798. ((eq type 'timestamp) (org-follow-timestamp-link))
  7799. ((eq type 'link) (org-link-open context arg))
  7800. (t (user-error "No link found")))))
  7801. (run-hook-with-args 'org-follow-link-hook))
  7802. ;;;###autoload
  7803. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7804. "Offer links in the current entry and return the selected link.
  7805. If there is only one link, return it.
  7806. If NTH is an integer, return the NTH link found.
  7807. If ZERO is a string, check also this string for a link, and if
  7808. there is one, return it."
  7809. (with-current-buffer buffer
  7810. (org-with-wide-buffer
  7811. (goto-char marker)
  7812. (let ((cnt ?0)
  7813. have-zero end links link c)
  7814. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7815. (push (match-string 0 zero) links)
  7816. (setq cnt (1- cnt) have-zero t))
  7817. (save-excursion
  7818. (org-back-to-heading t)
  7819. (setq end (save-excursion (outline-next-heading) (point)))
  7820. (while (re-search-forward org-link-any-re end t)
  7821. (push (match-string 0) links))
  7822. (setq links (org-uniquify (reverse links))))
  7823. (cond
  7824. ((null links)
  7825. (message "No links"))
  7826. ((equal (length links) 1)
  7827. (setq link (car links)))
  7828. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7829. (setq link (nth (if have-zero nth (1- nth)) links)))
  7830. (t ; we have to select a link
  7831. (save-excursion
  7832. (save-window-excursion
  7833. (delete-other-windows)
  7834. (with-output-to-temp-buffer "*Select Link*"
  7835. (dolist (l links)
  7836. (cond
  7837. ((not (string-match org-link-bracket-re l))
  7838. (princ (format "[%c] %s\n" (cl-incf cnt)
  7839. (org-unbracket-string "<" ">" l))))
  7840. ((match-end 2)
  7841. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7842. (match-string 2 l) (match-string 1 l))))
  7843. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7844. (match-string 1 l)))))))
  7845. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7846. (message "Select link to open, RET to open all:")
  7847. (setq c (read-char-exclusive))
  7848. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7849. (when (equal c ?q) (user-error "Abort"))
  7850. (if (equal c ?\C-m)
  7851. (setq link links)
  7852. (setq nth (- c ?0))
  7853. (when have-zero (setq nth (1+ nth)))
  7854. (unless (and (integerp nth) (>= (length links) nth))
  7855. (user-error "Invalid link selection"))
  7856. (setq link (nth (1- nth) links)))))
  7857. (cons link end)))))
  7858. ;;; File search
  7859. (defun org-do-occur (regexp &optional cleanup)
  7860. "Call the Emacs command `occur'.
  7861. If CLEANUP is non-nil, remove the printout of the regular expression
  7862. in the *Occur* buffer. This is useful if the regex is long and not useful
  7863. to read."
  7864. (occur regexp)
  7865. (when cleanup
  7866. (let ((cwin (selected-window)) win beg end)
  7867. (when (setq win (get-buffer-window "*Occur*"))
  7868. (select-window win))
  7869. (goto-char (point-min))
  7870. (when (re-search-forward "match[a-z]+" nil t)
  7871. (setq beg (match-end 0))
  7872. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7873. (setq end (1- (match-beginning 0)))))
  7874. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7875. (goto-char (point-min))
  7876. (select-window cwin))))
  7877. ;;; The Mark Ring
  7878. (defvar org-mark-ring nil
  7879. "Mark ring for positions before jumps in Org mode.")
  7880. (defvar org-mark-ring-last-goto nil
  7881. "Last position in the mark ring used to go back.")
  7882. ;; Fill and close the ring
  7883. (setq org-mark-ring nil)
  7884. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7885. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7886. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7887. org-mark-ring)
  7888. (defun org-mark-ring-push (&optional pos buffer)
  7889. "Put the current position into the mark ring and rotate it.
  7890. Also push position into the Emacs mark ring. If optional
  7891. argument POS and BUFFER are not nil, mark this location instead."
  7892. (interactive)
  7893. (let ((pos (or pos (point)))
  7894. (buffer (or buffer (current-buffer))))
  7895. (with-current-buffer buffer
  7896. (org-with-point-at pos (push-mark nil t)))
  7897. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  7898. (move-marker (car org-mark-ring) pos buffer))
  7899. (message
  7900. (substitute-command-keys
  7901. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  7902. (defun org-mark-ring-goto (&optional n)
  7903. "Jump to the previous position in the mark ring.
  7904. With prefix arg N, jump back that many stored positions. When
  7905. called several times in succession, walk through the entire ring.
  7906. Org mode commands jumping to a different position in the current file,
  7907. or to another Org file, automatically push the old position onto the ring."
  7908. (interactive "p")
  7909. (let (p m)
  7910. (if (eq last-command this-command)
  7911. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  7912. (setq p org-mark-ring))
  7913. (setq org-mark-ring-last-goto p)
  7914. (setq m (car p))
  7915. (pop-to-buffer-same-window (marker-buffer m))
  7916. (goto-char m)
  7917. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  7918. ;;; Following specific links
  7919. (defvar org-agenda-buffer-tmp-name)
  7920. (defvar org-agenda-start-on-weekday)
  7921. (defun org-follow-timestamp-link ()
  7922. "Open an agenda view for the time-stamp date/range at point."
  7923. (cond
  7924. ((org-at-date-range-p t)
  7925. (let ((org-agenda-start-on-weekday)
  7926. (t1 (match-string 1))
  7927. (t2 (match-string 2)) tt1 tt2)
  7928. (setq tt1 (time-to-days (org-time-string-to-time t1))
  7929. tt2 (time-to-days (org-time-string-to-time t2)))
  7930. (let ((org-agenda-buffer-tmp-name
  7931. (format "*Org Agenda(a:%s)"
  7932. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  7933. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  7934. ((org-at-timestamp-p 'lax)
  7935. (let ((org-agenda-buffer-tmp-name
  7936. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  7937. (org-agenda-list nil (time-to-days (org-time-string-to-time
  7938. (substring (match-string 1) 0 10)))
  7939. 1)))
  7940. (t (error "This should not happen"))))
  7941. ;;; Following file links
  7942. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  7943. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  7944. (declare-function mailcap-mime-info
  7945. "mailcap" (string &optional request no-decode))
  7946. (defvar org-wait nil)
  7947. ;;;; Refiling
  7948. (defun org-get-org-file ()
  7949. "Read a filename, with default directory `org-directory'."
  7950. (let ((default (or org-default-notes-file remember-data-file)))
  7951. (read-file-name (format "File name [%s]: " default)
  7952. (file-name-as-directory org-directory)
  7953. default)))
  7954. (defun org-notes-order-reversed-p ()
  7955. "Check if the current file should receive notes in reversed order."
  7956. (cond
  7957. ((not org-reverse-note-order) nil)
  7958. ((eq t org-reverse-note-order) t)
  7959. ((not (listp org-reverse-note-order)) nil)
  7960. (t (catch 'exit
  7961. (dolist (entry org-reverse-note-order)
  7962. (when (string-match (car entry) buffer-file-name)
  7963. (throw 'exit (cdr entry))))))))
  7964. (defvar org-refile-target-table nil
  7965. "The list of refile targets, created by `org-refile'.")
  7966. (defvar org-agenda-new-buffers nil
  7967. "Buffers created to visit agenda files.")
  7968. (defvar org-refile-cache nil
  7969. "Cache for refile targets.")
  7970. (defvar org-refile-markers nil
  7971. "All the markers used for caching refile locations.")
  7972. (defun org-refile-marker (pos)
  7973. "Get a new refile marker, but only if caching is in use."
  7974. (if (not org-refile-use-cache)
  7975. pos
  7976. (let ((m (make-marker)))
  7977. (move-marker m pos)
  7978. (push m org-refile-markers)
  7979. m)))
  7980. (defun org-refile-cache-clear ()
  7981. "Clear the refile cache and disable all the markers."
  7982. (dolist (m org-refile-markers) (move-marker m nil))
  7983. (setq org-refile-markers nil)
  7984. (setq org-refile-cache nil)
  7985. (message "Refile cache has been cleared"))
  7986. (defun org-refile-cache-check-set (set)
  7987. "Check if all the markers in the cache still have live buffers."
  7988. (let (marker)
  7989. (catch 'exit
  7990. (while (and set (setq marker (nth 3 (pop set))))
  7991. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  7992. (when (and marker (null (marker-buffer marker)))
  7993. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  7994. (sit-for 3)
  7995. (throw 'exit nil)))
  7996. t)))
  7997. (defun org-refile-cache-put (set &rest identifiers)
  7998. "Push the refile targets SET into the cache, under IDENTIFIERS."
  7999. (let* ((key (sha1 (prin1-to-string identifiers)))
  8000. (entry (assoc key org-refile-cache)))
  8001. (if entry
  8002. (setcdr entry set)
  8003. (push (cons key set) org-refile-cache))))
  8004. (defun org-refile-cache-get (&rest identifiers)
  8005. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  8006. (cond
  8007. ((not org-refile-cache) nil)
  8008. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  8009. (t
  8010. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  8011. org-refile-cache))))
  8012. (and set (org-refile-cache-check-set set) set)))))
  8013. (defvar org-outline-path-cache nil
  8014. "Alist between buffer positions and outline paths.
  8015. It value is an alist (POSITION . PATH) where POSITION is the
  8016. buffer position at the beginning of an entry and PATH is a list
  8017. of strings describing the outline path for that entry, in reverse
  8018. order.")
  8019. (defun org-refile-get-targets (&optional default-buffer)
  8020. "Produce a table with refile targets."
  8021. (let ((case-fold-search nil)
  8022. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  8023. (entries (or org-refile-targets '((nil . (:level . 1)))))
  8024. targets tgs files desc descre)
  8025. (message "Getting targets...")
  8026. (with-current-buffer (or default-buffer (current-buffer))
  8027. (dolist (entry entries)
  8028. (setq files (car entry) desc (cdr entry))
  8029. (cond
  8030. ((null files) (setq files (list (current-buffer))))
  8031. ((eq files 'org-agenda-files)
  8032. (setq files (org-agenda-files 'unrestricted)))
  8033. ((and (symbolp files) (fboundp files))
  8034. (setq files (funcall files)))
  8035. ((and (symbolp files) (boundp files))
  8036. (setq files (symbol-value files))))
  8037. (when (stringp files) (setq files (list files)))
  8038. (cond
  8039. ((eq (car desc) :tag)
  8040. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  8041. ((eq (car desc) :todo)
  8042. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  8043. ((eq (car desc) :regexp)
  8044. (setq descre (cdr desc)))
  8045. ((eq (car desc) :level)
  8046. (setq descre (concat "^\\*\\{" (number-to-string
  8047. (if org-odd-levels-only
  8048. (1- (* 2 (cdr desc)))
  8049. (cdr desc)))
  8050. "\\}[ \t]")))
  8051. ((eq (car desc) :maxlevel)
  8052. (setq descre (concat "^\\*\\{1," (number-to-string
  8053. (if org-odd-levels-only
  8054. (1- (* 2 (cdr desc)))
  8055. (cdr desc)))
  8056. "\\}[ \t]")))
  8057. (t (error "Bad refiling target description %s" desc)))
  8058. (dolist (f files)
  8059. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  8060. (or
  8061. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  8062. (progn
  8063. (when (bufferp f)
  8064. (setq f (buffer-file-name (buffer-base-buffer f))))
  8065. (setq f (and f (expand-file-name f)))
  8066. (when (eq org-refile-use-outline-path 'file)
  8067. (push (list (file-name-nondirectory f) f nil nil) tgs))
  8068. (when (eq org-refile-use-outline-path 'buffer-name)
  8069. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  8070. (when (eq org-refile-use-outline-path 'full-file-path)
  8071. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  8072. (org-with-wide-buffer
  8073. (goto-char (point-min))
  8074. (setq org-outline-path-cache nil)
  8075. (while (re-search-forward descre nil t)
  8076. (beginning-of-line)
  8077. (let ((case-fold-search nil))
  8078. (looking-at org-complex-heading-regexp))
  8079. (let ((begin (point))
  8080. (heading (match-string-no-properties 4)))
  8081. (unless (or (and
  8082. org-refile-target-verify-function
  8083. (not
  8084. (funcall org-refile-target-verify-function)))
  8085. (not heading))
  8086. (let ((re (format org-complex-heading-regexp-format
  8087. (regexp-quote heading)))
  8088. (target
  8089. (if (not org-refile-use-outline-path) heading
  8090. (mapconcat
  8091. #'identity
  8092. (append
  8093. (pcase org-refile-use-outline-path
  8094. (`file (list (file-name-nondirectory
  8095. (buffer-file-name
  8096. (buffer-base-buffer)))))
  8097. (`full-file-path
  8098. (list (buffer-file-name
  8099. (buffer-base-buffer))))
  8100. (`buffer-name
  8101. (list (buffer-name
  8102. (buffer-base-buffer))))
  8103. (_ nil))
  8104. (mapcar (lambda (s) (replace-regexp-in-string
  8105. "/" "\\/" s nil t))
  8106. (org-get-outline-path t t)))
  8107. "/"))))
  8108. (push (list target f re (org-refile-marker (point)))
  8109. tgs)))
  8110. (when (= (point) begin)
  8111. ;; Verification function has not moved point.
  8112. (end-of-line)))))))
  8113. (when org-refile-use-cache
  8114. (org-refile-cache-put tgs (buffer-file-name) descre))
  8115. (setq targets (append tgs targets))))))
  8116. (message "Getting targets...done")
  8117. (delete-dups (nreverse targets))))
  8118. (defun org--get-outline-path-1 (&optional use-cache)
  8119. "Return outline path to current headline.
  8120. Outline path is a list of strings, in reverse order. When
  8121. optional argument USE-CACHE is non-nil, make use of a cache. See
  8122. `org-get-outline-path' for details.
  8123. Assume buffer is widened and point is on a headline."
  8124. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  8125. (let ((p (point))
  8126. (heading (let ((case-fold-search nil))
  8127. (looking-at org-complex-heading-regexp)
  8128. (if (not (match-end 4)) ""
  8129. ;; Remove statistics cookies.
  8130. (org-trim
  8131. (org-link-display-format
  8132. (replace-regexp-in-string
  8133. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  8134. (match-string-no-properties 4))))))))
  8135. (if (org-up-heading-safe)
  8136. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  8137. (when use-cache
  8138. (push (cons p path) org-outline-path-cache))
  8139. path)
  8140. ;; This is a new root node. Since we assume we are moving
  8141. ;; forward, we can drop previous cache so as to limit number
  8142. ;; of associations there.
  8143. (let ((path (list heading)))
  8144. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  8145. path)))))
  8146. (defun org-get-outline-path (&optional with-self use-cache)
  8147. "Return the outline path to the current entry.
  8148. An outline path is a list of ancestors for current headline, as
  8149. a list of strings. Statistics cookies are removed and links are
  8150. replaced with their description, if any, or their path otherwise.
  8151. When optional argument WITH-SELF is non-nil, the path also
  8152. includes the current headline.
  8153. When optional argument USE-CACHE is non-nil, cache outline paths
  8154. between calls to this function so as to avoid backtracking. This
  8155. argument is useful when planning to find more than one outline
  8156. path in the same document. In that case, there are two
  8157. conditions to satisfy:
  8158. - `org-outline-path-cache' is set to nil before starting the
  8159. process;
  8160. - outline paths are computed by increasing buffer positions."
  8161. (org-with-wide-buffer
  8162. (and (or (and with-self (org-back-to-heading t))
  8163. (org-up-heading-safe))
  8164. (reverse (org--get-outline-path-1 use-cache)))))
  8165. (defun org-format-outline-path (path &optional width prefix separator)
  8166. "Format the outline path PATH for display.
  8167. WIDTH is the maximum number of characters that is available.
  8168. PREFIX is a prefix to be included in the returned string,
  8169. such as the file name.
  8170. SEPARATOR is inserted between the different parts of the path,
  8171. the default is \"/\"."
  8172. (setq width (or width 79))
  8173. (setq path (delq nil path))
  8174. (unless (> width 0)
  8175. (user-error "Argument `width' must be positive"))
  8176. (setq separator (or separator "/"))
  8177. (let* ((org-odd-levels-only nil)
  8178. (fpath (concat
  8179. prefix (and prefix path separator)
  8180. (mapconcat
  8181. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  8182. (cl-loop for head in path
  8183. for n from 0
  8184. collect (org-add-props
  8185. head nil 'face
  8186. (nth (% n org-n-level-faces) org-level-faces)))
  8187. separator))))
  8188. (when (> (length fpath) width)
  8189. (if (< width 7)
  8190. ;; It's unlikely that `width' will be this small, but don't
  8191. ;; waste characters by adding ".." if it is.
  8192. (setq fpath (substring fpath 0 width))
  8193. (setf (substring fpath (- width 2)) "..")))
  8194. fpath))
  8195. (defun org-display-outline-path (&optional file current separator just-return-string)
  8196. "Display the current outline path in the echo area.
  8197. If FILE is non-nil, prepend the output with the file name.
  8198. If CURRENT is non-nil, append the current heading to the output.
  8199. SEPARATOR is passed through to `org-format-outline-path'. It separates
  8200. the different parts of the path and defaults to \"/\".
  8201. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  8202. (interactive "P")
  8203. (let* (case-fold-search
  8204. (bfn (buffer-file-name (buffer-base-buffer)))
  8205. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  8206. res)
  8207. (when current (setq path (append path
  8208. (save-excursion
  8209. (org-back-to-heading t)
  8210. (when (looking-at org-complex-heading-regexp)
  8211. (list (match-string 4)))))))
  8212. (setq res
  8213. (org-format-outline-path
  8214. path
  8215. (1- (frame-width))
  8216. (and file bfn (concat (file-name-nondirectory bfn) separator))
  8217. separator))
  8218. (if just-return-string
  8219. (org-no-properties res)
  8220. (org-unlogged-message "%s" res))))
  8221. (defvar org-refile-history nil
  8222. "History for refiling operations.")
  8223. (defvar org-after-refile-insert-hook nil
  8224. "Hook run after `org-refile' has inserted its stuff at the new location.
  8225. Note that this is still *before* the stuff will be removed from
  8226. the *old* location.")
  8227. (defvar org-capture-last-stored-marker)
  8228. (defvar org-refile-keep nil
  8229. "Non-nil means `org-refile' will copy instead of refile.")
  8230. (defun org-copy ()
  8231. "Like `org-refile', but copy."
  8232. (interactive)
  8233. (let ((org-refile-keep t))
  8234. (org-refile nil nil nil "Copy")))
  8235. (defun org-refile (&optional arg default-buffer rfloc msg)
  8236. "Move the entry or entries at point to another heading.
  8237. The list of target headings is compiled using the information in
  8238. `org-refile-targets', which see.
  8239. At the target location, the entry is filed as a subitem of the
  8240. target heading. Depending on `org-reverse-note-order', the new
  8241. subitem will either be the first or the last subitem.
  8242. If there is an active region, all entries in that region will be
  8243. refiled. However, the region must fulfill the requirement that
  8244. the first heading sets the top-level of the moved text.
  8245. With a `\\[universal-argument]' ARG, the command will only visit the target \
  8246. location
  8247. and not actually move anything.
  8248. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  8249. location where the last
  8250. refiling operation has put the subtree.
  8251. With a numeric prefix argument of `2', refile to the running clock.
  8252. With a numeric prefix argument of `3', emulate `org-refile-keep'
  8253. being set to t and copy to the target location, don't move it.
  8254. Beware that keeping refiled entries may result in duplicated ID
  8255. properties.
  8256. RFLOC can be a refile location obtained in a different way.
  8257. MSG is a string to replace \"Refile\" in the default prompt with
  8258. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  8259. See also `org-refile-use-outline-path'.
  8260. If you are using target caching (see `org-refile-use-cache'), you
  8261. have to clear the target cache in order to find new targets.
  8262. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  8263. prefix argument (`C-u C-u C-u C-c C-w')."
  8264. (interactive "P")
  8265. (if (member arg '(0 (64)))
  8266. (org-refile-cache-clear)
  8267. (let* ((actionmsg (cond (msg msg)
  8268. ((equal arg 3) "Refile (and keep)")
  8269. (t "Refile")))
  8270. (regionp (org-region-active-p))
  8271. (region-start (and regionp (region-beginning)))
  8272. (region-end (and regionp (region-end)))
  8273. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  8274. pos it nbuf file level reversed)
  8275. (setq last-command nil)
  8276. (when regionp
  8277. (goto-char region-start)
  8278. (beginning-of-line)
  8279. (setq region-start (point))
  8280. (unless (or (org-kill-is-subtree-p
  8281. (buffer-substring region-start region-end))
  8282. (prog1 org-refile-active-region-within-subtree
  8283. (let ((s (point-at-eol)))
  8284. (org-toggle-heading)
  8285. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  8286. (user-error "The region is not a (sequence of) subtree(s)")))
  8287. (if (equal arg '(16))
  8288. (org-refile-goto-last-stored)
  8289. (when (or
  8290. (and (equal arg 2)
  8291. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  8292. (prog1
  8293. (setq it (list (or org-clock-heading "running clock")
  8294. (buffer-file-name
  8295. (marker-buffer org-clock-hd-marker))
  8296. ""
  8297. (marker-position org-clock-hd-marker)))
  8298. (setq arg nil)))
  8299. (setq it
  8300. (or rfloc
  8301. (let (heading-text)
  8302. (save-excursion
  8303. (unless (and arg (listp arg))
  8304. (org-back-to-heading t)
  8305. (setq heading-text
  8306. (replace-regexp-in-string
  8307. org-link-bracket-re
  8308. "\\2"
  8309. (or (nth 4 (org-heading-components))
  8310. ""))))
  8311. (org-refile-get-location
  8312. (cond ((and arg (listp arg)) "Goto")
  8313. (regionp (concat actionmsg " region to"))
  8314. (t (concat actionmsg " subtree \""
  8315. heading-text "\" to")))
  8316. default-buffer
  8317. (and (not (equal '(4) arg))
  8318. org-refile-allow-creating-parent-nodes)))))))
  8319. (setq file (nth 1 it)
  8320. pos (nth 3 it))
  8321. (when (and (not arg)
  8322. pos
  8323. (equal (buffer-file-name) file)
  8324. (if regionp
  8325. (and (>= pos region-start)
  8326. (<= pos region-end))
  8327. (and (>= pos (point))
  8328. (< pos (save-excursion
  8329. (org-end-of-subtree t t))))))
  8330. (error "Cannot refile to position inside the tree or region"))
  8331. (setq nbuf (or (find-buffer-visiting file)
  8332. (find-file-noselect file)))
  8333. (if (and arg (not (equal arg 3)))
  8334. (progn
  8335. (pop-to-buffer-same-window nbuf)
  8336. (goto-char (cond (pos)
  8337. ((org-notes-order-reversed-p) (point-min))
  8338. (t (point-max))))
  8339. (org-show-context 'org-goto))
  8340. (if regionp
  8341. (progn
  8342. (org-kill-new (buffer-substring region-start region-end))
  8343. (org-save-markers-in-region region-start region-end))
  8344. (org-copy-subtree 1 nil t))
  8345. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  8346. (find-file-noselect file)))
  8347. (setq reversed (org-notes-order-reversed-p))
  8348. (org-with-wide-buffer
  8349. (if pos
  8350. (progn
  8351. (goto-char pos)
  8352. (setq level (org-get-valid-level (funcall outline-level) 1))
  8353. (goto-char
  8354. (if reversed
  8355. (or (outline-next-heading) (point-max))
  8356. (or (save-excursion (org-get-next-sibling))
  8357. (org-end-of-subtree t t)
  8358. (point-max)))))
  8359. (setq level 1)
  8360. (if (not reversed)
  8361. (goto-char (point-max))
  8362. (goto-char (point-min))
  8363. (or (outline-next-heading) (goto-char (point-max)))))
  8364. (unless (bolp) (newline))
  8365. (org-paste-subtree level nil nil t)
  8366. ;; Record information, according to `org-log-refile'.
  8367. ;; Do not prompt for a note when refiling multiple
  8368. ;; headlines, however. Simply add a time stamp.
  8369. (cond
  8370. ((not org-log-refile))
  8371. (regionp
  8372. (org-map-region
  8373. (lambda () (org-add-log-setup 'refile nil nil 'time))
  8374. (point)
  8375. (+ (point) (- region-end region-start))))
  8376. (t
  8377. (org-add-log-setup 'refile nil nil org-log-refile)))
  8378. (and org-auto-align-tags
  8379. (let ((org-loop-over-headlines-in-active-region nil))
  8380. (org-align-tags)))
  8381. (let ((bookmark-name (plist-get org-bookmark-names-plist
  8382. :last-refile)))
  8383. (when bookmark-name
  8384. (with-demoted-errors
  8385. (bookmark-set bookmark-name))))
  8386. ;; If we are refiling for capture, make sure that the
  8387. ;; last-capture pointers point here
  8388. (when (bound-and-true-p org-capture-is-refiling)
  8389. (let ((bookmark-name (plist-get org-bookmark-names-plist
  8390. :last-capture-marker)))
  8391. (when bookmark-name
  8392. (with-demoted-errors
  8393. (bookmark-set bookmark-name))))
  8394. (move-marker org-capture-last-stored-marker (point)))
  8395. (when (fboundp 'deactivate-mark) (deactivate-mark))
  8396. (run-hooks 'org-after-refile-insert-hook)))
  8397. (unless org-refile-keep
  8398. (if regionp
  8399. (delete-region (point) (+ (point) (- region-end region-start)))
  8400. (org-preserve-local-variables
  8401. (delete-region
  8402. (and (org-back-to-heading t) (point))
  8403. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  8404. (when (featurep 'org-inlinetask)
  8405. (org-inlinetask-remove-END-maybe))
  8406. (setq org-markers-to-move nil)
  8407. (message "%s to \"%s\" in file %s: done" actionmsg
  8408. (car it) file)))))))
  8409. (defun org-refile-goto-last-stored ()
  8410. "Go to the location where the last refile was stored."
  8411. (interactive)
  8412. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  8413. (message "This is the location of the last refile"))
  8414. (defun org-refile--get-location (refloc tbl)
  8415. "When user refile to REFLOC, find the associated target in TBL.
  8416. Also check `org-refile-target-table'."
  8417. (car (delq
  8418. nil
  8419. (mapcar
  8420. (lambda (r) (or (assoc r tbl)
  8421. (assoc r org-refile-target-table)))
  8422. (list (replace-regexp-in-string "/$" "" refloc)
  8423. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  8424. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  8425. "Prompt the user for a refile location, using PROMPT.
  8426. PROMPT should not be suffixed with a colon and a space, because
  8427. this function appends the default value from
  8428. `org-refile-history' automatically, if that is not empty."
  8429. (let ((org-refile-targets org-refile-targets)
  8430. (org-refile-use-outline-path org-refile-use-outline-path))
  8431. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  8432. (unless org-refile-target-table
  8433. (user-error "No refile targets"))
  8434. (let* ((cbuf (current-buffer))
  8435. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  8436. (cfunc (if (and org-refile-use-outline-path
  8437. org-outline-path-complete-in-steps)
  8438. #'org-olpath-completing-read
  8439. #'completing-read))
  8440. (extra (if org-refile-use-outline-path "/" ""))
  8441. (cbnex (concat (buffer-name) extra))
  8442. (filename (and cfn (expand-file-name cfn)))
  8443. (tbl (mapcar
  8444. (lambda (x)
  8445. (if (and (not (member org-refile-use-outline-path
  8446. '(file full-file-path)))
  8447. (not (equal filename (nth 1 x))))
  8448. (cons (concat (car x) extra " ("
  8449. (file-name-nondirectory (nth 1 x)) ")")
  8450. (cdr x))
  8451. (cons (concat (car x) extra) (cdr x))))
  8452. org-refile-target-table))
  8453. (completion-ignore-case t)
  8454. cdef
  8455. (prompt (concat prompt
  8456. (or (and (car org-refile-history)
  8457. (concat " (default " (car org-refile-history) ")"))
  8458. (and (assoc cbnex tbl) (setq cdef cbnex)
  8459. (concat " (default " cbnex ")"))) ": "))
  8460. pa answ parent-target child parent old-hist)
  8461. (setq old-hist org-refile-history)
  8462. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  8463. nil 'org-refile-history (or cdef (car org-refile-history))))
  8464. (if (setq pa (org-refile--get-location answ tbl))
  8465. (progn
  8466. (org-refile-check-position pa)
  8467. (when (or (not org-refile-history)
  8468. (not (eq old-hist org-refile-history))
  8469. (not (equal (car pa) (car org-refile-history))))
  8470. (setq org-refile-history
  8471. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  8472. org-refile-history
  8473. (cdr org-refile-history))))
  8474. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  8475. (pop org-refile-history)))
  8476. pa)
  8477. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  8478. (progn
  8479. (setq parent (match-string 1 answ)
  8480. child (match-string 2 answ))
  8481. (setq parent-target (org-refile--get-location parent tbl))
  8482. (when (and parent-target
  8483. (or (eq new-nodes t)
  8484. (and (eq new-nodes 'confirm)
  8485. (y-or-n-p (format "Create new node \"%s\"? "
  8486. child)))))
  8487. (org-refile-new-child parent-target child)))
  8488. (user-error "Invalid target location")))))
  8489. (declare-function org-string-nw-p "org-macs" (s))
  8490. (defun org-refile-check-position (refile-pointer)
  8491. "Check if the refile pointer matches the headline to which it points."
  8492. (let* ((file (nth 1 refile-pointer))
  8493. (re (nth 2 refile-pointer))
  8494. (pos (nth 3 refile-pointer))
  8495. buffer)
  8496. (if (and (not (markerp pos)) (not file))
  8497. (user-error "Please indicate a target file in the refile path")
  8498. (when (org-string-nw-p re)
  8499. (setq buffer (if (markerp pos)
  8500. (marker-buffer pos)
  8501. (or (find-buffer-visiting file)
  8502. (find-file-noselect file))))
  8503. (with-current-buffer buffer
  8504. (org-with-wide-buffer
  8505. (goto-char pos)
  8506. (beginning-of-line 1)
  8507. (unless (looking-at-p re)
  8508. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  8509. (defun org-refile-new-child (parent-target child)
  8510. "Use refile target PARENT-TARGET to add new CHILD below it."
  8511. (unless parent-target
  8512. (error "Cannot find parent for new node"))
  8513. (let ((file (nth 1 parent-target))
  8514. (pos (nth 3 parent-target))
  8515. level)
  8516. (with-current-buffer (or (find-buffer-visiting file)
  8517. (find-file-noselect file))
  8518. (org-with-wide-buffer
  8519. (if pos
  8520. (goto-char pos)
  8521. (goto-char (point-max))
  8522. (unless (bolp) (newline)))
  8523. (when (looking-at org-outline-regexp)
  8524. (setq level (funcall outline-level))
  8525. (org-end-of-subtree t t))
  8526. (org-back-over-empty-lines)
  8527. (insert "\n" (make-string
  8528. (if pos (org-get-valid-level level 1) 1) ?*)
  8529. " " child "\n")
  8530. (beginning-of-line 0)
  8531. (list (concat (car parent-target) "/" child) file "" (point))))))
  8532. (defun org-olpath-completing-read (prompt collection &rest args)
  8533. "Read an outline path like a file name."
  8534. (let ((thetable collection))
  8535. (apply #'completing-read
  8536. prompt
  8537. (lambda (string predicate &optional flag)
  8538. (cond
  8539. ((eq flag nil) (try-completion string thetable))
  8540. ((eq flag t)
  8541. (let ((l (length string)))
  8542. (mapcar (lambda (x)
  8543. (let ((r (substring x l))
  8544. (f (if (string-match " ([^)]*)$" x)
  8545. (match-string 0 x)
  8546. "")))
  8547. (if (string-match "/" r)
  8548. (concat string (substring r 0 (match-end 0)) f)
  8549. x)))
  8550. (all-completions string thetable predicate))))
  8551. ;; Exact match?
  8552. ((eq flag 'lambda) (assoc string thetable))))
  8553. args)))
  8554. ;;;; Dynamic blocks
  8555. (defun org-find-dblock (name)
  8556. "Find the first dynamic block with name NAME in the buffer.
  8557. If not found, stay at current position and return nil."
  8558. (let ((case-fold-search t) pos)
  8559. (save-excursion
  8560. (goto-char (point-min))
  8561. (setq pos (and (re-search-forward
  8562. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8563. (match-beginning 0))))
  8564. (when pos (goto-char pos))
  8565. pos))
  8566. (defun org-create-dblock (plist)
  8567. "Create a dynamic block section, with parameters taken from PLIST.
  8568. PLIST must contain a :name entry which is used as the name of the block."
  8569. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8570. (end-of-line 1)
  8571. (newline))
  8572. (let ((col (current-column))
  8573. (name (plist-get plist :name)))
  8574. (insert "#+BEGIN: " name)
  8575. (while plist
  8576. (if (eq (car plist) :name)
  8577. (setq plist (cddr plist))
  8578. (insert " " (prin1-to-string (pop plist)))))
  8579. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8580. (beginning-of-line -2)))
  8581. (defun org-prepare-dblock ()
  8582. "Prepare dynamic block for refresh.
  8583. This empties the block, puts the cursor at the insert position and returns
  8584. the property list including an extra property :name with the block name."
  8585. (unless (looking-at org-dblock-start-re)
  8586. (user-error "Not at a dynamic block"))
  8587. (let* ((begdel (1+ (match-end 0)))
  8588. (name (org-no-properties (match-string 1)))
  8589. (params (append (list :name name)
  8590. (read (concat "(" (match-string 3) ")")))))
  8591. (save-excursion
  8592. (beginning-of-line 1)
  8593. (skip-chars-forward " \t")
  8594. (setq params (plist-put params :indentation-column (current-column))))
  8595. (unless (re-search-forward org-dblock-end-re nil t)
  8596. (error "Dynamic block not terminated"))
  8597. (setq params
  8598. (append params
  8599. (list :content (buffer-substring
  8600. begdel (match-beginning 0)))))
  8601. (delete-region begdel (match-beginning 0))
  8602. (goto-char begdel)
  8603. (open-line 1)
  8604. params))
  8605. (defun org-map-dblocks (&optional command)
  8606. "Apply COMMAND to all dynamic blocks in the current buffer.
  8607. If COMMAND is not given, use `org-update-dblock'."
  8608. (let ((cmd (or command 'org-update-dblock)))
  8609. (save-excursion
  8610. (goto-char (point-min))
  8611. (while (re-search-forward org-dblock-start-re nil t)
  8612. (goto-char (match-beginning 0))
  8613. (save-excursion
  8614. (condition-case nil
  8615. (funcall cmd)
  8616. (error (message "Error during update of dynamic block"))))
  8617. (unless (re-search-forward org-dblock-end-re nil t)
  8618. (error "Dynamic block not terminated"))))))
  8619. (defvar org-dynamic-block-alist nil
  8620. "Alist defining all the Org dynamic blocks.
  8621. The key is the dynamic block type name, as a string. The value
  8622. is the function used to insert the dynamic block.
  8623. Use `org-dynamic-block-define' to populate it.")
  8624. (defun org-dynamic-block-function (type)
  8625. "Return function associated to a given dynamic block type.
  8626. TYPE is the dynamic block type, as a string."
  8627. (cdr (assoc type org-dynamic-block-alist)))
  8628. (defun org-dynamic-block-types ()
  8629. "List all defined dynamic block types."
  8630. (mapcar #'car org-dynamic-block-alist))
  8631. (defun org-dynamic-block-define (type func)
  8632. "Define dynamic block TYPE with FUNC.
  8633. TYPE is a string. FUNC is the function creating the dynamic
  8634. block of such type."
  8635. (pcase (assoc type org-dynamic-block-alist)
  8636. (`nil (push (cons type func) org-dynamic-block-alist))
  8637. (def (setcdr def func))))
  8638. (defun org-dynamic-block-insert-dblock (type)
  8639. "Insert a dynamic block of type TYPE.
  8640. When used interactively, select the dynamic block types among
  8641. defined types, per `org-dynamic-block-define'."
  8642. (interactive (list (completing-read "Dynamic block: "
  8643. (org-dynamic-block-types))))
  8644. (pcase (org-dynamic-block-function type)
  8645. (`nil (error "No such dynamic block: %S" type))
  8646. ((and f (pred functionp)) (funcall f))
  8647. (_ (error "Invalid function for dynamic block %S" type))))
  8648. (defun org-dblock-update (&optional arg)
  8649. "User command for updating dynamic blocks.
  8650. Update the dynamic block at point. With prefix ARG, update all dynamic
  8651. blocks in the buffer."
  8652. (interactive "P")
  8653. (if arg
  8654. (org-update-all-dblocks)
  8655. (or (looking-at org-dblock-start-re)
  8656. (org-beginning-of-dblock))
  8657. (org-update-dblock)))
  8658. (defun org-update-dblock ()
  8659. "Update the dynamic block at point.
  8660. This means to empty the block, parse for parameters and then call
  8661. the correct writing function."
  8662. (interactive)
  8663. (save-excursion
  8664. (let* ((win (selected-window))
  8665. (pos (point))
  8666. (line (org-current-line))
  8667. (params (org-prepare-dblock))
  8668. (name (plist-get params :name))
  8669. (indent (plist-get params :indentation-column))
  8670. (cmd (intern (concat "org-dblock-write:" name))))
  8671. (message "Updating dynamic block `%s' at line %d..." name line)
  8672. (funcall cmd params)
  8673. (message "Updating dynamic block `%s' at line %d...done" name line)
  8674. (goto-char pos)
  8675. (when (and indent (> indent 0))
  8676. (setq indent (make-string indent ?\ ))
  8677. (save-excursion
  8678. (select-window win)
  8679. (org-beginning-of-dblock)
  8680. (forward-line 1)
  8681. (while (not (looking-at org-dblock-end-re))
  8682. (insert indent)
  8683. (beginning-of-line 2))
  8684. (when (looking-at org-dblock-end-re)
  8685. (and (looking-at "[ \t]+")
  8686. (replace-match ""))
  8687. (insert indent)))))))
  8688. (defun org-beginning-of-dblock ()
  8689. "Find the beginning of the dynamic block at point.
  8690. Error if there is no such block at point."
  8691. (let ((pos (point))
  8692. beg)
  8693. (end-of-line 1)
  8694. (if (and (re-search-backward org-dblock-start-re nil t)
  8695. (setq beg (match-beginning 0))
  8696. (re-search-forward org-dblock-end-re nil t)
  8697. (> (match-end 0) pos))
  8698. (goto-char beg)
  8699. (goto-char pos)
  8700. (error "Not in a dynamic block"))))
  8701. (defun org-update-all-dblocks ()
  8702. "Update all dynamic blocks in the buffer.
  8703. This function can be used in a hook."
  8704. (interactive)
  8705. (when (derived-mode-p 'org-mode)
  8706. (org-map-dblocks 'org-update-dblock)))
  8707. ;;;; Completion
  8708. (declare-function org-export-backend-options "ox" (cl-x) t)
  8709. (defun org-get-export-keywords ()
  8710. "Return a list of all currently understood export keywords.
  8711. Export keywords include options, block names, attributes and
  8712. keywords relative to each registered export back-end."
  8713. (let (keywords)
  8714. (dolist (backend
  8715. (bound-and-true-p org-export-registered-backends)
  8716. (delq nil keywords))
  8717. ;; Back-end name (for keywords, like #+LATEX:)
  8718. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8719. (dolist (option-entry (org-export-backend-options backend))
  8720. ;; Back-end options.
  8721. (push (nth 1 option-entry) keywords)))))
  8722. (defconst org-options-keywords
  8723. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8724. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8725. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8726. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8727. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8728. (defcustom org-structure-template-alist
  8729. '(("a" . "export ascii")
  8730. ("c" . "center")
  8731. ("C" . "comment")
  8732. ("e" . "example")
  8733. ("E" . "export")
  8734. ("h" . "export html")
  8735. ("l" . "export latex")
  8736. ("q" . "quote")
  8737. ("s" . "src")
  8738. ("v" . "verse"))
  8739. "An alist of keys and block types.
  8740. `org-insert-structure-template' will display a menu with this
  8741. list of templates to choose from. The block type is inserted,
  8742. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8743. The menu keys are defined by the car of each entry in this alist.
  8744. If two entries have the keys \"a\" and \"aa\" respectively, the
  8745. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8746. latter will be inserted by typing \"aa\". If an entry with the
  8747. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8748. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8749. block can be inserted by pressing TAB after the string \"<KEY\"."
  8750. :group 'org-edit-structure
  8751. :type '(repeat
  8752. (cons (string :tag "Key")
  8753. (string :tag "Template")))
  8754. :package-version '(Org . "9.2"))
  8755. (defun org--check-org-structure-template-alist (&optional checklist)
  8756. "Check whether `org-structure-template-alist' is set up correctly.
  8757. In particular, check if the Org 9.2 format is used as opposed to
  8758. previous format.
  8759. "
  8760. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8761. (or (eval checklist)
  8762. org-structure-template-alist))))
  8763. (when elm
  8764. (org-display-warning
  8765. (format "
  8766. Please update the entries of `%s'.
  8767. In Org 9.2 the format was changed from something like
  8768. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8769. to something like
  8770. (\"s\" . \"src\")
  8771. Please refer to the documentation of `org-structure-template-alist'.
  8772. The following entries must be updated:
  8773. %s"
  8774. (or checklist 'org-structure-template-alist)
  8775. (pp-to-string elm))))))
  8776. (defun org--insert-structure-template-mks ()
  8777. "Present `org-structure-template-alist' with `org-mks'.
  8778. Menus are added if keys require more than one keystroke. Tabs
  8779. are added to single key entries when more than one stroke is
  8780. needed. Keys longer than two characters are reduced to two
  8781. characters."
  8782. (org--check-org-structure-template-alist)
  8783. (let* (case-fold-search
  8784. (templates (append org-structure-template-alist
  8785. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8786. (keys (mapcar #'car templates))
  8787. (start-letters
  8788. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8789. ;; Sort each element of `org-structure-template-alist' into
  8790. ;; sublists according to the first letter.
  8791. (superlist
  8792. (mapcar (lambda (letter)
  8793. (list letter
  8794. (cl-remove-if-not
  8795. (apply-partially #'string-match-p (concat "^" letter))
  8796. templates :key #'car)))
  8797. start-letters)))
  8798. (org-mks
  8799. (apply #'append
  8800. ;; Make an `org-mks' table. If only one element is
  8801. ;; present in a sublist, make it part of the top-menu,
  8802. ;; otherwise make a submenu according to the starting
  8803. ;; letter and populate it.
  8804. (mapcar (lambda (sublist)
  8805. (if (eq 1 (length (cadr sublist)))
  8806. (mapcar (lambda (elm)
  8807. (list (substring (car elm) 0 1)
  8808. (cdr elm) ""))
  8809. (cadr sublist))
  8810. ;; Create submenu.
  8811. (let* ((topkey (car sublist))
  8812. (elms (cadr sublist))
  8813. (keys (mapcar #'car elms))
  8814. (long (> (length elms) 3)))
  8815. (append
  8816. (list
  8817. ;; Make a description of the submenu.
  8818. (list topkey
  8819. (concat
  8820. (mapconcat #'cdr
  8821. (cl-subseq elms 0 (if long 3 (length elms)))
  8822. ", ")
  8823. (when long ", ..."))))
  8824. ;; List of entries in submenu.
  8825. (cl-mapcar #'list
  8826. (org--insert-structure-template-unique-keys keys)
  8827. (mapcar #'cdr elms)
  8828. (make-list (length elms) ""))))))
  8829. superlist))
  8830. "Select a key\n============"
  8831. "Key: ")))
  8832. (defun org--insert-structure-template-unique-keys (keys)
  8833. "Make a list of unique, two characters long elements from KEYS.
  8834. Elements of length one have a tab appended. Elements of length
  8835. two are kept as is. Longer elements are truncated to length two.
  8836. If an element cannot be made unique, an error is raised."
  8837. (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8838. menu-keys)
  8839. (dolist (key orderd-keys)
  8840. (let ((potential-key
  8841. (cl-case (length key)
  8842. (1 (concat key "\t"))
  8843. (2 key)
  8844. (otherwise
  8845. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8846. (mapcar (apply-partially #'concat (substring key 0 1))
  8847. (split-string (substring key 1) "" t)))))))
  8848. (if (or (not potential-key) (assoc potential-key menu-keys))
  8849. (user-error "Could not make unique key for %s." key)
  8850. (push (cons potential-key key) menu-keys))))
  8851. (mapcar #'car
  8852. (cl-sort menu-keys #'<
  8853. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8854. (defun org-insert-structure-template (type)
  8855. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8856. Select a block from `org-structure-template-alist' then type
  8857. either RET, TAB or SPC to write the block type. With an active
  8858. region, wrap the region in the block. Otherwise, insert an empty
  8859. block."
  8860. (interactive
  8861. (list (pcase (org--insert-structure-template-mks)
  8862. (`("\t" . ,_) (read-string "Structure type: "))
  8863. (`(,_ ,choice . ,_) choice))))
  8864. (let* ((region? (use-region-p))
  8865. (region-start (and region? (region-beginning)))
  8866. (region-end (and region? (copy-marker (region-end))))
  8867. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8868. (verbatim? (string-match-p
  8869. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8870. type)))
  8871. (when region? (goto-char region-start))
  8872. (let ((column (current-indentation)))
  8873. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8874. (beginning-of-line)
  8875. (insert "\n"))
  8876. (save-excursion
  8877. (indent-to column)
  8878. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8879. (when region?
  8880. (when verbatim? (org-escape-code-in-region (point) region-end))
  8881. (goto-char region-end)
  8882. ;; Ignore empty lines at the end of the region.
  8883. (skip-chars-backward " \r\t\n")
  8884. (end-of-line))
  8885. (unless (bolp) (insert "\n"))
  8886. (indent-to column)
  8887. (insert (format "#+end_%s" (car (split-string type))))
  8888. (if (looking-at "[ \t]*$") (replace-match "")
  8889. (insert "\n"))
  8890. (when (and (eobp) (not (bolp))) (insert "\n")))
  8891. (if extended? (end-of-line)
  8892. (forward-line)
  8893. (skip-chars-forward " \t")))))
  8894. ;;;; TODO, DEADLINE, Comments
  8895. (defun org-toggle-comment ()
  8896. "Change the COMMENT state of an entry."
  8897. (interactive)
  8898. (save-excursion
  8899. (org-back-to-heading)
  8900. (let ((case-fold-search nil))
  8901. (looking-at org-complex-heading-regexp))
  8902. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8903. (skip-chars-forward " \t")
  8904. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8905. (if (org-in-commented-heading-p t)
  8906. (delete-region (point)
  8907. (progn (search-forward " " (line-end-position) 'move)
  8908. (skip-chars-forward " \t")
  8909. (point)))
  8910. (insert org-comment-string)
  8911. (unless (eolp) (insert " ")))))
  8912. (defvar org-last-todo-state-is-todo nil
  8913. "This is non-nil when the last TODO state change led to a TODO state.
  8914. If the last change removed the TODO tag or switched to DONE, then
  8915. this is nil.")
  8916. (defvar org-todo-setup-filter-hook nil
  8917. "Hook for functions that pre-filter todo specs.
  8918. Each function takes a todo spec and returns either nil or the spec
  8919. transformed into canonical form." )
  8920. (defvar org-todo-get-default-hook nil
  8921. "Hook for functions that get a default item for todo.
  8922. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8923. nil or a string to be used for the todo mark." )
  8924. (defvar org-agenda-headline-snapshot-before-repeat)
  8925. (defun org-current-effective-time ()
  8926. "Return current time adjusted for `org-extend-today-until' variable."
  8927. (let* ((ct (org-current-time))
  8928. (dct (decode-time ct))
  8929. (ct1
  8930. (cond
  8931. (org-use-last-clock-out-time-as-effective-time
  8932. (or (org-clock-get-last-clock-out-time) ct))
  8933. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8934. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8935. (t ct))))
  8936. ct1))
  8937. (defun org-todo-yesterday (&optional arg)
  8938. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8939. (interactive "P")
  8940. (if (eq major-mode 'org-agenda-mode)
  8941. (apply 'org-agenda-todo-yesterday arg)
  8942. (let* ((org-use-effective-time t)
  8943. (hour (nth 2 (decode-time (org-current-time))))
  8944. (org-extend-today-until (1+ hour)))
  8945. (org-todo arg))))
  8946. (defvar org-block-entry-blocking ""
  8947. "First entry preventing the TODO state change.")
  8948. (defun org-cancel-repeater ()
  8949. "Cancel a repeater by setting its numeric value to zero."
  8950. (interactive)
  8951. (save-excursion
  8952. (org-back-to-heading t)
  8953. (let ((bound1 (point))
  8954. (bound0 (save-excursion (outline-next-heading) (point))))
  8955. (when (and (re-search-forward
  8956. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8957. org-deadline-time-regexp "\\)\\|\\("
  8958. org-ts-regexp "\\)")
  8959. bound0 t)
  8960. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8961. bound1 t))
  8962. (replace-match "0" t nil nil 1)))))
  8963. (defvar org-state)
  8964. (defvar org-blocked-by-checkboxes)
  8965. (defun org-todo (&optional arg)
  8966. "Change the TODO state of an item.
  8967. The state of an item is given by a keyword at the start of the heading,
  8968. like
  8969. *** TODO Write paper
  8970. *** DONE Call mom
  8971. The different keywords are specified in the variable `org-todo-keywords'.
  8972. By default the available states are \"TODO\" and \"DONE\". So, for this
  8973. example: when the item starts with TODO, it is changed to DONE.
  8974. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8975. DONE are present, add TODO at the beginning of the heading.
  8976. You can set up single-charcter keys to fast-select the new state. See the
  8977. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8978. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8979. and take a
  8980. logging note.
  8981. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8982. next set of TODO \
  8983. keywords (nextset).
  8984. Another way to achieve this is `S-C-<right>'.
  8985. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8986. prefix, circumvent any state blocking.
  8987. With numeric prefix arg, switch to the Nth state.
  8988. With a numeric prefix arg of 0, inhibit note taking for the change.
  8989. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8990. When called through ELisp, arg is also interpreted in the following way:
  8991. `none' -> empty state
  8992. \"\" -> switch to empty state
  8993. `done' -> switch to DONE
  8994. `nextset' -> switch to the next set of keywords
  8995. `previousset' -> switch to the previous set of keywords
  8996. \"WAITING\" -> switch to the specified keyword, but only if it
  8997. really is a member of `org-todo-keywords'."
  8998. (interactive "P")
  8999. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9000. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9001. 'region-start-level 'region))
  9002. org-loop-over-headlines-in-active-region)
  9003. (org-map-entries
  9004. `(org-todo ,arg)
  9005. org-loop-over-headlines-in-active-region
  9006. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  9007. (when (equal arg '(16)) (setq arg 'nextset))
  9008. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  9009. (let ((org-blocker-hook org-blocker-hook)
  9010. commentp
  9011. case-fold-search)
  9012. (when (equal arg '(64))
  9013. (setq arg nil org-blocker-hook nil))
  9014. (when (and org-blocker-hook
  9015. (or org-inhibit-blocking
  9016. (org-entry-get nil "NOBLOCKING")))
  9017. (setq org-blocker-hook nil))
  9018. (save-excursion
  9019. (catch 'exit
  9020. (org-back-to-heading t)
  9021. (when (org-in-commented-heading-p t)
  9022. (org-toggle-comment)
  9023. (setq commentp t))
  9024. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  9025. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  9026. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  9027. (let* ((match-data (match-data))
  9028. (startpos (copy-marker (line-beginning-position)))
  9029. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  9030. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  9031. (org-log-done org-log-done)
  9032. (org-log-repeat org-log-repeat)
  9033. (org-todo-log-states org-todo-log-states)
  9034. (org-inhibit-logging
  9035. (if (equal arg 0)
  9036. (progn (setq arg nil) 'note) org-inhibit-logging))
  9037. (this (match-string 1))
  9038. (hl-pos (match-beginning 0))
  9039. (head (org-get-todo-sequence-head this))
  9040. (ass (assoc head org-todo-kwd-alist))
  9041. (interpret (nth 1 ass))
  9042. (done-word (nth 3 ass))
  9043. (final-done-word (nth 4 ass))
  9044. (org-last-state (or this ""))
  9045. (completion-ignore-case t)
  9046. (member (member this org-todo-keywords-1))
  9047. (tail (cdr member))
  9048. (org-state (cond
  9049. ((eq arg 'right)
  9050. ;; Next state
  9051. (if this
  9052. (if tail (car tail) nil)
  9053. (car org-todo-keywords-1)))
  9054. ((eq arg 'left)
  9055. ;; Previous state
  9056. (unless (equal member org-todo-keywords-1)
  9057. (if this
  9058. (nth (- (length org-todo-keywords-1)
  9059. (length tail) 2)
  9060. org-todo-keywords-1)
  9061. (org-last org-todo-keywords-1))))
  9062. (arg
  9063. ;; User or caller requests a specific state.
  9064. (cond
  9065. ((equal arg "") nil)
  9066. ((eq arg 'none) nil)
  9067. ((eq arg 'done) (or done-word (car org-done-keywords)))
  9068. ((eq arg 'nextset)
  9069. (or (car (cdr (member head org-todo-heads)))
  9070. (car org-todo-heads)))
  9071. ((eq arg 'previousset)
  9072. (let ((org-todo-heads (reverse org-todo-heads)))
  9073. (or (car (cdr (member head org-todo-heads)))
  9074. (car org-todo-heads))))
  9075. ((car (member arg org-todo-keywords-1)))
  9076. ((stringp arg)
  9077. (user-error "State `%s' not valid in this file" arg))
  9078. ((nth (1- (prefix-numeric-value arg))
  9079. org-todo-keywords-1))))
  9080. ((and org-todo-key-trigger org-use-fast-todo-selection)
  9081. ;; Use fast selection.
  9082. (org-fast-todo-selection this))
  9083. ((null member) (or head (car org-todo-keywords-1)))
  9084. ((equal this final-done-word) nil) ;-> make empty
  9085. ((null tail) nil) ;-> first entry
  9086. ((memq interpret '(type priority))
  9087. (if (eq this-command last-command)
  9088. (car tail)
  9089. (if (> (length tail) 0)
  9090. (or done-word (car org-done-keywords))
  9091. nil)))
  9092. (t
  9093. (car tail))))
  9094. (org-state (or
  9095. (run-hook-with-args-until-success
  9096. 'org-todo-get-default-hook org-state org-last-state)
  9097. org-state))
  9098. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  9099. (change-plist (list :type 'todo-state-change :from this :to org-state
  9100. :position startpos))
  9101. dolog now-done-p)
  9102. (when org-blocker-hook
  9103. (let (org-blocked-by-checkboxes block-reason)
  9104. (setq org-last-todo-state-is-todo
  9105. (not (member this org-done-keywords)))
  9106. (unless (save-excursion
  9107. (save-match-data
  9108. (org-with-wide-buffer
  9109. (run-hook-with-args-until-failure
  9110. 'org-blocker-hook change-plist))))
  9111. (setq block-reason (if org-blocked-by-checkboxes
  9112. "contained checkboxes"
  9113. (format "\"%s\"" org-block-entry-blocking)))
  9114. (if (called-interactively-p 'interactive)
  9115. (user-error "TODO state change from %s to %s blocked (by %s)"
  9116. this org-state block-reason)
  9117. ;; Fail silently.
  9118. (message "TODO state change from %s to %s blocked (by %s)"
  9119. this org-state block-reason)
  9120. (throw 'exit nil)))))
  9121. (store-match-data match-data)
  9122. (replace-match next t t)
  9123. (cond ((equal this org-state)
  9124. (message "TODO state was already %s" (org-trim next)))
  9125. ((not (pos-visible-in-window-p hl-pos))
  9126. (message "TODO state changed to %s" (org-trim next))))
  9127. (unless head
  9128. (setq head (org-get-todo-sequence-head org-state)
  9129. ass (assoc head org-todo-kwd-alist)
  9130. interpret (nth 1 ass)
  9131. done-word (nth 3 ass)
  9132. final-done-word (nth 4 ass)))
  9133. (when (memq arg '(nextset previousset))
  9134. (message "Keyword-Set %d/%d: %s"
  9135. (- (length org-todo-sets) -1
  9136. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  9137. (length org-todo-sets)
  9138. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  9139. (setq org-last-todo-state-is-todo
  9140. (not (member org-state org-done-keywords)))
  9141. (setq now-done-p (and (member org-state org-done-keywords)
  9142. (not (member this org-done-keywords))))
  9143. (and logging (org-local-logging logging))
  9144. (when (or (and (or org-todo-log-states org-log-done)
  9145. (not (eq org-inhibit-logging t))
  9146. (not (memq arg '(nextset previousset))))
  9147. force-log)
  9148. ;; We need to look at recording a time and note.
  9149. (setq dolog (or (if force-log 'note)
  9150. (nth 1 (assoc org-state org-todo-log-states))
  9151. (nth 2 (assoc this org-todo-log-states))))
  9152. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  9153. (setq dolog 'time))
  9154. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  9155. (and org-state
  9156. (member org-state org-not-done-keywords)
  9157. (not (member this org-not-done-keywords))))
  9158. ;; This is now a todo state and was not one before
  9159. ;; If there was a CLOSED time stamp, get rid of it.
  9160. (org-add-planning-info nil nil 'closed))
  9161. (when (and now-done-p org-log-done)
  9162. ;; It is now done, and it was not done before.
  9163. (org-add-planning-info 'closed (org-current-effective-time))
  9164. (when (and (not dolog) (eq 'note org-log-done))
  9165. (org-add-log-setup 'done org-state this 'note)))
  9166. (when (and org-state dolog)
  9167. ;; This is a non-nil state, and we need to log it.
  9168. (org-add-log-setup 'state org-state this dolog)))
  9169. ;; Fixup tag positioning.
  9170. (org-todo-trigger-tag-changes org-state)
  9171. (when org-auto-align-tags (org-align-tags))
  9172. (when org-provide-todo-statistics
  9173. (org-update-parent-todo-statistics))
  9174. (when (bound-and-true-p org-clock-out-when-done)
  9175. (org-clock-out-if-current))
  9176. (run-hooks 'org-after-todo-state-change-hook)
  9177. (when (and arg (not (member org-state org-done-keywords)))
  9178. (setq head (org-get-todo-sequence-head org-state)))
  9179. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  9180. ;; Do we need to trigger a repeat?
  9181. (when now-done-p
  9182. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  9183. ;; This is for the agenda, take a snapshot of the headline.
  9184. (save-match-data
  9185. (setq org-agenda-headline-snapshot-before-repeat
  9186. (org-get-heading))))
  9187. (org-auto-repeat-maybe org-state))
  9188. ;; Fixup cursor location if close to the keyword.
  9189. (when (and (outline-on-heading-p)
  9190. (not (bolp))
  9191. (save-excursion (beginning-of-line 1)
  9192. (looking-at org-todo-line-regexp))
  9193. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  9194. (goto-char (or (match-end 2) (match-end 1)))
  9195. (and (looking-at " ")
  9196. (not (looking-at " *:"))
  9197. (just-one-space)))
  9198. (when org-trigger-hook
  9199. (save-excursion
  9200. (run-hook-with-args 'org-trigger-hook change-plist)))
  9201. (when commentp (org-toggle-comment))))))))
  9202. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  9203. "Block turning an entry into a TODO, using the hierarchy.
  9204. This checks whether the current task should be blocked from state
  9205. changes. Such blocking occurs when:
  9206. 1. The task has children which are not all in a completed state.
  9207. 2. A task has a parent with the property :ORDERED:, and there
  9208. are siblings prior to the current task with incomplete
  9209. status.
  9210. 3. The parent of the task is blocked because it has siblings that should
  9211. be done first, or is child of a block grandparent TODO entry."
  9212. (if (not org-enforce-todo-dependencies)
  9213. t ; if locally turned off don't block
  9214. (catch 'dont-block
  9215. ;; If this is not a todo state change, or if this entry is already DONE,
  9216. ;; do not block
  9217. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9218. (member (plist-get change-plist :from)
  9219. (cons 'done org-done-keywords))
  9220. (member (plist-get change-plist :to)
  9221. (cons 'todo org-not-done-keywords))
  9222. (not (plist-get change-plist :to)))
  9223. (throw 'dont-block t))
  9224. ;; If this task has children, and any are undone, it's blocked
  9225. (save-excursion
  9226. (org-back-to-heading t)
  9227. (let ((this-level (funcall outline-level)))
  9228. (outline-next-heading)
  9229. (let ((child-level (funcall outline-level)))
  9230. (while (and (not (eobp))
  9231. (> child-level this-level))
  9232. ;; this todo has children, check whether they are all
  9233. ;; completed
  9234. (when (and (not (org-entry-is-done-p))
  9235. (org-entry-is-todo-p))
  9236. (setq org-block-entry-blocking (org-get-heading))
  9237. (throw 'dont-block nil))
  9238. (outline-next-heading)
  9239. (setq child-level (funcall outline-level))))))
  9240. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  9241. ;; any previous siblings are undone, it's blocked
  9242. (save-excursion
  9243. (org-back-to-heading t)
  9244. (let* ((pos (point))
  9245. (parent-pos (and (org-up-heading-safe) (point)))
  9246. (case-fold-search nil))
  9247. (unless parent-pos (throw 'dont-block t)) ; no parent
  9248. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9249. (forward-line 1)
  9250. (re-search-forward org-not-done-heading-regexp pos t))
  9251. (setq org-block-entry-blocking (match-string 0))
  9252. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  9253. ;; Search further up the hierarchy, to see if an ancestor is blocked
  9254. (while t
  9255. (goto-char parent-pos)
  9256. (unless (looking-at org-not-done-heading-regexp)
  9257. (throw 'dont-block t)) ; do not block, parent is not a TODO
  9258. (setq pos (point))
  9259. (setq parent-pos (and (org-up-heading-safe) (point)))
  9260. (unless parent-pos (throw 'dont-block t)) ; no parent
  9261. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9262. (forward-line 1)
  9263. (re-search-forward org-not-done-heading-regexp pos t)
  9264. (setq org-block-entry-blocking (org-get-heading)))
  9265. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  9266. (defcustom org-track-ordered-property-with-tag nil
  9267. "Should the ORDERED property also be shown as a tag?
  9268. The ORDERED property decides if an entry should require subtasks to be
  9269. completed in sequence. Since a property is not very visible, setting
  9270. this option means that toggling the ORDERED property with the command
  9271. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  9272. not relevant for the behavior, but it makes things more visible.
  9273. Note that toggling the tag with tags commands will not change the property
  9274. and therefore not influence behavior!
  9275. This can be t, meaning the tag ORDERED should be used, It can also be a
  9276. string to select a different tag for this task."
  9277. :group 'org-todo
  9278. :type '(choice
  9279. (const :tag "No tracking" nil)
  9280. (const :tag "Track with ORDERED tag" t)
  9281. (string :tag "Use other tag")))
  9282. (defun org-toggle-ordered-property ()
  9283. "Toggle the ORDERED property of the current entry.
  9284. For better visibility, you can track the value of this property with a tag.
  9285. See variable `org-track-ordered-property-with-tag'."
  9286. (interactive)
  9287. (let* ((t1 org-track-ordered-property-with-tag)
  9288. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  9289. (save-excursion
  9290. (org-back-to-heading)
  9291. (if (org-entry-get nil "ORDERED")
  9292. (progn
  9293. (org-delete-property "ORDERED")
  9294. (and tag (org-toggle-tag tag 'off))
  9295. (message "Subtasks can be completed in arbitrary order"))
  9296. (org-entry-put nil "ORDERED" "t")
  9297. (and tag (org-toggle-tag tag 'on))
  9298. (message "Subtasks must be completed in sequence")))))
  9299. (defun org-block-todo-from-checkboxes (change-plist)
  9300. "Block turning an entry into a TODO, using checkboxes.
  9301. This checks whether the current task should be blocked from state
  9302. changes because there are unchecked boxes in this entry."
  9303. (if (not org-enforce-todo-checkbox-dependencies)
  9304. t ; if locally turned off don't block
  9305. (catch 'dont-block
  9306. ;; If this is not a todo state change, or if this entry is already DONE,
  9307. ;; do not block
  9308. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9309. (member (plist-get change-plist :from)
  9310. (cons 'done org-done-keywords))
  9311. (member (plist-get change-plist :to)
  9312. (cons 'todo org-not-done-keywords))
  9313. (not (plist-get change-plist :to)))
  9314. (throw 'dont-block t))
  9315. ;; If this task has checkboxes that are not checked, it's blocked
  9316. (save-excursion
  9317. (org-back-to-heading t)
  9318. (let ((beg (point)) end)
  9319. (outline-next-heading)
  9320. (setq end (point))
  9321. (goto-char beg)
  9322. (when (org-list-search-forward
  9323. (concat (org-item-beginning-re)
  9324. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  9325. "\\[[- ]\\]")
  9326. end t)
  9327. (when (boundp 'org-blocked-by-checkboxes)
  9328. (setq org-blocked-by-checkboxes t))
  9329. (throw 'dont-block nil))))
  9330. t))) ; do not block
  9331. (defun org-entry-blocked-p ()
  9332. "Non-nil if entry at point is blocked."
  9333. (and (not (org-entry-get nil "NOBLOCKING"))
  9334. (member (org-entry-get nil "TODO") org-not-done-keywords)
  9335. (not (run-hook-with-args-until-failure
  9336. 'org-blocker-hook
  9337. (list :type 'todo-state-change
  9338. :position (point)
  9339. :from 'todo
  9340. :to 'done)))))
  9341. (defun org-update-statistics-cookies (all)
  9342. "Update the statistics cookie, either from TODO or from checkboxes.
  9343. This should be called with the cursor in a line with a statistics
  9344. cookie. When called with a \\[universal-argument] prefix, update
  9345. all statistics cookies in the buffer."
  9346. (interactive "P")
  9347. (if all
  9348. (progn
  9349. (org-update-checkbox-count 'all)
  9350. (org-map-entries 'org-update-parent-todo-statistics))
  9351. (if (not (org-at-heading-p))
  9352. (org-update-checkbox-count)
  9353. (let ((pos (point-marker))
  9354. end l1 l2)
  9355. (ignore-errors (org-back-to-heading t))
  9356. (if (not (org-at-heading-p))
  9357. (org-update-checkbox-count)
  9358. (setq l1 (org-outline-level))
  9359. (setq end (save-excursion
  9360. (outline-next-heading)
  9361. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  9362. (point)))
  9363. (if (and (save-excursion
  9364. (re-search-forward
  9365. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  9366. (not (save-excursion (re-search-forward
  9367. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  9368. (org-update-checkbox-count)
  9369. (if (and l2 (> l2 l1))
  9370. (progn
  9371. (goto-char end)
  9372. (org-update-parent-todo-statistics))
  9373. (goto-char pos)
  9374. (beginning-of-line 1)
  9375. (while (re-search-forward
  9376. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  9377. (point-at-eol) t)
  9378. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  9379. (goto-char pos)
  9380. (move-marker pos nil)))))
  9381. (defvar org-entry-property-inherited-from) ;; defined below
  9382. (defun org-update-parent-todo-statistics ()
  9383. "Update any statistics cookie in the parent of the current headline.
  9384. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  9385. the entire subtree and this will travel up the hierarchy and update
  9386. statistics everywhere."
  9387. (let* ((prop (save-excursion (org-up-heading-safe)
  9388. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  9389. (recursive (or (not org-hierarchical-todo-statistics)
  9390. (and prop (string-match "\\<recursive\\>" prop))))
  9391. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  9392. 0))
  9393. (first t)
  9394. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  9395. level ltoggle l1 new ndel
  9396. (cnt-all 0) (cnt-done 0) is-percent kwd
  9397. checkbox-beg cookie-present)
  9398. (catch 'exit
  9399. (save-excursion
  9400. (beginning-of-line 1)
  9401. (setq ltoggle (funcall outline-level))
  9402. ;; Three situations are to consider:
  9403. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  9404. ;; to the top-level ancestor on the headline;
  9405. ;; 2. If parent has "recursive" property, repeat up to the
  9406. ;; headline setting that property, taking inheritance into
  9407. ;; account;
  9408. ;; 3. Else, move up to direct parent and proceed only once.
  9409. (while (and (setq level (org-up-heading-safe))
  9410. (or recursive first)
  9411. (>= (point) lim))
  9412. (setq first nil cookie-present nil)
  9413. (unless (and level
  9414. (not (string-match
  9415. "\\<checkbox\\>"
  9416. (downcase (or (org-entry-get nil "COOKIE_DATA")
  9417. "")))))
  9418. (throw 'exit nil))
  9419. (while (re-search-forward box-re (point-at-eol) t)
  9420. (setq cnt-all 0 cnt-done 0 cookie-present t)
  9421. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  9422. (save-match-data
  9423. (unless (outline-next-heading) (throw 'exit nil))
  9424. (while (and (looking-at org-complex-heading-regexp)
  9425. (> (setq l1 (length (match-string 1))) level))
  9426. (setq kwd (and (or recursive (= l1 ltoggle))
  9427. (match-string 2)))
  9428. (if (or (eq org-provide-todo-statistics 'all-headlines)
  9429. (and (eq org-provide-todo-statistics t)
  9430. (or (member kwd org-done-keywords)))
  9431. (and (listp org-provide-todo-statistics)
  9432. (stringp (car org-provide-todo-statistics))
  9433. (or (member kwd org-provide-todo-statistics)
  9434. (member kwd org-done-keywords)))
  9435. (and (listp org-provide-todo-statistics)
  9436. (listp (car org-provide-todo-statistics))
  9437. (or (member kwd (car org-provide-todo-statistics))
  9438. (and (member kwd org-done-keywords)
  9439. (member kwd (cadr org-provide-todo-statistics))))))
  9440. (setq cnt-all (1+ cnt-all))
  9441. (and (eq org-provide-todo-statistics t)
  9442. kwd
  9443. (setq cnt-all (1+ cnt-all))))
  9444. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  9445. (member kwd org-done-keywords))
  9446. (and (listp org-provide-todo-statistics)
  9447. (listp (car org-provide-todo-statistics))
  9448. (member kwd org-done-keywords)
  9449. (member kwd (cadr org-provide-todo-statistics)))
  9450. (and (listp org-provide-todo-statistics)
  9451. (stringp (car org-provide-todo-statistics))
  9452. (member kwd org-done-keywords)))
  9453. (setq cnt-done (1+ cnt-done)))
  9454. (outline-next-heading)))
  9455. (setq new
  9456. (if is-percent
  9457. (format "[%d%%]" (floor (* 100.0 cnt-done)
  9458. (max 1 cnt-all)))
  9459. (format "[%d/%d]" cnt-done cnt-all))
  9460. ndel (- (match-end 0) checkbox-beg))
  9461. (goto-char checkbox-beg)
  9462. (insert new)
  9463. (delete-region (point) (+ (point) ndel))
  9464. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  9465. (when cookie-present
  9466. (run-hook-with-args 'org-after-todo-statistics-hook
  9467. cnt-done (- cnt-all cnt-done))))))
  9468. (run-hooks 'org-todo-statistics-hook)))
  9469. (defvar org-after-todo-statistics-hook nil
  9470. "Hook that is called after a TODO statistics cookie has been updated.
  9471. Each function is called with two arguments: the number of not-done entries
  9472. and the number of done entries.
  9473. For example, the following function, when added to this hook, will switch
  9474. an entry to DONE when all children are done, and back to TODO when new
  9475. entries are set to a TODO status. Note that this hook is only called
  9476. when there is a statistics cookie in the headline!
  9477. (defun org-summary-todo (n-done n-not-done)
  9478. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9479. (let (org-log-done org-log-states) ; turn off logging
  9480. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  9481. ")
  9482. (defvar org-todo-statistics-hook nil
  9483. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9484. This hook runs even if there is no statistics cookie present, in which case
  9485. `org-after-todo-statistics-hook' would not run.")
  9486. (defun org-todo-trigger-tag-changes (state)
  9487. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9488. (let ((l org-todo-state-tags-triggers)
  9489. changes)
  9490. (when (or (not state) (equal state ""))
  9491. (setq changes (append changes (cdr (assoc "" l)))))
  9492. (when (and (stringp state) (> (length state) 0))
  9493. (setq changes (append changes (cdr (assoc state l)))))
  9494. (when (member state org-not-done-keywords)
  9495. (setq changes (append changes (cdr (assq 'todo l)))))
  9496. (when (member state org-done-keywords)
  9497. (setq changes (append changes (cdr (assq 'done l)))))
  9498. (dolist (c changes)
  9499. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9500. (defun org-local-logging (value)
  9501. "Get logging settings from a property VALUE."
  9502. ;; Directly set the variables, they are already local.
  9503. (setq org-log-done nil
  9504. org-log-repeat nil
  9505. org-todo-log-states nil)
  9506. (dolist (w (split-string value))
  9507. (let (a)
  9508. (cond
  9509. ((setq a (assoc w org-startup-options))
  9510. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9511. (set (nth 1 a) (nth 2 a))))
  9512. ((setq a (org-extract-log-state-settings w))
  9513. (and (member (car a) org-todo-keywords-1)
  9514. (push a org-todo-log-states)))))))
  9515. (defun org-get-todo-sequence-head (kwd)
  9516. "Return the head of the TODO sequence to which KWD belongs.
  9517. If KWD is not set, check if there is a text property remembering the
  9518. right sequence."
  9519. (let (p)
  9520. (cond
  9521. ((not kwd)
  9522. (or (get-text-property (point-at-bol) 'org-todo-head)
  9523. (progn
  9524. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9525. nil (point-at-eol)))
  9526. (get-text-property p 'org-todo-head))))
  9527. ((not (member kwd org-todo-keywords-1))
  9528. (car org-todo-keywords-1))
  9529. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9530. (defun org-fast-todo-selection (&optional current-state)
  9531. "Fast TODO keyword selection with single keys.
  9532. Returns the new TODO keyword, or nil if no state change should occur.
  9533. When CURRENT-STATE is given and selection letters are not unique globally,
  9534. prefer a state in the current sequence over on in another sequence."
  9535. (let* ((fulltable org-todo-key-alist)
  9536. (head (org-get-todo-sequence-head current-state))
  9537. (done-keywords org-done-keywords) ;; needed for the faces.
  9538. (maxlen (apply 'max (mapcar
  9539. (lambda (x)
  9540. (if (stringp (car x)) (string-width (car x)) 0))
  9541. fulltable)))
  9542. (expert (equal org-use-fast-todo-selection 'expert))
  9543. (prompt "")
  9544. (fwidth (+ maxlen 3 1 3))
  9545. (ncol (/ (- (window-width) 4) fwidth))
  9546. tg cnt e c tbl subtable
  9547. groups ingroup in-current-sequence)
  9548. (save-excursion
  9549. (save-window-excursion
  9550. (if expert
  9551. (set-buffer (get-buffer-create " *Org todo*"))
  9552. (delete-other-windows)
  9553. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9554. (org-switch-to-buffer-other-window " *Org todo*"))
  9555. (erase-buffer)
  9556. (setq-local org-done-keywords done-keywords)
  9557. (setq tbl fulltable cnt 0)
  9558. (while (setq e (pop tbl))
  9559. (cond
  9560. ((equal e '(:startgroup))
  9561. (push '() groups) (setq ingroup t)
  9562. (unless (= cnt 0)
  9563. (setq cnt 0)
  9564. (insert "\n"))
  9565. (setq prompt (concat prompt "{"))
  9566. (insert "{ "))
  9567. ((equal e '(:endgroup))
  9568. (setq ingroup nil cnt 0 in-current-sequence nil)
  9569. (setq prompt (concat prompt "}"))
  9570. (insert "}\n"))
  9571. ((equal e '(:newline))
  9572. (unless (= cnt 0)
  9573. (setq cnt 0)
  9574. (insert "\n")
  9575. (setq e (car tbl))
  9576. (while (equal (car tbl) '(:newline))
  9577. (insert "\n")
  9578. (setq tbl (cdr tbl)))))
  9579. (t
  9580. (setq tg (car e) c (cdr e))
  9581. (if (equal tg head) (setq in-current-sequence t))
  9582. (when ingroup (push tg (car groups)))
  9583. (when in-current-sequence (push e subtable))
  9584. (setq tg (org-add-props tg nil 'face
  9585. (org-get-todo-face tg)))
  9586. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9587. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9588. (insert "[" c "] " tg (make-string
  9589. (- fwidth 4 (length tg)) ?\ ))
  9590. (when (and (= (setq cnt (1+ cnt)) ncol)
  9591. ;; Avoid lines with just a closing delimiter.
  9592. (not (equal (car tbl) '(:endgroup))))
  9593. (insert "\n")
  9594. (when ingroup (insert " "))
  9595. (setq cnt 0)))))
  9596. (insert "\n")
  9597. (goto-char (point-min))
  9598. (unless expert (org-fit-window-to-buffer))
  9599. (message (concat "[a-z..]:Set [SPC]:clear"
  9600. (if expert (concat "\n" prompt) "")))
  9601. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9602. (setq subtable (nreverse subtable))
  9603. (cond
  9604. ((or (= c ?\C-g)
  9605. (and (= c ?q) (not (rassoc c fulltable))))
  9606. (setq quit-flag t))
  9607. ((= c ?\ ) nil)
  9608. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9609. tg (car e))
  9610. tg)
  9611. (t (setq quit-flag t)))))))
  9612. (defun org-entry-is-todo-p ()
  9613. (member (org-get-todo-state) org-not-done-keywords))
  9614. (defun org-entry-is-done-p ()
  9615. (member (org-get-todo-state) org-done-keywords))
  9616. (defun org-get-todo-state ()
  9617. "Return the TODO keyword of the current subtree."
  9618. (save-excursion
  9619. (org-back-to-heading t)
  9620. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9621. (match-end 2)
  9622. (match-string 2))))
  9623. (defun org-at-date-range-p (&optional inactive-ok)
  9624. "Non-nil if point is inside a date range.
  9625. When optional argument INACTIVE-OK is non-nil, also consider
  9626. inactive time ranges.
  9627. When this function returns a non-nil value, match data is set
  9628. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9629. on INACTIVE-OK."
  9630. (interactive)
  9631. (save-excursion
  9632. (catch 'exit
  9633. (let ((pos (point)))
  9634. (skip-chars-backward "^[<\r\n")
  9635. (skip-chars-backward "<[")
  9636. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9637. (>= (match-end 0) pos)
  9638. (throw 'exit t))
  9639. (skip-chars-backward "^<[\r\n")
  9640. (skip-chars-backward "<[")
  9641. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9642. (>= (match-end 0) pos)
  9643. (throw 'exit t)))
  9644. nil)))
  9645. (defun org-get-repeat (&optional timestamp)
  9646. "Check if there is a time-stamp with repeater in this entry.
  9647. Return the repeater, as a string, or nil. Also return nil when
  9648. this function is called before first heading.
  9649. When optional argument TIMESTAMP is a string, extract the
  9650. repeater from there instead."
  9651. (save-match-data
  9652. (cond (timestamp
  9653. (and (string-match org-repeat-re timestamp)
  9654. (match-string-no-properties 1 timestamp)))
  9655. ((org-before-first-heading-p) nil)
  9656. (t
  9657. (save-excursion
  9658. (org-back-to-heading t)
  9659. (let ((end (org-entry-end-position)))
  9660. (catch :repeat
  9661. (while (re-search-forward org-repeat-re end t)
  9662. (when (save-match-data (org-at-timestamp-p 'agenda))
  9663. (throw :repeat (match-string-no-properties 1)))))))))))
  9664. (defvar org-last-changed-timestamp)
  9665. (defvar org-last-inserted-timestamp)
  9666. (defvar org-log-post-message)
  9667. (defvar org-log-note-purpose)
  9668. (defvar org-log-note-how nil)
  9669. (defvar org-log-note-extra)
  9670. (defun org-auto-repeat-maybe (done-word)
  9671. "Check if the current headline contains a repeated time-stamp.
  9672. If yes, set TODO state back to what it was and change the base date
  9673. of repeating deadline/scheduled time stamps to new date.
  9674. This function is run automatically after each state change to a DONE state."
  9675. (let* ((repeat (org-get-repeat))
  9676. (aa (assoc org-last-state org-todo-kwd-alist))
  9677. (interpret (nth 1 aa))
  9678. (head (nth 2 aa))
  9679. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9680. (msg "Entry repeats: ")
  9681. (org-log-done nil)
  9682. (org-todo-log-states nil)
  9683. (end (copy-marker (org-entry-end-position))))
  9684. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9685. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9686. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9687. (and (stringp org-todo-repeat-to-state)
  9688. org-todo-repeat-to-state)
  9689. (and org-todo-repeat-to-state org-last-state))))
  9690. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9691. to-state)
  9692. ((eq interpret 'type) org-last-state)
  9693. (head)
  9694. (t 'none))))
  9695. (org-back-to-heading t)
  9696. (org-add-planning-info nil nil 'closed)
  9697. ;; When `org-log-repeat' is non-nil or entry contains
  9698. ;; a clock, set LAST_REPEAT property.
  9699. (when (or org-log-repeat
  9700. (catch :clock
  9701. (save-excursion
  9702. (while (re-search-forward org-clock-line-re end t)
  9703. (when (org-at-clock-log-p) (throw :clock t))))))
  9704. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9705. (org-time-stamp-format t t))))
  9706. (when org-log-repeat
  9707. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  9708. (memq 'org-add-log-note post-command-hook))
  9709. ;; We are already setup for some record.
  9710. (when (eq org-log-repeat 'note)
  9711. ;; Make sure we take a note, not only a time stamp.
  9712. (setq org-log-note-how 'note))
  9713. ;; Set up for taking a record.
  9714. (org-add-log-setup 'state
  9715. (or done-word (car org-done-keywords))
  9716. org-last-state
  9717. org-log-repeat)))
  9718. ;; Time-stamps without a repeater are usually skipped. However,
  9719. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9720. ;; longer relevant.
  9721. (save-excursion
  9722. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9723. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9724. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9725. ;; Update every time-stamp with a repeater in the entry.
  9726. (let ((planning-re (regexp-opt
  9727. (list org-scheduled-string org-deadline-string))))
  9728. (while (re-search-forward org-repeat-re end t)
  9729. (let* ((ts (match-string 0))
  9730. (type (if (not (org-at-planning-p)) "Plain:"
  9731. (save-excursion
  9732. (re-search-backward
  9733. planning-re (line-beginning-position) t)
  9734. (match-string 0)))))
  9735. (when (and (org-at-timestamp-p 'agenda)
  9736. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9737. (let ((n (string-to-number (match-string 2 ts)))
  9738. (what (match-string 3 ts)))
  9739. (when (equal what "w") (setq n (* n 7) what "d"))
  9740. (when (and (equal what "h")
  9741. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9742. ts)))
  9743. (user-error
  9744. "Cannot repeat in %d hour(s) because no hour has been set"
  9745. n))
  9746. ;; Preparation, see if we need to modify the start
  9747. ;; date for the change.
  9748. (when (match-end 1)
  9749. (let ((time (save-match-data (org-time-string-to-time ts)))
  9750. (repeater-type (match-string 1 ts)))
  9751. (cond
  9752. ((equal "." repeater-type)
  9753. ;; Shift starting date to today.
  9754. (org-timestamp-change (- (org-today) (time-to-days time))
  9755. 'day))
  9756. ((equal "+" repeater-type)
  9757. (let ((nshiftmax 10)
  9758. (nshift 0))
  9759. (while (or (= nshift 0)
  9760. (not (time-less-p (current-time) time)))
  9761. (when (= nshiftmax (cl-incf nshift))
  9762. (or (y-or-n-p
  9763. (format "%d repeater intervals were not \
  9764. enough to shift date past today. Continue? "
  9765. nshift))
  9766. (user-error "Abort")))
  9767. (org-timestamp-change n (cdr (assoc what whata)))
  9768. (org-in-regexp org-ts-regexp3)
  9769. (setq ts (match-string 1))
  9770. (setq time
  9771. (save-match-data
  9772. (org-time-string-to-time ts)))))
  9773. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9774. ;; Rematch, so that we have everything in place
  9775. ;; for the real shift.
  9776. (org-in-regexp org-ts-regexp3)
  9777. (setq ts (match-string 1))
  9778. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9779. ts)))))
  9780. (save-excursion
  9781. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9782. (setq msg
  9783. (concat msg type " " org-last-changed-timestamp " ")))))))
  9784. (run-hooks 'org-todo-repeat-hook)
  9785. (setq org-log-post-message msg)
  9786. (message msg))))
  9787. (defun org-show-todo-tree (arg)
  9788. "Make a compact tree which shows all headlines marked with TODO.
  9789. The tree will show the lines where the regexp matches, and all higher
  9790. headlines above the match.
  9791. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9792. With a numeric prefix N, construct a sparse tree for the Nth element
  9793. of `org-todo-keywords-1'."
  9794. (interactive "P")
  9795. (let ((case-fold-search nil)
  9796. (kwd-re
  9797. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9798. ((equal arg '(4))
  9799. (let ((kwd
  9800. (completing-read "Keyword (or KWD1|KWD2|...): "
  9801. (mapcar #'list org-todo-keywords-1))))
  9802. (concat "\\("
  9803. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9804. "\\)\\>")))
  9805. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9806. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9807. org-todo-keywords-1)))
  9808. (t (user-error "Invalid prefix argument: %s" arg)))))
  9809. (message "%d TODO entries found"
  9810. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9811. (defun org--deadline-or-schedule (arg type time)
  9812. "Insert DEADLINE or SCHEDULE information in current entry.
  9813. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9814. `org-schedule' for information about ARG and TIME arguments."
  9815. (let* ((deadline? (eq type 'deadline))
  9816. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9817. (log (if deadline? org-log-redeadline org-log-reschedule))
  9818. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9819. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9820. ;; Save repeater cookie from either TIME or current scheduled
  9821. ;; time stamp. We are going to insert it back at the end of
  9822. ;; the process.
  9823. (repeater (or (and (org-string-nw-p time)
  9824. ;; We use `org-repeat-re' because we need
  9825. ;; to tell the difference between a real
  9826. ;; repeater and a time delta, e.g. "+2d".
  9827. (string-match org-repeat-re time)
  9828. (match-string 1 time))
  9829. (and (org-string-nw-p old-date)
  9830. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9831. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9832. old-date)
  9833. (match-string 1 old-date)))))
  9834. (pcase arg
  9835. (`(4)
  9836. (if (not old-date)
  9837. (message (if deadline? "Entry had no deadline to remove"
  9838. "Entry was not scheduled"))
  9839. (when (and old-date log)
  9840. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9841. nil old-date log))
  9842. (org-remove-timestamp-with-keyword keyword)
  9843. (message (if deadline? "Entry no longer has a deadline."
  9844. "Entry is no longer scheduled."))))
  9845. (`(16)
  9846. (save-excursion
  9847. (org-back-to-heading t)
  9848. (let ((regexp (if deadline? org-deadline-time-regexp
  9849. org-scheduled-time-regexp)))
  9850. (if (not (re-search-forward regexp (line-end-position 2) t))
  9851. (user-error (if deadline? "No deadline information to update"
  9852. "No scheduled information to update"))
  9853. (let* ((rpl0 (match-string 1))
  9854. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9855. (msg (if deadline? "Warn starting from" "Delay until")))
  9856. (replace-match
  9857. (concat keyword
  9858. " <" rpl
  9859. (format " -%dd"
  9860. (abs (- (time-to-days
  9861. (save-match-data
  9862. (org-read-date
  9863. nil t nil msg old-date-time)))
  9864. (time-to-days old-date-time))))
  9865. ">") t t))))))
  9866. (_
  9867. (org-add-planning-info type time 'closed)
  9868. (when (and old-date
  9869. log
  9870. (not (equal old-date org-last-inserted-timestamp)))
  9871. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9872. org-last-inserted-timestamp
  9873. old-date
  9874. log))
  9875. (when repeater
  9876. (save-excursion
  9877. (org-back-to-heading t)
  9878. (when (re-search-forward
  9879. (concat keyword " " org-last-inserted-timestamp)
  9880. (line-end-position 2)
  9881. t)
  9882. (goto-char (1- (match-end 0)))
  9883. (insert " " repeater)
  9884. (setq org-last-inserted-timestamp
  9885. (concat (substring org-last-inserted-timestamp 0 -1)
  9886. " " repeater
  9887. (substring org-last-inserted-timestamp -1))))))
  9888. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9889. org-last-inserted-timestamp)))))
  9890. (defun org-deadline (arg &optional time)
  9891. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  9892. With one universal prefix argument, remove any deadline from the item.
  9893. With two universal prefix arguments, prompt for a warning delay.
  9894. With argument TIME, set the deadline at the corresponding date. TIME
  9895. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9896. (interactive "P")
  9897. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9898. (org-map-entries
  9899. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9900. nil
  9901. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9902. 'region-start-level
  9903. 'region)
  9904. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9905. (org--deadline-or-schedule arg 'deadline time)))
  9906. (defun org-schedule (arg &optional time)
  9907. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  9908. With one universal prefix argument, remove any scheduling date from the item.
  9909. With two universal prefix arguments, prompt for a delay cookie.
  9910. With argument TIME, scheduled at the corresponding date. TIME can
  9911. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9912. (interactive "P")
  9913. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9914. (org-map-entries
  9915. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9916. nil
  9917. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9918. 'region-start-level
  9919. 'region)
  9920. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9921. (org--deadline-or-schedule arg 'scheduled time)))
  9922. (defun org-get-scheduled-time (pom &optional inherit)
  9923. "Get the scheduled time as a time tuple, of a format suitable
  9924. for calling org-schedule with, or if there is no scheduling,
  9925. returns nil."
  9926. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9927. (when time
  9928. (apply 'encode-time (org-parse-time-string time)))))
  9929. (defun org-get-deadline-time (pom &optional inherit)
  9930. "Get the deadline as a time tuple, of a format suitable for
  9931. calling org-deadline with, or if there is no scheduling, returns
  9932. nil."
  9933. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9934. (when time
  9935. (apply 'encode-time (org-parse-time-string time)))))
  9936. (defun org-remove-timestamp-with-keyword (keyword)
  9937. "Remove all time stamps with KEYWORD in the current entry."
  9938. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9939. beg)
  9940. (save-excursion
  9941. (org-back-to-heading t)
  9942. (setq beg (point))
  9943. (outline-next-heading)
  9944. (while (re-search-backward re beg t)
  9945. (replace-match "")
  9946. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9947. (equal (char-before) ?\ ))
  9948. (backward-delete-char 1)
  9949. (when (string-match "^[ \t]*$" (buffer-substring
  9950. (point-at-bol) (point-at-eol)))
  9951. (delete-region (point-at-bol)
  9952. (min (point-max) (1+ (point-at-eol))))))))))
  9953. (defvar org-time-was-given) ; dynamically scoped parameter
  9954. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9955. (defun org-at-planning-p ()
  9956. "Non-nil when point is on a planning info line."
  9957. ;; This is as accurate and faster than `org-element-at-point' since
  9958. ;; planning info location is fixed in the section.
  9959. (org-with-wide-buffer
  9960. (beginning-of-line)
  9961. (and (looking-at-p org-planning-line-re)
  9962. (eq (point)
  9963. (ignore-errors
  9964. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9965. (org-back-to-heading t)
  9966. (org-with-limited-levels (org-back-to-heading t)))
  9967. (line-beginning-position 2))))))
  9968. (defun org-add-planning-info (what &optional time &rest remove)
  9969. "Insert new timestamp with keyword in the planning line.
  9970. WHAT indicates what kind of time stamp to add. It is a symbol
  9971. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9972. the time to use. If none is given, the user is prompted for
  9973. a date. REMOVE indicates what kind of entries to remove. An old
  9974. WHAT entry will also be removed."
  9975. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9976. (catch 'exit
  9977. (when (and (memq what '(scheduled deadline))
  9978. (or (not time)
  9979. (and (stringp time)
  9980. (string-match "^[-+]+[0-9]" time))))
  9981. ;; Try to get a default date/time from existing timestamp
  9982. (save-excursion
  9983. (org-back-to-heading t)
  9984. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9985. (when (re-search-forward (if (eq what 'scheduled)
  9986. org-scheduled-time-regexp
  9987. org-deadline-time-regexp)
  9988. end t)
  9989. (setq ts (match-string 1)
  9990. default-time (apply 'encode-time (org-parse-time-string ts))
  9991. default-input (and ts (org-get-compact-tod ts)))))))
  9992. (when what
  9993. (setq time
  9994. (if (stringp time)
  9995. ;; This is a string (relative or absolute), set
  9996. ;; proper date.
  9997. (apply #'encode-time
  9998. (org-read-date-analyze
  9999. time default-time (decode-time default-time)))
  10000. ;; If necessary, get the time from the user
  10001. (or time (org-read-date nil 'to-time nil
  10002. (cl-case what
  10003. (deadline "DEADLINE")
  10004. (scheduled "SCHEDULED")
  10005. (otherwise nil))
  10006. default-time default-input)))))
  10007. (org-with-wide-buffer
  10008. (org-back-to-heading t)
  10009. (forward-line)
  10010. (unless (bolp) (insert "\n"))
  10011. (cond ((looking-at-p org-planning-line-re)
  10012. ;; Move to current indentation.
  10013. (skip-chars-forward " \t")
  10014. ;; Check if we have to remove something.
  10015. (dolist (type (if what (cons what remove) remove))
  10016. (save-excursion
  10017. (when (re-search-forward
  10018. (cl-case type
  10019. (closed org-closed-time-regexp)
  10020. (deadline org-deadline-time-regexp)
  10021. (scheduled org-scheduled-time-regexp)
  10022. (otherwise
  10023. (error "Invalid planning type: %s" type)))
  10024. (line-end-position) t)
  10025. ;; Delete until next keyword or end of line.
  10026. (delete-region
  10027. (match-beginning 0)
  10028. (if (re-search-forward org-keyword-time-not-clock-regexp
  10029. (line-end-position)
  10030. t)
  10031. (match-beginning 0)
  10032. (line-end-position))))))
  10033. ;; If there is nothing more to add and no more keyword
  10034. ;; is left, remove the line completely.
  10035. (if (and (looking-at-p "[ \t]*$") (not what))
  10036. (delete-region (line-beginning-position)
  10037. (line-beginning-position 2))
  10038. ;; If we removed last keyword, do not leave trailing
  10039. ;; white space at the end of line.
  10040. (let ((p (point)))
  10041. (save-excursion
  10042. (end-of-line)
  10043. (unless (= (skip-chars-backward " \t" p) 0)
  10044. (delete-region (point) (line-end-position)))))))
  10045. ((not what) (throw 'exit nil)) ; Nothing to do.
  10046. (t (insert-before-markers "\n")
  10047. (backward-char 1)
  10048. (when org-adapt-indentation
  10049. (indent-to-column (1+ (org-outline-level))))))
  10050. (when what
  10051. ;; Insert planning keyword.
  10052. (insert (cl-case what
  10053. (closed org-closed-string)
  10054. (deadline org-deadline-string)
  10055. (scheduled org-scheduled-string)
  10056. (otherwise (error "Invalid planning type: %s" what)))
  10057. " ")
  10058. ;; Insert associated timestamp.
  10059. (let ((ts (org-insert-time-stamp
  10060. time
  10061. (or org-time-was-given
  10062. (and (eq what 'closed) org-log-done-with-time))
  10063. (eq what 'closed)
  10064. nil nil (list org-end-time-was-given))))
  10065. (unless (eolp) (insert " "))
  10066. ts))))))
  10067. (defvar org-log-note-marker (make-marker)
  10068. "Marker pointing at the entry where the note is to be inserted.")
  10069. (defvar org-log-note-purpose nil)
  10070. (defvar org-log-note-state nil)
  10071. (defvar org-log-note-previous-state nil)
  10072. (defvar org-log-note-extra nil)
  10073. (defvar org-log-note-window-configuration nil)
  10074. (defvar org-log-note-return-to (make-marker))
  10075. (defvar org-log-note-effective-time nil
  10076. "Remembered current time so that dynamically scoped
  10077. `org-extend-today-until' affects timestamps in state change log")
  10078. (defvar org-log-post-message nil
  10079. "Message to be displayed after a log note has been stored.
  10080. The auto-repeater uses this.")
  10081. (defun org-add-note ()
  10082. "Add a note to the current entry.
  10083. This is done in the same way as adding a state change note."
  10084. (interactive)
  10085. (org-add-log-setup 'note))
  10086. (defun org-log-beginning (&optional create)
  10087. "Return expected start of log notes in current entry.
  10088. When optional argument CREATE is non-nil, the function creates
  10089. a drawer to store notes, if necessary. Returned position ignores
  10090. narrowing."
  10091. (org-with-wide-buffer
  10092. (let ((drawer (org-log-into-drawer)))
  10093. (cond
  10094. (drawer
  10095. (org-end-of-meta-data)
  10096. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  10097. (end (if (org-at-heading-p) (point)
  10098. (save-excursion (outline-next-heading) (point))))
  10099. (case-fold-search t))
  10100. (catch 'exit
  10101. ;; Try to find existing drawer.
  10102. (while (re-search-forward regexp end t)
  10103. (let ((element (org-element-at-point)))
  10104. (when (eq (org-element-type element) 'drawer)
  10105. (let ((cend (org-element-property :contents-end element)))
  10106. (when (and (not org-log-states-order-reversed) cend)
  10107. (goto-char cend)))
  10108. (throw 'exit nil))))
  10109. ;; No drawer found. Create one, if permitted.
  10110. (when create
  10111. (unless (bolp) (insert "\n"))
  10112. (let ((beg (point)))
  10113. (insert ":" drawer ":\n:END:\n")
  10114. (org-indent-region beg (point))
  10115. (org-flag-region
  10116. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  10117. (end-of-line -1)))))
  10118. (t
  10119. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  10120. (skip-chars-forward " \t\n")
  10121. (beginning-of-line)
  10122. (unless org-log-states-order-reversed
  10123. (org-skip-over-state-notes)
  10124. (skip-chars-backward " \t\n")
  10125. (forward-line)))))
  10126. (if (bolp) (point) (line-beginning-position 2))))
  10127. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  10128. "Set up the post command hook to take a note.
  10129. If this is about to TODO state change, the new state is expected in STATE.
  10130. HOW is an indicator what kind of note should be created.
  10131. EXTRA is additional text that will be inserted into the notes buffer."
  10132. (move-marker org-log-note-marker (point))
  10133. (setq org-log-note-purpose purpose
  10134. org-log-note-state state
  10135. org-log-note-previous-state prev-state
  10136. org-log-note-how how
  10137. org-log-note-extra extra
  10138. org-log-note-effective-time (org-current-effective-time))
  10139. (add-hook 'post-command-hook 'org-add-log-note 'append))
  10140. (defun org-skip-over-state-notes ()
  10141. "Skip past the list of State notes in an entry."
  10142. (when (ignore-errors (goto-char (org-in-item-p)))
  10143. (let* ((struct (org-list-struct))
  10144. (prevs (org-list-prevs-alist struct))
  10145. (regexp
  10146. (concat "[ \t]*- +"
  10147. (replace-regexp-in-string
  10148. " +" " +"
  10149. (org-replace-escapes
  10150. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  10151. `(("%d" . ,org-ts-regexp-inactive)
  10152. ("%D" . ,org-ts-regexp)
  10153. ("%s" . "\\(?:\"\\S-+\"\\)?")
  10154. ("%S" . "\\(?:\"\\S-+\"\\)?")
  10155. ("%t" . ,org-ts-regexp-inactive)
  10156. ("%T" . ,org-ts-regexp)
  10157. ("%u" . ".*?")
  10158. ("%U" . ".*?")))))))
  10159. (while (looking-at-p regexp)
  10160. (goto-char (or (org-list-get-next-item (point) struct prevs)
  10161. (org-list-get-item-end (point) struct)))))))
  10162. (defun org-add-log-note (&optional _purpose)
  10163. "Pop up a window for taking a note, and add this note later."
  10164. (remove-hook 'post-command-hook 'org-add-log-note)
  10165. (setq org-log-note-window-configuration (current-window-configuration))
  10166. (delete-other-windows)
  10167. (move-marker org-log-note-return-to (point))
  10168. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  10169. (goto-char org-log-note-marker)
  10170. (org-switch-to-buffer-other-window "*Org Note*")
  10171. (erase-buffer)
  10172. (if (memq org-log-note-how '(time state))
  10173. (org-store-log-note)
  10174. (let ((org-inhibit-startup t)) (org-mode))
  10175. (insert (format "# Insert note for %s.
  10176. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  10177. (cl-case org-log-note-purpose
  10178. (clock-out "stopped clock")
  10179. (done "closed todo item")
  10180. (reschedule "rescheduling")
  10181. (delschedule "no longer scheduled")
  10182. (redeadline "changing deadline")
  10183. (deldeadline "removing deadline")
  10184. (refile "refiling")
  10185. (note "this entry")
  10186. (state
  10187. (format "state change from \"%s\" to \"%s\""
  10188. (or org-log-note-previous-state "")
  10189. (or org-log-note-state "")))
  10190. (t (error "This should not happen")))))
  10191. (when org-log-note-extra (insert org-log-note-extra))
  10192. (setq-local org-finish-function 'org-store-log-note)
  10193. (run-hooks 'org-log-buffer-setup-hook)))
  10194. (defvar org-note-abort nil) ; dynamically scoped
  10195. (defun org-store-log-note ()
  10196. "Finish taking a log note, and insert it to where it belongs."
  10197. (let ((txt (prog1 (buffer-string)
  10198. (kill-buffer)))
  10199. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  10200. lines)
  10201. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  10202. (setq txt (replace-match "" t t txt)))
  10203. (when (string-match "\\s-+\\'" txt)
  10204. (setq txt (replace-match "" t t txt)))
  10205. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  10206. (when (org-string-nw-p note)
  10207. (setq note
  10208. (org-replace-escapes
  10209. note
  10210. (list (cons "%u" (user-login-name))
  10211. (cons "%U" user-full-name)
  10212. (cons "%t" (format-time-string
  10213. (org-time-stamp-format 'long 'inactive)
  10214. org-log-note-effective-time))
  10215. (cons "%T" (format-time-string
  10216. (org-time-stamp-format 'long nil)
  10217. org-log-note-effective-time))
  10218. (cons "%d" (format-time-string
  10219. (org-time-stamp-format nil 'inactive)
  10220. org-log-note-effective-time))
  10221. (cons "%D" (format-time-string
  10222. (org-time-stamp-format nil nil)
  10223. org-log-note-effective-time))
  10224. (cons "%s" (cond
  10225. ((not org-log-note-state) "")
  10226. ((string-match-p org-ts-regexp
  10227. org-log-note-state)
  10228. (format "\"[%s]\""
  10229. (substring org-log-note-state 1 -1)))
  10230. (t (format "\"%s\"" org-log-note-state))))
  10231. (cons "%S"
  10232. (cond
  10233. ((not org-log-note-previous-state) "")
  10234. ((string-match-p org-ts-regexp
  10235. org-log-note-previous-state)
  10236. (format "\"[%s]\""
  10237. (substring
  10238. org-log-note-previous-state 1 -1)))
  10239. (t (format "\"%s\""
  10240. org-log-note-previous-state)))))))
  10241. (when lines (setq note (concat note " \\\\")))
  10242. (push note lines))
  10243. (when (and lines (not org-note-abort))
  10244. (with-current-buffer (marker-buffer org-log-note-marker)
  10245. (org-with-wide-buffer
  10246. ;; Find location for the new note.
  10247. (goto-char org-log-note-marker)
  10248. (set-marker org-log-note-marker nil)
  10249. ;; Note associated to a clock is to be located right after
  10250. ;; the clock. Do not move point.
  10251. (unless (eq org-log-note-purpose 'clock-out)
  10252. (goto-char (org-log-beginning t)))
  10253. ;; Make sure point is at the beginning of an empty line.
  10254. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  10255. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  10256. ;; In an existing list, add a new item at the top level.
  10257. ;; Otherwise, indent line like a regular one.
  10258. (let ((itemp (org-in-item-p)))
  10259. (if itemp
  10260. (indent-line-to
  10261. (let ((struct (save-excursion
  10262. (goto-char itemp) (org-list-struct))))
  10263. (org-list-get-ind (org-list-get-top-point struct) struct)))
  10264. (org-indent-line)))
  10265. (insert (org-list-bullet-string "-") (pop lines))
  10266. (let ((ind (org-list-item-body-column (line-beginning-position))))
  10267. (dolist (line lines)
  10268. (insert "\n")
  10269. (indent-line-to ind)
  10270. (insert line)))
  10271. (message "Note stored")
  10272. (org-back-to-heading t))
  10273. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  10274. ;; from within `org-add-log-note' because `buffer-undo-list'
  10275. ;; is then modified outside of `org-with-remote-undo'.
  10276. (when (eq this-command 'org-agenda-todo)
  10277. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  10278. ;; Don't add undo information when called from `org-agenda-todo'.
  10279. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  10280. (set-window-configuration org-log-note-window-configuration)
  10281. (with-current-buffer (marker-buffer org-log-note-return-to)
  10282. (goto-char org-log-note-return-to))
  10283. (move-marker org-log-note-return-to nil)
  10284. (when org-log-post-message (message "%s" org-log-post-message))))
  10285. (defun org-remove-empty-drawer-at (pos)
  10286. "Remove an empty drawer at position POS.
  10287. POS may also be a marker."
  10288. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  10289. (org-with-wide-buffer
  10290. (goto-char pos)
  10291. (let ((drawer (org-element-at-point)))
  10292. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  10293. (not (org-element-property :contents-begin drawer)))
  10294. (delete-region (org-element-property :begin drawer)
  10295. (progn (goto-char (org-element-property :end drawer))
  10296. (skip-chars-backward " \r\t\n")
  10297. (forward-line)
  10298. (point))))))))
  10299. (defvar org-ts-type nil)
  10300. (defun org-sparse-tree (&optional arg type)
  10301. "Create a sparse tree, prompt for the details.
  10302. This command can create sparse trees. You first need to select the type
  10303. of match used to create the tree:
  10304. t Show all TODO entries.
  10305. T Show entries with a specific TODO keyword.
  10306. m Show entries selected by a tags/property match.
  10307. p Enter a property name and its value (both with completion on existing
  10308. names/values) and show entries with that property.
  10309. r Show entries matching a regular expression (`/' can be used as well).
  10310. b Show deadlines and scheduled items before a date.
  10311. a Show deadlines and scheduled items after a date.
  10312. d Show deadlines due within `org-deadline-warning-days'.
  10313. D Show deadlines and scheduled items between a date range."
  10314. (interactive "P")
  10315. (setq type (or type org-sparse-tree-default-date-type))
  10316. (setq org-ts-type type)
  10317. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  10318. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  10319. \[c]ycle through date types: %s"
  10320. (cl-case type
  10321. (all "all timestamps")
  10322. (scheduled "only scheduled")
  10323. (deadline "only deadline")
  10324. (active "only active timestamps")
  10325. (inactive "only inactive timestamps")
  10326. (closed "with a closed time-stamp")
  10327. (otherwise "scheduled/deadline")))
  10328. (let ((answer (read-char-exclusive)))
  10329. (cl-case answer
  10330. (?c
  10331. (org-sparse-tree
  10332. arg
  10333. (cadr
  10334. (memq type '(nil all scheduled deadline active inactive closed)))))
  10335. (?d (call-interactively 'org-check-deadlines))
  10336. (?b (call-interactively 'org-check-before-date))
  10337. (?a (call-interactively 'org-check-after-date))
  10338. (?D (call-interactively 'org-check-dates-range))
  10339. (?t (call-interactively 'org-show-todo-tree))
  10340. (?T (org-show-todo-tree '(4)))
  10341. (?m (call-interactively 'org-match-sparse-tree))
  10342. ((?p ?P)
  10343. (let* ((kwd (completing-read
  10344. "Property: " (mapcar #'list (org-buffer-property-keys))))
  10345. (value (completing-read
  10346. "Value: " (mapcar #'list (org-property-values kwd)))))
  10347. (unless (string-match "\\`{.*}\\'" value)
  10348. (setq value (concat "\"" value "\"")))
  10349. (org-match-sparse-tree arg (concat kwd "=" value))))
  10350. ((?r ?R ?/) (call-interactively 'org-occur))
  10351. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  10352. (defvar-local org-occur-highlights nil
  10353. "List of overlays used for occur matches.")
  10354. (defvar-local org-occur-parameters nil
  10355. "Parameters of the active org-occur calls.
  10356. This is a list, each call to org-occur pushes as cons cell,
  10357. containing the regular expression and the callback, onto the list.
  10358. The list can contain several entries if `org-occur' has been called
  10359. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  10360. will only contain one set of parameters. When the highlights are
  10361. removed (for example with `C-c C-c', or with the next edit (depending
  10362. on `org-remove-highlights-with-change'), this variable is emptied
  10363. as well.")
  10364. (defun org-occur (regexp &optional keep-previous callback)
  10365. "Make a compact tree which shows all matches of REGEXP.
  10366. The tree will show the lines where the regexp matches, and any other context
  10367. defined in `org-show-context-detail', which see.
  10368. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  10369. done by a previous call to `org-occur' will be kept, to allow stacking of
  10370. calls to this command.
  10371. Optional argument CALLBACK can be a function of no argument. In this case,
  10372. it is called with point at the end of the match, match data being set
  10373. accordingly. Current match is shown only if the return value is non-nil.
  10374. The function must neither move point nor alter narrowing."
  10375. (interactive "sRegexp: \nP")
  10376. (when (equal regexp "")
  10377. (user-error "Regexp cannot be empty"))
  10378. (unless keep-previous
  10379. (org-remove-occur-highlights nil nil t))
  10380. (push (cons regexp callback) org-occur-parameters)
  10381. (let ((cnt 0))
  10382. (save-excursion
  10383. (goto-char (point-min))
  10384. (when (or (not keep-previous) ; do not want to keep
  10385. (not org-occur-highlights)) ; no previous matches
  10386. ;; hide everything
  10387. (org-overview))
  10388. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  10389. (isearch-no-upper-case-p regexp t)
  10390. org-occur-case-fold-search)))
  10391. (while (re-search-forward regexp nil t)
  10392. (when (or (not callback)
  10393. (save-match-data (funcall callback)))
  10394. (setq cnt (1+ cnt))
  10395. (when org-highlight-sparse-tree-matches
  10396. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  10397. (org-show-context 'occur-tree)))))
  10398. (when org-remove-highlights-with-change
  10399. (add-hook 'before-change-functions 'org-remove-occur-highlights
  10400. nil 'local))
  10401. (unless org-sparse-tree-open-archived-trees
  10402. (org-hide-archived-subtrees (point-min) (point-max)))
  10403. (run-hooks 'org-occur-hook)
  10404. (when (called-interactively-p 'interactive)
  10405. (message "%d match(es) for regexp %s" cnt regexp))
  10406. cnt))
  10407. (defun org-occur-next-match (&optional n _reset)
  10408. "Function for `next-error-function' to find sparse tree matches.
  10409. N is the number of matches to move, when negative move backwards.
  10410. This function always goes back to the starting point when no
  10411. match is found."
  10412. (let* ((limit (if (< n 0) (point-min) (point-max)))
  10413. (search-func (if (< n 0)
  10414. 'previous-single-char-property-change
  10415. 'next-single-char-property-change))
  10416. (n (abs n))
  10417. (pos (point))
  10418. p1)
  10419. (catch 'exit
  10420. (while (setq p1 (funcall search-func (point) 'org-type))
  10421. (when (equal p1 limit)
  10422. (goto-char pos)
  10423. (user-error "No more matches"))
  10424. (when (equal (get-char-property p1 'org-type) 'org-occur)
  10425. (setq n (1- n))
  10426. (when (= n 0)
  10427. (goto-char p1)
  10428. (throw 'exit (point))))
  10429. (goto-char p1))
  10430. (goto-char p1)
  10431. (user-error "No more matches"))))
  10432. (defun org-highlight-new-match (beg end)
  10433. "Highlight from BEG to END and mark the highlight is an occur headline."
  10434. (let ((ov (make-overlay beg end)))
  10435. (overlay-put ov 'face 'secondary-selection)
  10436. (overlay-put ov 'org-type 'org-occur)
  10437. (push ov org-occur-highlights)))
  10438. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10439. "Remove the occur highlights from the buffer.
  10440. BEG and END are ignored. If NOREMOVE is nil, remove this function
  10441. from the `before-change-functions' in the current buffer."
  10442. (interactive)
  10443. (unless org-inhibit-highlight-removal
  10444. (mapc #'delete-overlay org-occur-highlights)
  10445. (setq org-occur-highlights nil)
  10446. (setq org-occur-parameters nil)
  10447. (unless noremove
  10448. (remove-hook 'before-change-functions
  10449. 'org-remove-occur-highlights 'local))))
  10450. ;;;; Priorities
  10451. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  10452. "Regular expression matching the priority indicator.")
  10453. (defvar org-remove-priority-next-time nil)
  10454. (defun org-priority-up ()
  10455. "Increase the priority of the current item."
  10456. (interactive)
  10457. (org-priority 'up))
  10458. (defun org-priority-down ()
  10459. "Decrease the priority of the current item."
  10460. (interactive)
  10461. (org-priority 'down))
  10462. (defun org-priority (&optional action show)
  10463. "Change the priority of an item.
  10464. When called interactively with a `\\[universal-argument]' prefix,
  10465. show the priority in the minibuffer instead of changing it.
  10466. When called programatically, ACTION can be `set', `up', `down',
  10467. or a character."
  10468. (interactive "P")
  10469. (when show
  10470. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10471. ;; passed the SHOW argument should be removed.
  10472. (warn "`org-priority' called with deprecated SHOW argument"))
  10473. (if (equal action '(4))
  10474. (org-show-priority)
  10475. (unless org-enable-priority-commands
  10476. (user-error "Priority commands are disabled"))
  10477. (setq action (or action 'set))
  10478. (let (current new news have remove)
  10479. (save-excursion
  10480. (org-back-to-heading t)
  10481. (when (looking-at org-priority-regexp)
  10482. (setq current (string-to-char (match-string 2))
  10483. have t))
  10484. (cond
  10485. ((eq action 'remove)
  10486. (setq remove t new ?\ ))
  10487. ((or (eq action 'set)
  10488. (integerp action))
  10489. (if (not (eq action 'set))
  10490. (setq new action)
  10491. (message "Priority %c-%c, SPC to remove: "
  10492. org-highest-priority org-lowest-priority)
  10493. (save-match-data
  10494. (setq new (read-char-exclusive))))
  10495. (when (and (= (upcase org-highest-priority) org-highest-priority)
  10496. (= (upcase org-lowest-priority) org-lowest-priority))
  10497. (setq new (upcase new)))
  10498. (cond ((equal new ?\s) (setq remove t))
  10499. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  10500. (user-error "Priority must be between `%c' and `%c'"
  10501. org-highest-priority org-lowest-priority))))
  10502. ((eq action 'up)
  10503. (setq new (if have
  10504. (1- current) ; normal cycling
  10505. ;; last priority was empty
  10506. (if (eq last-command this-command)
  10507. org-lowest-priority ; wrap around empty to lowest
  10508. ;; default
  10509. (if org-priority-start-cycle-with-default
  10510. org-default-priority
  10511. (1- org-default-priority))))))
  10512. ((eq action 'down)
  10513. (setq new (if have
  10514. (1+ current) ; normal cycling
  10515. ;; last priority was empty
  10516. (if (eq last-command this-command)
  10517. org-highest-priority ; wrap around empty to highest
  10518. ;; default
  10519. (if org-priority-start-cycle-with-default
  10520. org-default-priority
  10521. (1+ org-default-priority))))))
  10522. (t (user-error "Invalid action")))
  10523. (when (or (< (upcase new) org-highest-priority)
  10524. (> (upcase new) org-lowest-priority))
  10525. (if (and (memq action '(up down))
  10526. (not have) (not (eq last-command this-command)))
  10527. ;; `new' is from default priority
  10528. (error
  10529. "The default can not be set, see `org-default-priority' why")
  10530. ;; normal cycling: `new' is beyond highest/lowest priority
  10531. ;; and is wrapped around to the empty priority
  10532. (setq remove t)))
  10533. (setq news (format "%c" new))
  10534. (if have
  10535. (if remove
  10536. (replace-match "" t t nil 1)
  10537. (replace-match news t t nil 2))
  10538. (if remove
  10539. (user-error "No priority cookie found in line")
  10540. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10541. (if (match-end 2)
  10542. (progn
  10543. (goto-char (match-end 2))
  10544. (insert " [#" news "]"))
  10545. (goto-char (match-beginning 3))
  10546. (insert "[#" news "] "))))
  10547. (org-align-tags))
  10548. (if remove
  10549. (message "Priority removed")
  10550. (message "Priority of current item set to %s" news)))))
  10551. (defun org-show-priority ()
  10552. "Show the priority of the current item.
  10553. This priority is composed of the main priority given with the [#A] cookies,
  10554. and by additional input from the age of a schedules or deadline entry."
  10555. (interactive)
  10556. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10557. (org-get-at-bol 'priority)
  10558. (save-excursion
  10559. (save-match-data
  10560. (beginning-of-line)
  10561. (and (looking-at org-heading-regexp)
  10562. (org-get-priority (match-string 0))))))))
  10563. (message "Priority is %d" (if pri pri -1000))))
  10564. (defun org-get-priority (s)
  10565. "Find priority cookie and return priority."
  10566. (save-match-data
  10567. (if (functionp org-get-priority-function)
  10568. (funcall org-get-priority-function)
  10569. (if (not (string-match org-priority-regexp s))
  10570. (* 1000 (- org-lowest-priority org-default-priority))
  10571. (* 1000 (- org-lowest-priority
  10572. (string-to-char (match-string 2 s))))))))
  10573. ;;;; Tags
  10574. (defvar org-agenda-archives-mode)
  10575. (defvar org-map-continue-from nil
  10576. "Position from where mapping should continue.
  10577. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10578. (defvar org-scanner-tags nil
  10579. "The current tag list while the tags scanner is running.")
  10580. (defvar org-trust-scanner-tags nil
  10581. "Should `org-get-tags' use the tags for the scanner.
  10582. This is for internal dynamical scoping only.
  10583. When this is non-nil, the function `org-get-tags' will return the value
  10584. of `org-scanner-tags' instead of building the list by itself. This
  10585. can lead to large speed-ups when the tags scanner is used in a file with
  10586. many entries, and when the list of tags is retrieved, for example to
  10587. obtain a list of properties. Building the tags list for each entry in such
  10588. a file becomes an N^2 operation - but with this variable set, it scales
  10589. as N.")
  10590. (defvar org--matcher-tags-todo-only nil)
  10591. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10592. "Scan headline tags with inheritance and produce output ACTION.
  10593. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10594. or `agenda' to produce an entry list for an agenda view. It can also be
  10595. a Lisp form or a function that should be called at each matched headline, in
  10596. this case the return value is a list of all return values from these calls.
  10597. MATCHER is a function accepting three arguments, returning
  10598. a non-nil value whenever a given set of tags qualifies a headline
  10599. for inclusion. See `org-make-tags-matcher' for more information.
  10600. As a special case, it can also be set to t (respectively nil) in
  10601. order to match all (respectively none) headline.
  10602. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10603. included in the output.
  10604. START-LEVEL can be a string with asterisks, reducing the scope to
  10605. headlines matching this string."
  10606. (require 'org-agenda)
  10607. (let* ((re (concat "^"
  10608. (if start-level
  10609. ;; Get the correct level to match
  10610. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10611. org-outline-regexp)
  10612. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10613. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10614. (props (list 'face 'default
  10615. 'done-face 'org-agenda-done
  10616. 'undone-face 'default
  10617. 'mouse-face 'highlight
  10618. 'org-not-done-regexp org-not-done-regexp
  10619. 'org-todo-regexp org-todo-regexp
  10620. 'org-complex-heading-regexp org-complex-heading-regexp
  10621. 'help-echo
  10622. (format "mouse-2 or RET jump to Org file %S"
  10623. (abbreviate-file-name
  10624. (or (buffer-file-name (buffer-base-buffer))
  10625. (buffer-name (buffer-base-buffer)))))))
  10626. (org-map-continue-from nil)
  10627. lspos tags tags-list
  10628. (tags-alist (list (cons 0 org-file-tags)))
  10629. (llast 0) rtn rtn1 level category i txt
  10630. todo marker entry priority
  10631. ts-date ts-date-type ts-date-pair)
  10632. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10633. (setq action (list 'lambda nil action)))
  10634. (save-excursion
  10635. (goto-char (point-min))
  10636. (when (eq action 'sparse-tree)
  10637. (org-overview)
  10638. (org-remove-occur-highlights))
  10639. (while (let (case-fold-search)
  10640. (re-search-forward re nil t))
  10641. (setq org-map-continue-from nil)
  10642. (catch :skip
  10643. ;; Ignore closing parts of inline tasks.
  10644. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10645. (throw :skip t))
  10646. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10647. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10648. (goto-char (setq lspos (match-beginning 0)))
  10649. (setq level (org-reduced-level (org-outline-level))
  10650. category (org-get-category))
  10651. (when (eq action 'agenda)
  10652. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10653. ts-date (car ts-date-pair)
  10654. ts-date-type (cdr ts-date-pair)))
  10655. (setq i llast llast level)
  10656. ;; remove tag lists from same and sublevels
  10657. (while (>= i level)
  10658. (when (setq entry (assoc i tags-alist))
  10659. (setq tags-alist (delete entry tags-alist)))
  10660. (setq i (1- i)))
  10661. ;; add the next tags
  10662. (when tags
  10663. (setq tags (org-split-string tags ":")
  10664. tags-alist
  10665. (cons (cons level tags) tags-alist)))
  10666. ;; compile tags for current headline
  10667. (setq tags-list
  10668. (if org-use-tag-inheritance
  10669. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10670. tags)
  10671. org-scanner-tags tags-list)
  10672. (when org-use-tag-inheritance
  10673. (setcdr (car tags-alist)
  10674. (mapcar (lambda (x)
  10675. (setq x (copy-sequence x))
  10676. (org-add-prop-inherited x))
  10677. (cdar tags-alist))))
  10678. (when (and tags org-use-tag-inheritance
  10679. (or (not (eq t org-use-tag-inheritance))
  10680. org-tags-exclude-from-inheritance))
  10681. ;; Selective inheritance, remove uninherited ones.
  10682. (setcdr (car tags-alist)
  10683. (org-remove-uninherited-tags (cdar tags-alist))))
  10684. (when (and
  10685. ;; eval matcher only when the todo condition is OK
  10686. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10687. (if (functionp matcher)
  10688. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10689. (funcall matcher todo tags-list level))
  10690. matcher))
  10691. ;; Call the skipper, but return t if it does not
  10692. ;; skip, so that the `and' form continues evaluating.
  10693. (progn
  10694. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10695. t)
  10696. ;; Check if timestamps are deselecting this entry
  10697. (or (not todo-only)
  10698. (and (member todo org-todo-keywords-1)
  10699. (or (not org-agenda-tags-todo-honor-ignore-options)
  10700. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10701. ;; select this headline
  10702. (cond
  10703. ((eq action 'sparse-tree)
  10704. (and org-highlight-sparse-tree-matches
  10705. (org-get-heading) (match-end 0)
  10706. (org-highlight-new-match
  10707. (match-beginning 1) (match-end 1)))
  10708. (org-show-context 'tags-tree))
  10709. ((eq action 'agenda)
  10710. (setq txt (org-agenda-format-item
  10711. ""
  10712. (concat
  10713. (if (eq org-tags-match-list-sublevels 'indented)
  10714. (make-string (1- level) ?.) "")
  10715. (org-get-heading))
  10716. (make-string level ?\s)
  10717. category
  10718. tags-list)
  10719. priority (org-get-priority txt))
  10720. (goto-char lspos)
  10721. (setq marker (org-agenda-new-marker))
  10722. (org-add-props txt props
  10723. 'org-marker marker 'org-hd-marker marker 'org-category category
  10724. 'todo-state todo
  10725. 'ts-date ts-date
  10726. 'priority priority
  10727. 'type (concat "tagsmatch" ts-date-type))
  10728. (push txt rtn))
  10729. ((functionp action)
  10730. (setq org-map-continue-from nil)
  10731. (save-excursion
  10732. (setq rtn1 (funcall action))
  10733. (push rtn1 rtn)))
  10734. (t (user-error "Invalid action")))
  10735. ;; if we are to skip sublevels, jump to end of subtree
  10736. (unless org-tags-match-list-sublevels
  10737. (org-end-of-subtree t)
  10738. (backward-char 1))))
  10739. ;; Get the correct position from where to continue
  10740. (if org-map-continue-from
  10741. (goto-char org-map-continue-from)
  10742. (and (= (point) lspos) (end-of-line 1)))))
  10743. (when (and (eq action 'sparse-tree)
  10744. (not org-sparse-tree-open-archived-trees))
  10745. (org-hide-archived-subtrees (point-min) (point-max)))
  10746. (nreverse rtn)))
  10747. (defun org-remove-uninherited-tags (tags)
  10748. "Remove all tags that are not inherited from the list TAGS."
  10749. (cond
  10750. ((eq org-use-tag-inheritance t)
  10751. (if org-tags-exclude-from-inheritance
  10752. (org-delete-all org-tags-exclude-from-inheritance tags)
  10753. tags))
  10754. ((not org-use-tag-inheritance) nil)
  10755. ((stringp org-use-tag-inheritance)
  10756. (delq nil (mapcar
  10757. (lambda (x)
  10758. (if (and (string-match org-use-tag-inheritance x)
  10759. (not (member x org-tags-exclude-from-inheritance)))
  10760. x nil))
  10761. tags)))
  10762. ((listp org-use-tag-inheritance)
  10763. (delq nil (mapcar
  10764. (lambda (x)
  10765. (if (member x org-use-tag-inheritance) x nil))
  10766. tags)))))
  10767. (defun org-match-sparse-tree (&optional todo-only match)
  10768. "Create a sparse tree according to tags string MATCH.
  10769. MATCH is a string with match syntax. It can contain a selection
  10770. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10771. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10772. those. See the manual for details.
  10773. If optional argument TODO-ONLY is non-nil, only select lines that
  10774. are also TODO tasks."
  10775. (interactive "P")
  10776. (org-agenda-prepare-buffers (list (current-buffer)))
  10777. (let ((org--matcher-tags-todo-only todo-only))
  10778. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  10779. org--matcher-tags-todo-only)))
  10780. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10781. (defvar org-cached-props nil)
  10782. (defun org-cached-entry-get (pom property)
  10783. (if (or (eq t org-use-property-inheritance)
  10784. (and (stringp org-use-property-inheritance)
  10785. (let ((case-fold-search t))
  10786. (string-match-p org-use-property-inheritance property)))
  10787. (and (listp org-use-property-inheritance)
  10788. (member-ignore-case property org-use-property-inheritance)))
  10789. ;; Caching is not possible, check it directly.
  10790. (org-entry-get pom property 'inherit)
  10791. ;; Get all properties, so we can do complicated checks easily.
  10792. (cdr (assoc-string property
  10793. (or org-cached-props
  10794. (setq org-cached-props (org-entry-properties pom)))
  10795. t))))
  10796. (defun org-global-tags-completion-table (&optional files)
  10797. "Return the list of all tags in all agenda buffer/files.
  10798. Optional FILES argument is a list of files which can be used
  10799. instead of the agenda files."
  10800. (save-excursion
  10801. (org-uniquify
  10802. (delq nil
  10803. (apply #'append
  10804. (mapcar
  10805. (lambda (file)
  10806. (set-buffer (find-file-noselect file))
  10807. (org--tag-add-to-alist
  10808. (org-get-buffer-tags)
  10809. (mapcar (lambda (x)
  10810. (and (stringp (car-safe x))
  10811. (list (car-safe x))))
  10812. org-current-tag-alist)))
  10813. (if (car-safe files) files
  10814. (org-agenda-files))))))))
  10815. (defun org-make-tags-matcher (match)
  10816. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10817. Returns a cons of the selection string MATCH and a function
  10818. implementing the matcher.
  10819. The matcher is to be called at an Org entry, with point on the
  10820. headline, and returns non-nil if the entry matches the selection
  10821. string MATCH. It must be called with three arguments: the TODO
  10822. keyword at the entry (or nil if none), the list of all tags at
  10823. the entry including inherited ones and the reduced level of the
  10824. headline. Additionally, the category of the entry, if any, must
  10825. be specified as the text property `org-category' on the headline.
  10826. This function sets the variable `org--matcher-tags-todo-only' to
  10827. a non-nil value if the matcher restricts matching to TODO
  10828. entries, otherwise it is not touched.
  10829. See also `org-scan-tags'."
  10830. (unless match
  10831. ;; Get a new match request, with completion against the global
  10832. ;; tags table and the local tags in current buffer.
  10833. (let ((org-last-tags-completion-table
  10834. (org--tag-add-to-alist
  10835. (org-get-buffer-tags)
  10836. (org-global-tags-completion-table))))
  10837. (setq match
  10838. (completing-read
  10839. "Match: "
  10840. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10841. (let ((match0 match)
  10842. (re (concat
  10843. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10844. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10845. "\\([<>=]\\{1,2\\}\\)"
  10846. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10847. "\\|" org-tag-re "\\)"))
  10848. (start 0)
  10849. tagsmatch todomatch tagsmatcher todomatcher)
  10850. ;; Expand group tags.
  10851. (setq match (org-tags-expand match))
  10852. ;; Check if there is a TODO part of this match, which would be the
  10853. ;; part after a "/". To make sure that this slash is not part of
  10854. ;; a property value to be matched against, we also check that
  10855. ;; there is no / after that slash. First, find the last slash.
  10856. (let ((s 0))
  10857. (while (string-match "/+" match s)
  10858. (setq start (match-beginning 0))
  10859. (setq s (match-end 0))))
  10860. (if (and (string-match "/+" match start)
  10861. (not (string-match-p "\"" match start)))
  10862. ;; Match contains also a TODO-matching request.
  10863. (progn
  10864. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10865. (setq todomatch (substring match (match-end 0)))
  10866. (when (string-prefix-p "!" todomatch)
  10867. (setq org--matcher-tags-todo-only t)
  10868. (setq todomatch (substring todomatch 1)))
  10869. (when (string-match "\\`\\s-*\\'" todomatch)
  10870. (setq todomatch nil)))
  10871. ;; Only matching tags.
  10872. (setq tagsmatch match)
  10873. (setq todomatch nil))
  10874. ;; Make the tags matcher.
  10875. (when (org-string-nw-p tagsmatch)
  10876. (let ((orlist nil)
  10877. (orterms (org-split-string tagsmatch "|"))
  10878. term)
  10879. (while (setq term (pop orterms))
  10880. (while (and (equal (substring term -1) "\\") orterms)
  10881. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10882. (while (string-match re term)
  10883. (let* ((rest (substring term (match-end 0)))
  10884. (minus (and (match-end 1)
  10885. (equal (match-string 1 term) "-")))
  10886. (tag (save-match-data
  10887. (replace-regexp-in-string
  10888. "\\\\-" "-" (match-string 2 term))))
  10889. (regexp (eq (string-to-char tag) ?{))
  10890. (levelp (match-end 4))
  10891. (propp (match-end 5))
  10892. (mm
  10893. (cond
  10894. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10895. (levelp
  10896. `(,(org-op-to-function (match-string 3 term))
  10897. level
  10898. ,(string-to-number (match-string 4 term))))
  10899. (propp
  10900. (let* ((gv (pcase (upcase (match-string 5 term))
  10901. ("CATEGORY"
  10902. '(get-text-property (point) 'org-category))
  10903. ("TODO" 'todo)
  10904. (p `(org-cached-entry-get nil ,p))))
  10905. (pv (match-string 7 term))
  10906. (regexp (eq (string-to-char pv) ?{))
  10907. (strp (eq (string-to-char pv) ?\"))
  10908. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10909. (po (org-op-to-function (match-string 6 term)
  10910. (if timep 'time strp))))
  10911. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10912. (when timep (setq pv (org-matcher-time pv)))
  10913. (cond ((and regexp (eq po '/=))
  10914. `(not (string-match ,pv (or ,gv ""))))
  10915. (regexp `(string-match ,pv (or ,gv "")))
  10916. (strp `(,po (or ,gv "") ,pv))
  10917. (t
  10918. `(,po
  10919. (string-to-number (or ,gv ""))
  10920. ,(string-to-number pv))))))
  10921. (t `(member ,tag tags-list)))))
  10922. (push (if minus `(not ,mm) mm) tagsmatcher)
  10923. (setq term rest)))
  10924. (push `(and ,@tagsmatcher) orlist)
  10925. (setq tagsmatcher nil))
  10926. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10927. ;; Make the TODO matcher.
  10928. (when (org-string-nw-p todomatch)
  10929. (let ((orlist nil))
  10930. (dolist (term (org-split-string todomatch "|"))
  10931. (while (string-match re term)
  10932. (let* ((minus (and (match-end 1)
  10933. (equal (match-string 1 term) "-")))
  10934. (kwd (match-string 2 term))
  10935. (regexp (eq (string-to-char kwd) ?{))
  10936. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10937. `(equal todo ,kwd))))
  10938. (push (if minus `(not ,mm) mm) todomatcher))
  10939. (setq term (substring term (match-end 0))))
  10940. (push (if (> (length todomatcher) 1)
  10941. (cons 'and todomatcher)
  10942. (car todomatcher))
  10943. orlist)
  10944. (setq todomatcher nil))
  10945. (setq todomatcher (cons 'or orlist))))
  10946. ;; Return the string and function of the matcher. If no
  10947. ;; tags-specific or todo-specific matcher exists, match
  10948. ;; everything.
  10949. (let ((matcher (if (and tagsmatcher todomatcher)
  10950. `(and ,tagsmatcher ,todomatcher)
  10951. (or tagsmatcher todomatcher t))))
  10952. (when org--matcher-tags-todo-only
  10953. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10954. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10955. (defun org--tags-expand-group (group tag-groups expanded)
  10956. "Recursively Expand all tags in GROUP, according to TAG-GROUPS.
  10957. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10958. an accumulator used in recursive calls."
  10959. (dolist (tag group)
  10960. (unless (member tag expanded)
  10961. (let ((group (assoc tag tag-groups)))
  10962. (push tag expanded)
  10963. (when group
  10964. (setq expanded
  10965. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10966. expanded)
  10967. (defun org-tags-expand (match &optional single-as-list downcased)
  10968. "Expand group tags in MATCH.
  10969. This replaces every group tag in MATCH with a regexp tag search.
  10970. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10971. will be replaced like this:
  10972. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10973. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10974. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10975. Replacing by a regexp preserves the structure of the match.
  10976. E.g., this expansion
  10977. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10978. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10979. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10980. A group tag in MATCH can contain regular expressions of its own.
  10981. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10982. will be replaced like this:
  10983. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10984. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10985. assumed to be a single group tag, and the function will return
  10986. the list of tags in this group.
  10987. When DOWNCASED is non-nil, expand downcased TAGS."
  10988. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10989. (let ((tag-groups
  10990. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10991. (if (not downcased) g
  10992. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  10993. (cond
  10994. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10995. (org-group-tags
  10996. (let* ((case-fold-search t)
  10997. (tag-syntax org-mode-syntax-table)
  10998. (group-keys (mapcar #'car tag-groups))
  10999. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  11000. (return-match (if downcased (downcase match) match)))
  11001. ;; Mark regexp-expressions in the match-expression so that we
  11002. ;; do not replace them later on.
  11003. (let ((s 0))
  11004. (while (string-match "{.+?}" return-match s)
  11005. (setq s (match-end 0))
  11006. (add-text-properties
  11007. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  11008. ;; @ and _ are allowed as word-components in tags.
  11009. (modify-syntax-entry ?@ "w" tag-syntax)
  11010. (modify-syntax-entry ?_ "w" tag-syntax)
  11011. ;; For each tag token found in MATCH, compute a regexp and it
  11012. (with-syntax-table tag-syntax
  11013. (replace-regexp-in-string
  11014. key-regexp
  11015. (lambda (m)
  11016. (if (get-text-property (match-beginning 2) 'regexp m)
  11017. m ;regexp tag: ignore
  11018. (let* ((operator (match-string 1 m))
  11019. (tag-token (let ((tag (match-string 2 m)))
  11020. (list (if downcased (downcase tag) tag))))
  11021. regexp-tags regular-tags)
  11022. ;; Partition tags between regexp and regular tags.
  11023. ;; Remove curly bracket syntax from regexp tags.
  11024. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  11025. (save-match-data
  11026. (if (string-match "{\\(.+?\\)}" tag)
  11027. (push (match-string 1 tag) regexp-tags)
  11028. (push tag regular-tags))))
  11029. ;; Replace tag token by the appropriate regexp.
  11030. ;; Regular tags need to be regexp-quoted, whereas
  11031. ;; regexp-tags are inserted as-is.
  11032. (let ((regular (regexp-opt regular-tags))
  11033. (regexp (mapconcat #'identity regexp-tags "\\|")))
  11034. (concat operator
  11035. (cond
  11036. ((null regular-tags) (format "{%s}" regexp))
  11037. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  11038. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  11039. return-match
  11040. t t))))
  11041. (t match))))
  11042. (defun org-op-to-function (op &optional stringp)
  11043. "Turn an operator into the appropriate function."
  11044. (setq op
  11045. (cond
  11046. ((equal op "<" ) '(< org-string< org-time<))
  11047. ((equal op ">" ) '(> org-string> org-time>))
  11048. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  11049. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  11050. ((member op '("=" "==")) '(= string= org-time=))
  11051. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  11052. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  11053. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  11054. (defvar org-tags-overlay (make-overlay 1 1))
  11055. (delete-overlay org-tags-overlay)
  11056. (defun org-add-prop-inherited (s)
  11057. (add-text-properties 0 (length s) '(inherited t) s)
  11058. s)
  11059. (defun org-toggle-tag (tag &optional onoff)
  11060. "Toggle the tag TAG for the current line.
  11061. If ONOFF is `on' or `off', don't toggle but set to this state."
  11062. (save-excursion
  11063. (org-back-to-heading t)
  11064. (let ((current
  11065. ;; Reverse the tags list so any new tag is appended to the
  11066. ;; current list of tags.
  11067. (nreverse (org-get-tags nil t)))
  11068. res)
  11069. (pcase onoff
  11070. (`off (setq current (delete tag current)))
  11071. ((or `on (guard (not (member tag current))))
  11072. (setq res t)
  11073. (cl-pushnew tag current :test #'equal))
  11074. (_ (setq current (delete tag current))))
  11075. (org-set-tags (nreverse current))
  11076. res)))
  11077. (defun org--align-tags-here (to-col)
  11078. "Align tags on the current headline to TO-COL.
  11079. Assume point is on a headline. Preserve point when aligning
  11080. tags."
  11081. (when (org-match-line org-tag-line-re)
  11082. (let* ((tags-start (match-beginning 1))
  11083. (blank-start (save-excursion
  11084. (goto-char tags-start)
  11085. (skip-chars-backward " \t")
  11086. (point)))
  11087. (new (max (if (>= to-col 0) to-col
  11088. (- (abs to-col) (string-width (match-string 1))))
  11089. ;; Introduce at least one space after the heading
  11090. ;; or the stars.
  11091. (save-excursion
  11092. (goto-char blank-start)
  11093. (1+ (current-column)))))
  11094. (current
  11095. (save-excursion (goto-char tags-start) (current-column)))
  11096. (origin (point-marker))
  11097. (column (current-column))
  11098. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  11099. (when (/= new current)
  11100. (delete-region blank-start tags-start)
  11101. (goto-char blank-start)
  11102. (let ((indent-tabs-mode nil)) (indent-to new))
  11103. ;; Try to move back to original position. If point was in the
  11104. ;; blanks before the tags, ORIGIN marker is of no use because
  11105. ;; it now points to BLANK-START. Use COLUMN instead.
  11106. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  11107. (defun org-set-tags-command (&optional arg)
  11108. "Set the tags for the current visible entry.
  11109. When called with `\\[universal-argument]' prefix argument ARG, \
  11110. realign all tags
  11111. in the current buffer.
  11112. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  11113. unconditionally do not
  11114. offer the fast tag selection interface.
  11115. If a region is active, set tags in the region according to the
  11116. setting of `org-loop-over-headlines-in-active-region'.
  11117. This function is for interactive use only;
  11118. in Lisp code use `org-set-tags' instead."
  11119. (interactive "P")
  11120. (let ((org-use-fast-tag-selection
  11121. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  11122. (cond
  11123. ((equal '(4) arg) (org-align-tags t))
  11124. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11125. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  11126. (org-map-entries
  11127. #'org-set-tags-command
  11128. nil
  11129. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11130. 'region-start-level
  11131. 'region)
  11132. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  11133. (t
  11134. (save-excursion
  11135. (org-back-to-heading)
  11136. (let* ((all-tags (org-get-tags))
  11137. (table (setq org-last-tags-completion-table
  11138. (org--tag-add-to-alist
  11139. (and org-complete-tags-always-offer-all-agenda-tags
  11140. (org-global-tags-completion-table
  11141. (org-agenda-files)))
  11142. (or org-current-tag-alist (org-get-buffer-tags)))))
  11143. (current-tags
  11144. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  11145. all-tags))
  11146. (inherited-tags
  11147. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  11148. all-tags))
  11149. (tags
  11150. (replace-regexp-in-string
  11151. ;; Ignore all forbidden characters in tags.
  11152. "[^[:alnum:]_@#%]+" ":"
  11153. (if (or (eq t org-use-fast-tag-selection)
  11154. (and org-use-fast-tag-selection
  11155. (delq nil (mapcar #'cdr table))))
  11156. (org-fast-tag-selection
  11157. current-tags
  11158. inherited-tags
  11159. table
  11160. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  11161. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  11162. (org-trim (completing-read
  11163. "Tags: "
  11164. #'org-tags-completion-function
  11165. nil nil (org-make-tag-string current-tags)
  11166. 'org-tags-history)))))))
  11167. (org-set-tags tags)))))))
  11168. (defun org-align-tags (&optional all)
  11169. "Align tags in current entry.
  11170. When optional argument ALL is non-nil, align all tags in the
  11171. visible part of the buffer."
  11172. (let ((get-indent-column
  11173. (lambda ()
  11174. (let ((offset (if (bound-and-true-p org-indent-mode)
  11175. (* (1- org-indent-indentation-per-level)
  11176. (1- (org-current-level)))
  11177. 0)))
  11178. (+ org-tags-column
  11179. (if (> org-tags-column 0) (- offset) offset))))))
  11180. (if (and (not all) (org-at-heading-p))
  11181. (org--align-tags-here (funcall get-indent-column))
  11182. (save-excursion
  11183. (if all
  11184. (progn
  11185. (goto-char (point-min))
  11186. (while (re-search-forward org-tag-line-re nil t)
  11187. (org--align-tags-here (funcall get-indent-column))))
  11188. (org-back-to-heading t)
  11189. (org--align-tags-here (funcall get-indent-column)))))))
  11190. (defun org-set-tags (tags)
  11191. "Set the tags of the current entry to TAGS, replacing current tags.
  11192. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  11193. If TAGS is nil or the empty string, all tags are removed.
  11194. This function assumes point is on a headline."
  11195. (org-with-wide-buffer
  11196. (let ((tags (pcase tags
  11197. ((pred listp) tags)
  11198. ((pred stringp) (split-string (org-trim tags) ":" t))
  11199. (_ (error "Invalid tag specification: %S" tags))))
  11200. (old-tags (org-get-tags nil t))
  11201. (tags-change? nil))
  11202. (when (functionp org-tags-sort-function)
  11203. (setq tags (sort tags org-tags-sort-function)))
  11204. (setq tags-change? (not (equal tags old-tags)))
  11205. (when tags-change?
  11206. ;; Delete previous tags and any trailing white space.
  11207. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  11208. (line-end-position)))
  11209. (skip-chars-backward " \t")
  11210. (delete-region (point) (line-end-position))
  11211. ;; Deleting white spaces may break an otherwise empty headline.
  11212. ;; Re-introduce one space in this case.
  11213. (unless (org-at-heading-p) (insert " "))
  11214. (when tags
  11215. (save-excursion (insert " " (org-make-tag-string tags)))
  11216. ;; When text is being inserted on an invisible region
  11217. ;; boundary, it can be inadvertently sucked into
  11218. ;; invisibility.
  11219. (unless (org-invisible-p (line-beginning-position))
  11220. (org-flag-region (point) (line-end-position) nil 'outline))))
  11221. ;; Align tags, if any.
  11222. (when tags (org-align-tags))
  11223. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  11224. (defun org-change-tag-in-region (beg end tag off)
  11225. "Add or remove TAG for each entry in the region.
  11226. This works in the agenda, and also in an Org buffer."
  11227. (interactive
  11228. (list (region-beginning) (region-end)
  11229. (let ((org-last-tags-completion-table
  11230. (if (derived-mode-p 'org-mode)
  11231. (org--tag-add-to-alist
  11232. (org-get-buffer-tags)
  11233. (org-global-tags-completion-table))
  11234. (org-global-tags-completion-table))))
  11235. (completing-read
  11236. "Tag: " 'org-tags-completion-function nil nil nil
  11237. 'org-tags-history))
  11238. (progn
  11239. (message "[s]et or [r]emove? ")
  11240. (equal (read-char-exclusive) ?r))))
  11241. (when (fboundp 'deactivate-mark) (deactivate-mark))
  11242. (let ((agendap (equal major-mode 'org-agenda-mode))
  11243. l1 l2 m buf pos newhead (cnt 0))
  11244. (goto-char end)
  11245. (setq l2 (1- (org-current-line)))
  11246. (goto-char beg)
  11247. (setq l1 (org-current-line))
  11248. (cl-loop for l from l1 to l2 do
  11249. (org-goto-line l)
  11250. (setq m (get-text-property (point) 'org-hd-marker))
  11251. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  11252. (and agendap m))
  11253. (setq buf (if agendap (marker-buffer m) (current-buffer))
  11254. pos (if agendap m (point)))
  11255. (with-current-buffer buf
  11256. (save-excursion
  11257. (save-restriction
  11258. (goto-char pos)
  11259. (setq cnt (1+ cnt))
  11260. (org-toggle-tag tag (if off 'off 'on))
  11261. (setq newhead (org-get-heading)))))
  11262. (and agendap (org-agenda-change-all-lines newhead m))))
  11263. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  11264. (defun org-tags-completion-function (string _predicate &optional flag)
  11265. "Complete tag STRING.
  11266. FLAG specifies the type of completion operation to perform. This
  11267. function is passed as a collection function to `completing-read',
  11268. which see."
  11269. (let ((completion-ignore-case nil) ;tags are case-sensitive
  11270. (confirm (lambda (x) (stringp (car x))))
  11271. (prefix ""))
  11272. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  11273. (setq prefix (match-string 1 string))
  11274. (setq string (match-string 2 string)))
  11275. (pcase flag
  11276. (`t (all-completions string org-last-tags-completion-table confirm))
  11277. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  11278. (`nil
  11279. (pcase (try-completion string org-last-tags-completion-table confirm)
  11280. ((and completion (pred stringp))
  11281. (concat prefix
  11282. completion
  11283. (if (and org-add-colon-after-tag-completion
  11284. (assoc completion org-last-tags-completion-table))
  11285. ":"
  11286. "")))
  11287. (completion completion)))
  11288. (_ nil))))
  11289. (defun org-fast-tag-insert (kwd tags face &optional end)
  11290. "Insert KWD, and the TAGS, the latter with face FACE.
  11291. Also insert END."
  11292. (insert (format "%-12s" (concat kwd ":"))
  11293. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  11294. (or end "")))
  11295. (defun org-fast-tag-show-exit (flag)
  11296. (save-excursion
  11297. (org-goto-line 3)
  11298. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  11299. (replace-match ""))
  11300. (when flag
  11301. (end-of-line 1)
  11302. (org-move-to-column (- (window-width) 19) t)
  11303. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  11304. (defun org-set-current-tags-overlay (current prefix)
  11305. "Add an overlay to CURRENT tag with PREFIX."
  11306. (let ((s (org-make-tag-string current)))
  11307. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  11308. (org-overlay-display org-tags-overlay (concat prefix s))))
  11309. (defvar org-last-tag-selection-key nil)
  11310. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  11311. "Fast tag selection with single keys.
  11312. CURRENT is the current list of tags in the headline, INHERITED is the
  11313. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  11314. possibly with grouping information. TODO-TABLE is a similar table with
  11315. TODO keywords, should these have keys assigned to them.
  11316. If the keys are nil, a-z are automatically assigned.
  11317. Returns the new tags string, or nil to not change the current settings."
  11318. (let* ((fulltable (append table todo-table))
  11319. (maxlen (if (null fulltable) 0
  11320. (apply #'max
  11321. (mapcar (lambda (x)
  11322. (if (stringp (car x)) (string-width (car x))
  11323. 0))
  11324. fulltable))))
  11325. (buf (current-buffer))
  11326. (expert (eq org-fast-tag-selection-single-key 'expert))
  11327. (buffer-tags nil)
  11328. (fwidth (+ maxlen 3 1 3))
  11329. (ncol (/ (- (window-width) 4) fwidth))
  11330. (i-face 'org-done)
  11331. (c-face 'org-todo)
  11332. tg cnt e c char c1 c2 ntable tbl rtn
  11333. ov-start ov-end ov-prefix
  11334. (exit-after-next org-fast-tag-selection-single-key)
  11335. (done-keywords org-done-keywords)
  11336. groups ingroup intaggroup)
  11337. (save-excursion
  11338. (beginning-of-line)
  11339. (if (looking-at org-tag-line-re)
  11340. (setq ov-start (match-beginning 1)
  11341. ov-end (match-end 1)
  11342. ov-prefix "")
  11343. (setq ov-start (1- (point-at-eol))
  11344. ov-end (1+ ov-start))
  11345. (skip-chars-forward "^\n\r")
  11346. (setq ov-prefix
  11347. (concat
  11348. (buffer-substring (1- (point)) (point))
  11349. (if (> (current-column) org-tags-column)
  11350. " "
  11351. (make-string (- org-tags-column (current-column)) ?\ ))))))
  11352. (move-overlay org-tags-overlay ov-start ov-end)
  11353. (save-excursion
  11354. (save-window-excursion
  11355. (if expert
  11356. (set-buffer (get-buffer-create " *Org tags*"))
  11357. (delete-other-windows)
  11358. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  11359. (org-switch-to-buffer-other-window " *Org tags*"))
  11360. (erase-buffer)
  11361. (setq-local org-done-keywords done-keywords)
  11362. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  11363. (org-fast-tag-insert "Current" current c-face "\n\n")
  11364. (org-fast-tag-show-exit exit-after-next)
  11365. (org-set-current-tags-overlay current ov-prefix)
  11366. (setq tbl fulltable char ?a cnt 0)
  11367. (while (setq e (pop tbl))
  11368. (cond
  11369. ((eq (car e) :startgroup)
  11370. (push '() groups) (setq ingroup t)
  11371. (unless (zerop cnt)
  11372. (setq cnt 0)
  11373. (insert "\n"))
  11374. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11375. ((eq (car e) :endgroup)
  11376. (setq ingroup nil cnt 0)
  11377. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11378. ((eq (car e) :startgrouptag)
  11379. (setq intaggroup t)
  11380. (unless (zerop cnt)
  11381. (setq cnt 0)
  11382. (insert "\n"))
  11383. (insert "[ "))
  11384. ((eq (car e) :endgrouptag)
  11385. (setq intaggroup nil cnt 0)
  11386. (insert "]\n"))
  11387. ((equal e '(:newline))
  11388. (unless (zerop cnt)
  11389. (setq cnt 0)
  11390. (insert "\n")
  11391. (setq e (car tbl))
  11392. (while (equal (car tbl) '(:newline))
  11393. (insert "\n")
  11394. (setq tbl (cdr tbl)))))
  11395. ((equal e '(:grouptags)) (insert " : "))
  11396. (t
  11397. (setq tg (copy-sequence (car e)) c2 nil)
  11398. (if (cdr e)
  11399. (setq c (cdr e))
  11400. ;; automatically assign a character.
  11401. (setq c1 (string-to-char
  11402. (downcase (substring
  11403. tg (if (= (string-to-char tg) ?@) 1 0)))))
  11404. (if (or (rassoc c1 ntable) (rassoc c1 table))
  11405. (while (or (rassoc char ntable) (rassoc char table))
  11406. (setq char (1+ char)))
  11407. (setq c2 c1))
  11408. (setq c (or c2 char)))
  11409. (when ingroup (push tg (car groups)))
  11410. (setq tg (org-add-props tg nil 'face
  11411. (cond
  11412. ((not (assoc tg table))
  11413. (org-get-todo-face tg))
  11414. ((member tg current) c-face)
  11415. ((member tg inherited) i-face))))
  11416. (when (equal (caar tbl) :grouptags)
  11417. (org-add-props tg nil 'face 'org-tag-group))
  11418. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  11419. (insert "[" c "] " tg (make-string
  11420. (- fwidth 4 (length tg)) ?\ ))
  11421. (push (cons tg c) ntable)
  11422. (when (= (cl-incf cnt) ncol)
  11423. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11424. (insert "\n")
  11425. (when (or ingroup intaggroup) (insert " ")))
  11426. (setq cnt 0)))))
  11427. (setq ntable (nreverse ntable))
  11428. (insert "\n")
  11429. (goto-char (point-min))
  11430. (unless expert (org-fit-window-to-buffer))
  11431. (setq rtn
  11432. (catch 'exit
  11433. (while t
  11434. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11435. (if (not groups) "no " "")
  11436. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11437. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11438. (setq org-last-tag-selection-key c)
  11439. (cond
  11440. ((= c ?\r) (throw 'exit t))
  11441. ((= c ?!)
  11442. (setq groups (not groups))
  11443. (goto-char (point-min))
  11444. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11445. ((= c ?\C-c)
  11446. (if (not expert)
  11447. (org-fast-tag-show-exit
  11448. (setq exit-after-next (not exit-after-next)))
  11449. (setq expert nil)
  11450. (delete-other-windows)
  11451. (set-window-buffer (split-window-vertically) " *Org tags*")
  11452. (org-switch-to-buffer-other-window " *Org tags*")
  11453. (org-fit-window-to-buffer)))
  11454. ((or (= c ?\C-g)
  11455. (and (= c ?q) (not (rassoc c ntable))))
  11456. (delete-overlay org-tags-overlay)
  11457. (setq quit-flag t))
  11458. ((= c ?\ )
  11459. (setq current nil)
  11460. (when exit-after-next (setq exit-after-next 'now)))
  11461. ((= c ?\t)
  11462. (condition-case nil
  11463. (setq tg (completing-read
  11464. "Tag: "
  11465. (or buffer-tags
  11466. (with-current-buffer buf
  11467. (setq buffer-tags
  11468. (org-get-buffer-tags))))))
  11469. (quit (setq tg "")))
  11470. (when (string-match "\\S-" tg)
  11471. (cl-pushnew (list tg) buffer-tags :test #'equal)
  11472. (if (member tg current)
  11473. (setq current (delete tg current))
  11474. (push tg current)))
  11475. (when exit-after-next (setq exit-after-next 'now)))
  11476. ((setq e (rassoc c todo-table) tg (car e))
  11477. (with-current-buffer buf
  11478. (save-excursion (org-todo tg)))
  11479. (when exit-after-next (setq exit-after-next 'now)))
  11480. ((setq e (rassoc c ntable) tg (car e))
  11481. (if (member tg current)
  11482. (setq current (delete tg current))
  11483. (cl-loop for g in groups do
  11484. (when (member tg g)
  11485. (dolist (x g) (setq current (delete x current)))))
  11486. (push tg current))
  11487. (when exit-after-next (setq exit-after-next 'now))))
  11488. ;; Create a sorted list
  11489. (setq current
  11490. (sort current
  11491. (lambda (a b)
  11492. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11493. (when (eq exit-after-next 'now) (throw 'exit t))
  11494. (goto-char (point-min))
  11495. (beginning-of-line 2)
  11496. (delete-region (point) (point-at-eol))
  11497. (org-fast-tag-insert "Current" current c-face)
  11498. (org-set-current-tags-overlay current ov-prefix)
  11499. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11500. (while (re-search-forward tag-re nil t)
  11501. (let ((tag (match-string 1)))
  11502. (add-text-properties
  11503. (match-beginning 1) (match-end 1)
  11504. (list 'face
  11505. (cond
  11506. ((member tag current) c-face)
  11507. ((member tag inherited) i-face)
  11508. (t (get-text-property (match-beginning 1) '
  11509. face))))))))
  11510. (goto-char (point-min)))))
  11511. (delete-overlay org-tags-overlay)
  11512. (if rtn
  11513. (mapconcat 'identity current ":")
  11514. nil)))))
  11515. (defun org-make-tag-string (tags)
  11516. "Return string associated to TAGS.
  11517. TAGS is a list of strings."
  11518. (if (null tags) ""
  11519. (format ":%s:" (mapconcat #'identity tags ":"))))
  11520. (defun org--get-local-tags ()
  11521. "Return list of tags for the current headline.
  11522. Assume point is at the beginning of the headline."
  11523. (and (looking-at org-tag-line-re)
  11524. (split-string (match-string-no-properties 2) ":" t)))
  11525. (defun org-get-tags (&optional pos local)
  11526. "Get the list of tags specified in the current headline.
  11527. When argument POS is non-nil, retrieve tags for headline at POS.
  11528. According to `org-use-tag-inheritance', tags may be inherited
  11529. from parent headlines, and from the whole document, through
  11530. `org-file-tags'. In this case, the returned list of tags
  11531. contains tags in this order: file tags, tags inherited from
  11532. parent headlines, local tags.
  11533. However, when optional argument LOCAL is non-nil, only return
  11534. tags specified at the headline.
  11535. Inherited tags have the `inherited' text property."
  11536. (if (and org-trust-scanner-tags
  11537. (or (not pos) (eq pos (point)))
  11538. (not local))
  11539. org-scanner-tags
  11540. (org-with-point-at (or pos (point))
  11541. (unless (org-before-first-heading-p)
  11542. (org-back-to-heading t)
  11543. (let ((ltags (org--get-local-tags)) itags)
  11544. (if (or local (not org-use-tag-inheritance)) ltags
  11545. (while (org-up-heading-safe)
  11546. (setq itags (append (mapcar #'org-add-prop-inherited
  11547. (org--get-local-tags))
  11548. itags)))
  11549. (setq itags (append org-file-tags itags))
  11550. (delete-dups
  11551. (append (org-remove-uninherited-tags itags) ltags))))))))
  11552. (defun org-get-buffer-tags ()
  11553. "Get a table of all tags used in the buffer, for completion."
  11554. (org-with-point-at 1
  11555. (let (tags)
  11556. (while (re-search-forward org-tag-line-re nil t)
  11557. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11558. tags)))
  11559. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11560. ;;;; The mapping API
  11561. (defvar org-agenda-skip-comment-trees)
  11562. (defvar org-agenda-skip-function)
  11563. (defun org-map-entries (func &optional match scope &rest skip)
  11564. "Call FUNC at each headline selected by MATCH in SCOPE.
  11565. FUNC is a function or a lisp form. The function will be called without
  11566. arguments, with the cursor positioned at the beginning of the headline.
  11567. The return values of all calls to the function will be collected and
  11568. returned as a list.
  11569. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  11570. does not need to preserve point. After evaluation, the cursor will be
  11571. moved to the end of the line (presumably of the headline of the
  11572. processed entry) and search continues from there. Under some
  11573. circumstances, this may not produce the wanted results. For example,
  11574. if you have removed (e.g. archived) the current (sub)tree it could
  11575. mean that the next entry will be skipped entirely. In such cases, you
  11576. can specify the position from where search should continue by making
  11577. FUNC set the variable `org-map-continue-from' to the desired buffer
  11578. position.
  11579. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11580. Only headlines that are matched by this query will be considered during
  11581. the iteration. When MATCH is nil or t, all headlines will be
  11582. visited by the iteration.
  11583. SCOPE determines the scope of this command. It can be any of:
  11584. nil The current buffer, respecting the restriction if any
  11585. tree The subtree started with the entry at point
  11586. region The entries within the active region, if any
  11587. region-start-level
  11588. The entries within the active region, but only those at
  11589. the same level than the first one.
  11590. file The current buffer, without restriction
  11591. file-with-archives
  11592. The current buffer, and any archives associated with it
  11593. agenda All agenda files
  11594. agenda-with-archives
  11595. All agenda files with any archive files associated with them
  11596. \(file1 file2 ...)
  11597. If this is a list, all files in the list will be scanned
  11598. The remaining args are treated as settings for the skipping facilities of
  11599. the scanner. The following items can be given here:
  11600. archive skip trees with the archive tag
  11601. comment skip trees with the COMMENT keyword
  11602. function or Emacs Lisp form:
  11603. will be used as value for `org-agenda-skip-function', so
  11604. whenever the function returns a position, FUNC will not be
  11605. called for that entry and search will continue from the
  11606. position returned
  11607. If your function needs to retrieve the tags including inherited tags
  11608. at the *current* entry, you can use the value of the variable
  11609. `org-scanner-tags' which will be much faster than getting the value
  11610. with `org-get-tags'. If your function gets properties with
  11611. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11612. to t around the call to `org-entry-properties' to get the same speedup.
  11613. Note that if your function moves around to retrieve tags and properties at
  11614. a *different* entry, you cannot use these techniques."
  11615. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11616. (not (org-region-active-p)))
  11617. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11618. (org-agenda-skip-archived-trees (memq 'archive skip))
  11619. (org-agenda-skip-comment-trees (memq 'comment skip))
  11620. (org-agenda-skip-function
  11621. (car (org-delete-all '(comment archive) skip)))
  11622. (org-tags-match-list-sublevels t)
  11623. (start-level (eq scope 'region-start-level))
  11624. matcher res
  11625. org-todo-keywords-for-agenda
  11626. org-done-keywords-for-agenda
  11627. org-todo-keyword-alist-for-agenda
  11628. org-tag-alist-for-agenda
  11629. org--matcher-tags-todo-only)
  11630. (cond
  11631. ((eq match t) (setq matcher t))
  11632. ((eq match nil) (setq matcher t))
  11633. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11634. (save-excursion
  11635. (save-restriction
  11636. (cond ((eq scope 'tree)
  11637. (org-back-to-heading t)
  11638. (org-narrow-to-subtree)
  11639. (setq scope nil))
  11640. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11641. (org-region-active-p))
  11642. ;; If needed, set start-level to a string like "2"
  11643. (when start-level
  11644. (save-excursion
  11645. (goto-char (region-beginning))
  11646. (unless (org-at-heading-p) (outline-next-heading))
  11647. (setq start-level (org-current-level))))
  11648. (narrow-to-region (region-beginning)
  11649. (save-excursion
  11650. (goto-char (region-end))
  11651. (unless (and (bolp) (org-at-heading-p))
  11652. (outline-next-heading))
  11653. (point)))
  11654. (setq scope nil)))
  11655. (if (not scope)
  11656. (progn
  11657. (org-agenda-prepare-buffers
  11658. (and buffer-file-name (list buffer-file-name)))
  11659. (setq res
  11660. (org-scan-tags
  11661. func matcher org--matcher-tags-todo-only start-level)))
  11662. ;; Get the right scope
  11663. (cond
  11664. ((and scope (listp scope) (symbolp (car scope)))
  11665. (setq scope (eval scope)))
  11666. ((eq scope 'agenda)
  11667. (setq scope (org-agenda-files t)))
  11668. ((eq scope 'agenda-with-archives)
  11669. (setq scope (org-agenda-files t))
  11670. (setq scope (org-add-archive-files scope)))
  11671. ((eq scope 'file)
  11672. (setq scope (and buffer-file-name (list buffer-file-name))))
  11673. ((eq scope 'file-with-archives)
  11674. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11675. (org-agenda-prepare-buffers scope)
  11676. (dolist (file scope)
  11677. (with-current-buffer (org-find-base-buffer-visiting file)
  11678. (org-with-wide-buffer
  11679. (goto-char (point-min))
  11680. (setq res
  11681. (append
  11682. res
  11683. (org-scan-tags
  11684. func matcher org--matcher-tags-todo-only)))))))))
  11685. res)))
  11686. ;;; Properties API
  11687. (defconst org-special-properties
  11688. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11689. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11690. "The special properties valid in Org mode.
  11691. These are properties that are not defined in the property drawer,
  11692. but in some other way.")
  11693. (defconst org-default-properties
  11694. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11695. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11696. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11697. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11698. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11699. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11700. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11701. "Some properties that are used by Org mode for various purposes.
  11702. Being in this list makes sure that they are offered for completion.")
  11703. (defun org--valid-property-p (property)
  11704. "Non nil when string PROPERTY is a valid property name."
  11705. (not
  11706. (or (equal property "")
  11707. (string-match-p "\\s-" property))))
  11708. (defun org--update-property-plist (key val props)
  11709. "Associate KEY to VAL in alist PROPS.
  11710. Modifications are made by side-effect. Return new alist."
  11711. (let* ((appending (string= (substring key -1) "+"))
  11712. (key (if appending (substring key 0 -1) key))
  11713. (old (assoc-string key props t)))
  11714. (if (not old) (cons (cons key val) props)
  11715. (setcdr old (if appending (concat (cdr old) " " val) val))
  11716. props)))
  11717. (defun org-get-property-block (&optional beg force)
  11718. "Return the (beg . end) range of the body of the property drawer.
  11719. BEG is the beginning of the current subtree, or of the part
  11720. before the first headline. If it is not given, it will be found.
  11721. If the drawer does not exist, create it if FORCE is non-nil, or
  11722. return nil."
  11723. (org-with-wide-buffer
  11724. (when beg (goto-char beg))
  11725. (unless (org-before-first-heading-p)
  11726. (let ((beg (cond (beg)
  11727. ((or (not (featurep 'org-inlinetask))
  11728. (org-inlinetask-in-task-p))
  11729. (org-back-to-heading t))
  11730. (t (org-with-limited-levels (org-back-to-heading t))))))
  11731. (forward-line)
  11732. (when (looking-at-p org-planning-line-re) (forward-line))
  11733. (cond ((looking-at org-property-drawer-re)
  11734. (forward-line)
  11735. (cons (point) (progn (goto-char (match-end 0))
  11736. (line-beginning-position))))
  11737. (force
  11738. (goto-char beg)
  11739. (org-insert-property-drawer)
  11740. (let ((pos (save-excursion (search-forward ":END:")
  11741. (line-beginning-position))))
  11742. (cons pos pos))))))))
  11743. (defun org-at-property-p ()
  11744. "Non-nil when point is inside a property drawer.
  11745. See `org-property-re' for match data, if applicable."
  11746. (save-excursion
  11747. (beginning-of-line)
  11748. (and (looking-at org-property-re)
  11749. (let ((property-drawer (save-match-data (org-get-property-block))))
  11750. (and property-drawer
  11751. (>= (point) (car property-drawer))
  11752. (< (point) (cdr property-drawer)))))))
  11753. (defun org-property-action ()
  11754. "Do an action on properties."
  11755. (interactive)
  11756. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11757. (let ((c (read-char-exclusive)))
  11758. (cl-case c
  11759. (?s (call-interactively #'org-set-property))
  11760. (?d (call-interactively #'org-delete-property))
  11761. (?D (call-interactively #'org-delete-property-globally))
  11762. (?c (call-interactively #'org-compute-property-at-point))
  11763. (otherwise (user-error "No such property action %c" c)))))
  11764. (defun org-inc-effort ()
  11765. "Increment the value of the effort property in the current entry."
  11766. (interactive)
  11767. (org-set-effort t))
  11768. (defvar org-clock-effort) ; Defined in org-clock.el.
  11769. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11770. (defun org-set-effort (&optional increment value)
  11771. "Set the effort property of the current entry.
  11772. If INCREMENT is non-nil, set the property to the next allowed
  11773. value. Otherwise, if optional argument VALUE is provided, use
  11774. it. Eventually, prompt for the new value if none of the previous
  11775. variables is set."
  11776. (interactive "P")
  11777. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11778. (current (org-entry-get nil org-effort-property))
  11779. (value
  11780. (cond
  11781. (increment
  11782. (unless allowed (user-error "Allowed effort values are not set"))
  11783. (or (cl-caadr (member (list current) allowed))
  11784. (user-error "Unknown value %S among allowed values" current)))
  11785. (value
  11786. (if (stringp value) value
  11787. (error "Invalid effort value: %S" value)))
  11788. (t
  11789. (let ((must-match
  11790. (and allowed
  11791. (not (get-text-property 0 'org-unrestricted
  11792. (caar allowed))))))
  11793. (completing-read "Effort: " allowed nil must-match))))))
  11794. (unless (equal current value)
  11795. (org-entry-put nil org-effort-property value))
  11796. (org-refresh-property '((effort . identity)
  11797. (effort-minutes . org-duration-to-minutes))
  11798. value)
  11799. (when (equal (org-get-heading t t t t)
  11800. (bound-and-true-p org-clock-current-task))
  11801. (setq org-clock-effort value)
  11802. (org-clock-update-mode-line))
  11803. (message "%s is now %s" org-effort-property value)))
  11804. (defun org-entry-properties (&optional pom which)
  11805. "Get all properties of the current entry.
  11806. When POM is a buffer position, get all properties from the entry
  11807. there instead.
  11808. This includes the TODO keyword, the tags, time strings for
  11809. deadline, scheduled, and clocking, and any additional properties
  11810. defined in the entry.
  11811. If WHICH is nil or `all', get all properties. If WHICH is
  11812. `special' or `standard', only get that subclass. If WHICH is
  11813. a string, only get that property.
  11814. Return value is an alist. Keys are properties, as upcased
  11815. strings."
  11816. (org-with-point-at pom
  11817. (when (and (derived-mode-p 'org-mode)
  11818. (ignore-errors (org-back-to-heading t)))
  11819. (catch 'exit
  11820. (let* ((beg (point))
  11821. (specific (and (stringp which) (upcase which)))
  11822. (which (cond ((not specific) which)
  11823. ((member specific org-special-properties) 'special)
  11824. (t 'standard)))
  11825. props)
  11826. ;; Get the special properties, like TODO and TAGS.
  11827. (when (memq which '(nil all special))
  11828. (when (or (not specific) (string= specific "CLOCKSUM"))
  11829. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11830. (when clocksum
  11831. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11832. props)))
  11833. (when specific (throw 'exit props)))
  11834. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11835. (let ((clocksumt (get-text-property (point)
  11836. :org-clock-minutes-today)))
  11837. (when clocksumt
  11838. (push (cons "CLOCKSUM_T"
  11839. (org-duration-from-minutes clocksumt))
  11840. props)))
  11841. (when specific (throw 'exit props)))
  11842. (when (or (not specific) (string= specific "ITEM"))
  11843. (let ((case-fold-search nil))
  11844. (when (looking-at org-complex-heading-regexp)
  11845. (push (cons "ITEM"
  11846. (let ((title (match-string-no-properties 4)))
  11847. (if (org-string-nw-p title)
  11848. (org-remove-tabs title)
  11849. "")))
  11850. props)))
  11851. (when specific (throw 'exit props)))
  11852. (when (or (not specific) (string= specific "TODO"))
  11853. (let ((case-fold-search nil))
  11854. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11855. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11856. (when specific (throw 'exit props)))
  11857. (when (or (not specific) (string= specific "PRIORITY"))
  11858. (push (cons "PRIORITY"
  11859. (if (looking-at org-priority-regexp)
  11860. (match-string-no-properties 2)
  11861. (char-to-string org-default-priority)))
  11862. props)
  11863. (when specific (throw 'exit props)))
  11864. (when (or (not specific) (string= specific "FILE"))
  11865. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11866. props)
  11867. (when specific (throw 'exit props)))
  11868. (when (or (not specific) (string= specific "TAGS"))
  11869. (let ((tags (org-get-tags nil t)))
  11870. (when tags
  11871. (push (cons "TAGS" (org-make-tag-string tags))
  11872. props)))
  11873. (when specific (throw 'exit props)))
  11874. (when (or (not specific) (string= specific "ALLTAGS"))
  11875. (let ((tags (org-get-tags)))
  11876. (when tags
  11877. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11878. props)))
  11879. (when specific (throw 'exit props)))
  11880. (when (or (not specific) (string= specific "BLOCKED"))
  11881. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11882. (when specific (throw 'exit props)))
  11883. (when (or (not specific)
  11884. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11885. (forward-line)
  11886. (when (looking-at-p org-planning-line-re)
  11887. (end-of-line)
  11888. (let ((bol (line-beginning-position))
  11889. ;; Backward compatibility: time keywords used to
  11890. ;; be configurable (before 8.3). Make sure we
  11891. ;; get the correct keyword.
  11892. (key-assoc `(("CLOSED" . ,org-closed-string)
  11893. ("DEADLINE" . ,org-deadline-string)
  11894. ("SCHEDULED" . ,org-scheduled-string))))
  11895. (dolist (pair (if specific (list (assoc specific key-assoc))
  11896. key-assoc))
  11897. (save-excursion
  11898. (when (search-backward (cdr pair) bol t)
  11899. (goto-char (match-end 0))
  11900. (skip-chars-forward " \t")
  11901. (and (looking-at org-ts-regexp-both)
  11902. (push (cons (car pair)
  11903. (match-string-no-properties 0))
  11904. props)))))))
  11905. (when specific (throw 'exit props)))
  11906. (when (or (not specific)
  11907. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11908. (let ((find-ts
  11909. (lambda (end ts)
  11910. ;; Fix next time-stamp before END. TS is the
  11911. ;; list of time-stamps found so far.
  11912. (let ((ts ts)
  11913. (regexp (cond
  11914. ((string= specific "TIMESTAMP")
  11915. org-ts-regexp)
  11916. ((string= specific "TIMESTAMP_IA")
  11917. org-ts-regexp-inactive)
  11918. ((assoc "TIMESTAMP_IA" ts)
  11919. org-ts-regexp)
  11920. ((assoc "TIMESTAMP" ts)
  11921. org-ts-regexp-inactive)
  11922. (t org-ts-regexp-both))))
  11923. (catch 'next
  11924. (while (re-search-forward regexp end t)
  11925. (backward-char)
  11926. (let ((object (org-element-context)))
  11927. ;; Accept to match timestamps in node
  11928. ;; properties, too.
  11929. (when (memq (org-element-type object)
  11930. '(node-property timestamp))
  11931. (let ((type
  11932. (org-element-property :type object)))
  11933. (cond
  11934. ((and (memq type '(active active-range))
  11935. (not (equal specific "TIMESTAMP_IA")))
  11936. (unless (assoc "TIMESTAMP" ts)
  11937. (push (cons "TIMESTAMP"
  11938. (org-element-property
  11939. :raw-value object))
  11940. ts)
  11941. (when specific (throw 'exit ts))))
  11942. ((and (memq type '(inactive inactive-range))
  11943. (not (string= specific "TIMESTAMP")))
  11944. (unless (assoc "TIMESTAMP_IA" ts)
  11945. (push (cons "TIMESTAMP_IA"
  11946. (org-element-property
  11947. :raw-value object))
  11948. ts)
  11949. (when specific (throw 'exit ts))))))
  11950. ;; Both timestamp types are found,
  11951. ;; move to next part.
  11952. (when (= (length ts) 2) (throw 'next ts)))))
  11953. ts)))))
  11954. (goto-char beg)
  11955. ;; First look for timestamps within headline.
  11956. (let ((ts (funcall find-ts (line-end-position) nil)))
  11957. (if (= (length ts) 2) (setq props (nconc ts props))
  11958. ;; Then find timestamps in the section, skipping
  11959. ;; planning line.
  11960. (let ((end (save-excursion (outline-next-heading))))
  11961. (forward-line)
  11962. (when (looking-at-p org-planning-line-re) (forward-line))
  11963. (setq props (nconc (funcall find-ts end ts) props))))))))
  11964. ;; Get the standard properties, like :PROP:.
  11965. (when (memq which '(nil all standard))
  11966. ;; If we are looking after a specific property, delegate
  11967. ;; to `org-entry-get', which is faster. However, make an
  11968. ;; exception for "CATEGORY", since it can be also set
  11969. ;; through keywords (i.e. #+CATEGORY).
  11970. (if (and specific (not (equal specific "CATEGORY")))
  11971. (let ((value (org-entry-get beg specific nil t)))
  11972. (throw 'exit (and value (list (cons specific value)))))
  11973. (let ((range (org-get-property-block beg)))
  11974. (when range
  11975. (let ((end (cdr range)) seen-base)
  11976. (goto-char (car range))
  11977. ;; Unlike to `org--update-property-plist', we
  11978. ;; handle the case where base values is found
  11979. ;; after its extension. We also forbid standard
  11980. ;; properties to be named as special properties.
  11981. (while (re-search-forward org-property-re end t)
  11982. (let* ((key (upcase (match-string-no-properties 2)))
  11983. (extendp (string-match-p "\\+\\'" key))
  11984. (key-base (if extendp (substring key 0 -1) key))
  11985. (value (match-string-no-properties 3)))
  11986. (cond
  11987. ((member-ignore-case key-base org-special-properties))
  11988. (extendp
  11989. (setq props
  11990. (org--update-property-plist key value props)))
  11991. ((member key seen-base))
  11992. (t (push key seen-base)
  11993. (let ((p (assoc-string key props t)))
  11994. (if p (setcdr p (concat value " " (cdr p)))
  11995. (push (cons key value) props))))))))))))
  11996. (unless (assoc "CATEGORY" props)
  11997. (push (cons "CATEGORY" (org-get-category beg)) props)
  11998. (when (string= specific "CATEGORY") (throw 'exit props)))
  11999. ;; Return value.
  12000. props)))))
  12001. (defun org--property-local-values (property literal-nil)
  12002. "Return value for PROPERTY in current entry.
  12003. Value is a list whose car is the base value for PROPERTY and cdr
  12004. a list of accumulated values. Return nil if neither is found in
  12005. the entry. Also return nil when PROPERTY is set to \"nil\",
  12006. unless LITERAL-NIL is non-nil."
  12007. (let ((range (org-get-property-block)))
  12008. (when range
  12009. (goto-char (car range))
  12010. (let* ((case-fold-search t)
  12011. (end (cdr range))
  12012. (value
  12013. ;; Base value.
  12014. (save-excursion
  12015. (let ((v (and (re-search-forward
  12016. (org-re-property property nil t) end t)
  12017. (match-string-no-properties 3))))
  12018. (list (if literal-nil v (org-not-nil v)))))))
  12019. ;; Find additional values.
  12020. (let* ((property+ (org-re-property (concat property "+") nil t)))
  12021. (while (re-search-forward property+ end t)
  12022. (push (match-string-no-properties 3) value)))
  12023. ;; Return final values.
  12024. (and (not (equal value '(nil))) (nreverse value))))))
  12025. (defun org--property-global-value (property literal-nil)
  12026. "Return value for PROPERTY in current buffer.
  12027. Return value is a string. Return nil if property is not set
  12028. globally. Also return nil when PROPERTY is set to \"nil\",
  12029. unless LITERAL-NIL is non-nil."
  12030. (let ((global
  12031. (cdr (or (assoc-string property org-file-properties t)
  12032. (assoc-string property org-global-properties t)
  12033. (assoc-string property org-global-properties-fixed t)))))
  12034. (if literal-nil global (org-not-nil global))))
  12035. (defun org-entry-get (pom property &optional inherit literal-nil)
  12036. "Get value of PROPERTY for entry or content at point-or-marker POM.
  12037. If INHERIT is non-nil and the entry does not have the property,
  12038. then also check higher levels of the hierarchy. If INHERIT is
  12039. the symbol `selective', use inheritance only if the setting in
  12040. `org-use-property-inheritance' selects PROPERTY for inheritance.
  12041. If the property is present but empty, the return value is the
  12042. empty string. If the property is not present at all, nil is
  12043. returned. In any other case, return the value as a string.
  12044. Search is case-insensitive.
  12045. If LITERAL-NIL is set, return the string value \"nil\" as
  12046. a string, do not interpret it as the list atom nil. This is used
  12047. for inheritance when a \"nil\" value can supersede a non-nil
  12048. value higher up the hierarchy."
  12049. (org-with-point-at pom
  12050. (cond
  12051. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  12052. ;; We need a special property. Use `org-entry-properties' to
  12053. ;; retrieve it, but specify the wanted property.
  12054. (cdr (assoc-string property (org-entry-properties nil property))))
  12055. ((and inherit
  12056. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  12057. (org-entry-get-with-inheritance property literal-nil))
  12058. (t
  12059. (let* ((local (org--property-local-values property literal-nil))
  12060. (value (and local (mapconcat #'identity (delq nil local) " "))))
  12061. (if literal-nil value (org-not-nil value)))))))
  12062. (defun org-property-or-variable-value (var &optional inherit)
  12063. "Check if there is a property fixing the value of VAR.
  12064. If yes, return this value. If not, return the current value of the variable."
  12065. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  12066. (if (and prop (stringp prop) (string-match "\\S-" prop))
  12067. (read prop)
  12068. (symbol-value var))))
  12069. (defun org-entry-delete (pom property)
  12070. "Delete PROPERTY from entry at point-or-marker POM.
  12071. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  12072. non-nil when a property was removed."
  12073. (org-with-point-at pom
  12074. (pcase (org-get-property-block)
  12075. (`(,begin . ,origin)
  12076. (let* ((end (copy-marker origin))
  12077. (re (org-re-property
  12078. (concat (regexp-quote property) "\\+?") t t)))
  12079. (goto-char begin)
  12080. (while (re-search-forward re end t)
  12081. (delete-region (match-beginning 0) (line-beginning-position 2)))
  12082. ;; If drawer is empty, remove it altogether.
  12083. (when (= begin end)
  12084. (delete-region (line-beginning-position 0)
  12085. (line-beginning-position 2)))
  12086. ;; Return non-nil if some property was removed.
  12087. (prog1 (/= end origin) (set-marker end nil))))
  12088. (_ nil))))
  12089. ;; Multi-values properties are properties that contain multiple values
  12090. ;; These values are assumed to be single words, separated by whitespace.
  12091. (defun org-entry-add-to-multivalued-property (pom property value)
  12092. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  12093. (let* ((old (org-entry-get pom property))
  12094. (values (and old (split-string old))))
  12095. (setq value (org-entry-protect-space value))
  12096. (unless (member value values)
  12097. (setq values (append values (list value)))
  12098. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12099. (defun org-entry-remove-from-multivalued-property (pom property value)
  12100. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  12101. (let* ((old (org-entry-get pom property))
  12102. (values (and old (split-string old))))
  12103. (setq value (org-entry-protect-space value))
  12104. (when (member value values)
  12105. (setq values (delete value values))
  12106. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12107. (defun org-entry-member-in-multivalued-property (pom property value)
  12108. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  12109. (let* ((old (org-entry-get pom property))
  12110. (values (and old (split-string old))))
  12111. (setq value (org-entry-protect-space value))
  12112. (member value values)))
  12113. (defun org-entry-get-multivalued-property (pom property)
  12114. "Return a list of values in a multivalued property."
  12115. (let* ((value (org-entry-get pom property))
  12116. (values (and value (split-string value))))
  12117. (mapcar #'org-entry-restore-space values)))
  12118. (defun org-entry-put-multivalued-property (pom property &rest values)
  12119. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  12120. VALUES should be a list of strings. Spaces will be protected."
  12121. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  12122. (let* ((value (org-entry-get pom property))
  12123. (values (and value (split-string value))))
  12124. (mapcar #'org-entry-restore-space values)))
  12125. (defun org-entry-protect-space (s)
  12126. "Protect spaces and newline in string S."
  12127. (while (string-match " " s)
  12128. (setq s (replace-match "%20" t t s)))
  12129. (while (string-match "\n" s)
  12130. (setq s (replace-match "%0A" t t s)))
  12131. s)
  12132. (defun org-entry-restore-space (s)
  12133. "Restore spaces and newline in string S."
  12134. (while (string-match "%20" s)
  12135. (setq s (replace-match " " t t s)))
  12136. (while (string-match "%0A" s)
  12137. (setq s (replace-match "\n" t t s)))
  12138. s)
  12139. (defvar org-entry-property-inherited-from (make-marker)
  12140. "Marker pointing to the entry from where a property was inherited.
  12141. Each call to `org-entry-get-with-inheritance' will set this marker to the
  12142. location of the entry where the inheritance search matched. If there was
  12143. no match, the marker will point nowhere.
  12144. Note that also `org-entry-get' calls this function, if the INHERIT flag
  12145. is set.")
  12146. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  12147. "Get PROPERTY of entry or content at point, search higher levels if needed.
  12148. The search will stop at the first ancestor which has the property defined.
  12149. If the value found is \"nil\", return nil to show that the property
  12150. should be considered as undefined (this is the meaning of nil here).
  12151. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  12152. (move-marker org-entry-property-inherited-from nil)
  12153. (org-with-wide-buffer
  12154. (let (value)
  12155. (catch 'exit
  12156. (while t
  12157. (let ((v (org--property-local-values property literal-nil)))
  12158. (when v
  12159. (setq value
  12160. (concat (mapconcat #'identity (delq nil v) " ")
  12161. (and value " ")
  12162. value)))
  12163. (cond
  12164. ((car v)
  12165. (org-back-to-heading t)
  12166. (move-marker org-entry-property-inherited-from (point))
  12167. (throw 'exit nil))
  12168. ((org-up-heading-safe))
  12169. (t
  12170. (let ((global (org--property-global-value property literal-nil)))
  12171. (cond ((not global))
  12172. (value (setq value (concat global " " value)))
  12173. (t (setq value global))))
  12174. (throw 'exit nil))))))
  12175. (if literal-nil value (org-not-nil value)))))
  12176. (defvar org-property-changed-functions nil
  12177. "Hook called when the value of a property has changed.
  12178. Each hook function should accept two arguments, the name of the property
  12179. and the new value.")
  12180. (defun org-entry-put (pom property value)
  12181. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  12182. If the value is nil, it is converted to the empty string. If it
  12183. is not a string, an error is raised. Also raise an error on
  12184. invalid property names.
  12185. PROPERTY can be any regular property (see
  12186. `org-special-properties'). It can also be \"TODO\",
  12187. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  12188. For the last two properties, VALUE may have any of the special
  12189. values \"earlier\" and \"later\". The function then increases or
  12190. decreases scheduled or deadline date by one day."
  12191. (cond ((null value) (setq value ""))
  12192. ((not (stringp value)) (error "Properties values should be strings"))
  12193. ((not (org--valid-property-p property))
  12194. (user-error "Invalid property name: \"%s\"" property)))
  12195. (org-with-point-at pom
  12196. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12197. (org-back-to-heading t)
  12198. (org-with-limited-levels (org-back-to-heading t)))
  12199. (let ((beg (point)))
  12200. (cond
  12201. ((equal property "TODO")
  12202. (cond ((not (org-string-nw-p value)) (setq value 'none))
  12203. ((not (member value org-todo-keywords-1))
  12204. (user-error "\"%s\" is not a valid TODO state" value)))
  12205. (org-todo value)
  12206. (org-align-tags))
  12207. ((equal property "PRIORITY")
  12208. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  12209. (org-align-tags))
  12210. ((equal property "SCHEDULED")
  12211. (forward-line)
  12212. (if (and (looking-at-p org-planning-line-re)
  12213. (re-search-forward
  12214. org-scheduled-time-regexp (line-end-position) t))
  12215. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12216. ((string= value "later") (org-timestamp-change 1 'day))
  12217. ((string= value "") (org-schedule '(4)))
  12218. (t (org-schedule nil value)))
  12219. (if (member value '("earlier" "later" ""))
  12220. (call-interactively #'org-schedule)
  12221. (org-schedule nil value))))
  12222. ((equal property "DEADLINE")
  12223. (forward-line)
  12224. (if (and (looking-at-p org-planning-line-re)
  12225. (re-search-forward
  12226. org-deadline-time-regexp (line-end-position) t))
  12227. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12228. ((string= value "later") (org-timestamp-change 1 'day))
  12229. ((string= value "") (org-deadline '(4)))
  12230. (t (org-deadline nil value)))
  12231. (if (member value '("earlier" "later" ""))
  12232. (call-interactively #'org-deadline)
  12233. (org-deadline nil value))))
  12234. ((member property org-special-properties)
  12235. (error "The %s property cannot be set with `org-entry-put'" property))
  12236. (t
  12237. (let* ((range (org-get-property-block beg 'force))
  12238. (end (cdr range))
  12239. (case-fold-search t))
  12240. (goto-char (car range))
  12241. (if (re-search-forward (org-re-property property nil t) end t)
  12242. (progn (delete-region (match-beginning 0) (match-end 0))
  12243. (goto-char (match-beginning 0)))
  12244. (goto-char end)
  12245. (insert "\n")
  12246. (backward-char))
  12247. (insert ":" property ":")
  12248. (when value (insert " " value))
  12249. (org-indent-line)))))
  12250. (run-hook-with-args 'org-property-changed-functions property value)))
  12251. (defun org-buffer-property-keys (&optional specials defaults columns)
  12252. "Get all property keys in the current buffer.
  12253. When SPECIALS is non-nil, also list the special properties that
  12254. reflect things like tags and TODO state.
  12255. When DEFAULTS is non-nil, also include properties that has
  12256. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  12257. DESCRIPTION, LOCATION, and LOGGING and others.
  12258. When COLUMNS in non-nil, also include property names given in
  12259. COLUMN formats in the current buffer."
  12260. (let ((case-fold-search t)
  12261. (props (append
  12262. (and specials org-special-properties)
  12263. (and defaults (cons org-effort-property org-default-properties))
  12264. nil)))
  12265. (org-with-wide-buffer
  12266. (goto-char (point-min))
  12267. (while (re-search-forward org-property-start-re nil t)
  12268. (catch :skip
  12269. (let ((range (org-get-property-block)))
  12270. (unless range (throw :skip nil))
  12271. (goto-char (car range))
  12272. (let ((begin (car range))
  12273. (end (cdr range)))
  12274. ;; Make sure that found property block is not located
  12275. ;; before current point, as it would generate an infloop.
  12276. ;; It can happen, for example, in the following
  12277. ;; situation:
  12278. ;;
  12279. ;; * Headline
  12280. ;; :PROPERTIES:
  12281. ;; ...
  12282. ;; :END:
  12283. ;; *************** Inlinetask
  12284. ;; #+BEGIN_EXAMPLE
  12285. ;; :PROPERTIES:
  12286. ;; #+END_EXAMPLE
  12287. ;;
  12288. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  12289. (while (< (point) end)
  12290. (let ((p (progn (looking-at org-property-re)
  12291. (match-string-no-properties 2))))
  12292. ;; Only add true property name, not extension symbol.
  12293. (push (if (not (string-match-p "\\+\\'" p)) p
  12294. (substring p 0 -1))
  12295. props))
  12296. (forward-line))))
  12297. (outline-next-heading)))
  12298. (when columns
  12299. (goto-char (point-min))
  12300. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  12301. (let ((element (org-element-at-point)))
  12302. (when (memq (org-element-type element) '(keyword node-property))
  12303. (let ((value (org-element-property :value element))
  12304. (start 0))
  12305. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  12306. \\(?:{[^}]+}\\)?"
  12307. value start)
  12308. (setq start (match-end 0))
  12309. (let ((p (match-string-no-properties 1 value)))
  12310. (unless (member-ignore-case p org-special-properties)
  12311. (push p props))))))))))
  12312. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  12313. (defun org-property-values (key)
  12314. "List all non-nil values of property KEY in current buffer."
  12315. (org-with-wide-buffer
  12316. (goto-char (point-min))
  12317. (let ((case-fold-search t)
  12318. (re (org-re-property key))
  12319. values)
  12320. (while (re-search-forward re nil t)
  12321. (push (org-entry-get (point) key) values))
  12322. (delete-dups values))))
  12323. (defun org-insert-property-drawer ()
  12324. "Insert a property drawer into the current entry.
  12325. Do nothing if the drawer already exists. The newly created
  12326. drawer is immediately hidden."
  12327. (org-with-wide-buffer
  12328. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12329. (org-back-to-heading t)
  12330. (org-with-limited-levels (org-back-to-heading t)))
  12331. (forward-line)
  12332. (when (looking-at-p org-planning-line-re) (forward-line))
  12333. (unless (looking-at-p org-property-drawer-re)
  12334. ;; Make sure we start editing a line from current entry, not from
  12335. ;; next one. It prevents extending text properties or overlays
  12336. ;; belonging to the latter.
  12337. (when (bolp) (backward-char))
  12338. (let ((begin (1+ (point)))
  12339. (inhibit-read-only t))
  12340. (insert "\n:PROPERTIES:\n:END:")
  12341. (org-flag-drawer t nil (line-end-position 0) (point))
  12342. (when (eobp) (insert "\n"))
  12343. (org-indent-region begin (point))))))
  12344. (defun org-insert-drawer (&optional arg drawer)
  12345. "Insert a drawer at point.
  12346. When optional argument ARG is non-nil, insert a property drawer.
  12347. Optional argument DRAWER, when non-nil, is a string representing
  12348. drawer's name. Otherwise, the user is prompted for a name.
  12349. If a region is active, insert the drawer around that region
  12350. instead.
  12351. Point is left between drawer's boundaries."
  12352. (interactive "P")
  12353. (let* ((drawer (if arg "PROPERTIES"
  12354. (or drawer (read-from-minibuffer "Drawer: ")))))
  12355. (cond
  12356. ;; With C-u, fall back on `org-insert-property-drawer'
  12357. (arg (org-insert-property-drawer))
  12358. ;; Check validity of suggested drawer's name.
  12359. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  12360. (user-error "Invalid drawer name"))
  12361. ;; With an active region, insert a drawer at point.
  12362. ((not (org-region-active-p))
  12363. (progn
  12364. (unless (bolp) (insert "\n"))
  12365. (insert (format ":%s:\n\n:END:\n" drawer))
  12366. (forward-line -2)))
  12367. ;; Otherwise, insert the drawer at point
  12368. (t
  12369. (let ((rbeg (region-beginning))
  12370. (rend (copy-marker (region-end))))
  12371. (unwind-protect
  12372. (progn
  12373. (goto-char rbeg)
  12374. (beginning-of-line)
  12375. (when (save-excursion
  12376. (re-search-forward org-outline-regexp-bol rend t))
  12377. (user-error "Drawers cannot contain headlines"))
  12378. ;; Position point at the beginning of the first
  12379. ;; non-blank line in region. Insert drawer's opening
  12380. ;; there, then indent it.
  12381. (org-skip-whitespace)
  12382. (beginning-of-line)
  12383. (insert ":" drawer ":\n")
  12384. (forward-line -1)
  12385. (indent-for-tab-command)
  12386. ;; Move point to the beginning of the first blank line
  12387. ;; after the last non-blank line in region. Insert
  12388. ;; drawer's closing, then indent it.
  12389. (goto-char rend)
  12390. (skip-chars-backward " \r\t\n")
  12391. (insert "\n:END:")
  12392. (deactivate-mark t)
  12393. (indent-for-tab-command)
  12394. (unless (eolp) (insert "\n")))
  12395. ;; Clear marker, whatever the outcome of insertion is.
  12396. (set-marker rend nil)))))))
  12397. (defvar org-property-set-functions-alist nil
  12398. "Property set function alist.
  12399. Each entry should have the following format:
  12400. (PROPERTY . READ-FUNCTION)
  12401. The read function will be called with the same argument as
  12402. `org-completing-read'.")
  12403. (defun org-set-property-function (property)
  12404. "Get the function that should be used to set PROPERTY.
  12405. This is computed according to `org-property-set-functions-alist'."
  12406. (or (cdr (assoc property org-property-set-functions-alist))
  12407. 'org-completing-read))
  12408. (defun org-read-property-value (property &optional pom)
  12409. "Read value for PROPERTY, as a string.
  12410. When optional argument POM is non-nil, completion uses additional
  12411. information, i.e., allowed or existing values at point or marker
  12412. POM."
  12413. (let* ((completion-ignore-case t)
  12414. (allowed
  12415. (or (org-property-get-allowed-values nil property 'table)
  12416. (and pom (org-property-get-allowed-values pom property 'table))))
  12417. (current (org-entry-get nil property))
  12418. (prompt (format "%s value%s: "
  12419. property
  12420. (if (org-string-nw-p current)
  12421. (format " [%s]" current)
  12422. "")))
  12423. (set-function (org-set-property-function property)))
  12424. (org-trim
  12425. (if allowed
  12426. (funcall set-function
  12427. prompt allowed nil
  12428. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  12429. (let ((all (mapcar #'list
  12430. (append (org-property-values property)
  12431. (and pom
  12432. (org-with-point-at pom
  12433. (org-property-values property)))))))
  12434. (funcall set-function prompt all nil nil "" nil current))))))
  12435. (defvar org-last-set-property nil)
  12436. (defvar org-last-set-property-value nil)
  12437. (defun org-read-property-name ()
  12438. "Read a property name."
  12439. (let ((completion-ignore-case t)
  12440. (default-prop (or (and (org-at-property-p)
  12441. (match-string-no-properties 2))
  12442. org-last-set-property)))
  12443. (org-completing-read
  12444. (concat "Property"
  12445. (if default-prop (concat " [" default-prop "]") "")
  12446. ": ")
  12447. (mapcar #'list (org-buffer-property-keys nil t t))
  12448. nil nil nil nil default-prop)))
  12449. (defun org-set-property-and-value (use-last)
  12450. "Allow to set [PROPERTY]: [value] direction from prompt.
  12451. When use-default, don't even ask, just use the last
  12452. \"[PROPERTY]: [value]\" string from the history."
  12453. (interactive "P")
  12454. (let* ((completion-ignore-case t)
  12455. (pv (or (and use-last org-last-set-property-value)
  12456. (org-completing-read
  12457. "Enter a \"[Property]: [value]\" pair: "
  12458. nil nil nil nil nil
  12459. org-last-set-property-value)))
  12460. prop val)
  12461. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12462. (setq prop (match-string 1 pv)
  12463. val (match-string 2 pv))
  12464. (org-set-property prop val))))
  12465. (defun org-set-property (property value)
  12466. "In the current entry, set PROPERTY to VALUE.
  12467. When called interactively, this will prompt for a property name, offering
  12468. completion on existing and default properties. And then it will prompt
  12469. for a value, offering completion either on allowed values (via an inherited
  12470. xxx_ALL property) or on existing values in other instances of this property
  12471. in the current file.
  12472. Throw an error when trying to set a property with an invalid name."
  12473. (interactive (list nil nil))
  12474. (let ((property (or property (org-read-property-name))))
  12475. ;; `org-entry-put' also makes the following check, but this one
  12476. ;; avoids polluting `org-last-set-property' and
  12477. ;; `org-last-set-property-value' needlessly.
  12478. (unless (org--valid-property-p property)
  12479. (user-error "Invalid property name: \"%s\"" property))
  12480. (let ((value (or value (org-read-property-value property)))
  12481. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12482. (setq org-last-set-property property)
  12483. (setq org-last-set-property-value (concat property ": " value))
  12484. ;; Possibly postprocess the inserted value:
  12485. (when fn (setq value (funcall fn value)))
  12486. (unless (equal (org-entry-get nil property) value)
  12487. (org-entry-put nil property value)))))
  12488. (defun org-find-property (property &optional value)
  12489. "Find first entry in buffer that sets PROPERTY.
  12490. When optional argument VALUE is non-nil, only consider an entry
  12491. if it contains PROPERTY set to this value. If PROPERTY should be
  12492. explicitly set to nil, use string \"nil\" for VALUE.
  12493. Return position where the entry begins, or nil if there is no
  12494. such entry. If narrowing is in effect, only search the visible
  12495. part of the buffer."
  12496. (save-excursion
  12497. (goto-char (point-min))
  12498. (let ((case-fold-search t)
  12499. (re (org-re-property property nil (not value) value)))
  12500. (catch 'exit
  12501. (while (re-search-forward re nil t)
  12502. (when (if value (org-at-property-p)
  12503. (org-entry-get (point) property nil t))
  12504. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  12505. (defun org-delete-property (property)
  12506. "In the current entry, delete PROPERTY."
  12507. (interactive
  12508. (let* ((completion-ignore-case t)
  12509. (cat (org-entry-get (point) "CATEGORY"))
  12510. (props0 (org-entry-properties nil 'standard))
  12511. (props (if cat props0
  12512. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12513. (prop (if (< 1 (length props))
  12514. (completing-read "Property: " props nil t)
  12515. (caar props))))
  12516. (list prop)))
  12517. (if (not property)
  12518. (message "No property to delete in this entry")
  12519. (org-entry-delete nil property)
  12520. (message "Property \"%s\" deleted" property)))
  12521. (defun org-delete-property-globally (property)
  12522. "Remove PROPERTY globally, from all entries.
  12523. This function ignores narrowing, if any."
  12524. (interactive
  12525. (let* ((completion-ignore-case t)
  12526. (prop (completing-read
  12527. "Globally remove property: "
  12528. (mapcar #'list (org-buffer-property-keys)))))
  12529. (list prop)))
  12530. (org-with-wide-buffer
  12531. (goto-char (point-min))
  12532. (let ((count 0)
  12533. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12534. (while (re-search-forward re nil t)
  12535. (when (org-entry-delete (point) property) (cl-incf count)))
  12536. (message "Property \"%s\" removed from %d entries" property count))))
  12537. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12538. (defun org-compute-property-at-point ()
  12539. "Compute the property at point.
  12540. This looks for an enclosing column format, extracts the operator and
  12541. then applies it to the property in the column format's scope."
  12542. (interactive)
  12543. (unless (org-at-property-p)
  12544. (user-error "Not at a property"))
  12545. (let ((prop (match-string-no-properties 2)))
  12546. (org-columns-get-format-and-top-level)
  12547. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12548. (user-error "No operator defined for property %s" prop))
  12549. (org-columns-compute prop)))
  12550. (defvar org-property-allowed-value-functions nil
  12551. "Hook for functions supplying allowed values for a specific property.
  12552. The functions must take a single argument, the name of the property, and
  12553. return a flat list of allowed values. If \":ETC\" is one of
  12554. the values, this means that these values are intended as defaults for
  12555. completion, but that other values should be allowed too.
  12556. The functions must return nil if they are not responsible for this
  12557. property.")
  12558. (defun org-property-get-allowed-values (pom property &optional table)
  12559. "Get allowed values for the property PROPERTY.
  12560. When TABLE is non-nil, return an alist that can directly be used for
  12561. completion."
  12562. (let (vals)
  12563. (cond
  12564. ((equal property "TODO")
  12565. (setq vals (org-with-point-at pom
  12566. (append org-todo-keywords-1 '("")))))
  12567. ((equal property "PRIORITY")
  12568. (let ((n org-lowest-priority))
  12569. (while (>= n org-highest-priority)
  12570. (push (char-to-string n) vals)
  12571. (setq n (1- n)))))
  12572. ((equal property "CATEGORY"))
  12573. ((member property org-special-properties))
  12574. ((setq vals (run-hook-with-args-until-success
  12575. 'org-property-allowed-value-functions property)))
  12576. (t
  12577. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12578. (when (and vals (string-match "\\S-" vals))
  12579. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12580. (setq vals (mapcar (lambda (x)
  12581. (cond ((stringp x) x)
  12582. ((numberp x) (number-to-string x))
  12583. ((symbolp x) (symbol-name x))
  12584. (t "???")))
  12585. vals)))))
  12586. (when (member ":ETC" vals)
  12587. (setq vals (remove ":ETC" vals))
  12588. (org-add-props (car vals) '(org-unrestricted t)))
  12589. (if table (mapcar 'list vals) vals)))
  12590. (defun org-property-previous-allowed-value (&optional _previous)
  12591. "Switch to the next allowed value for this property."
  12592. (interactive)
  12593. (org-property-next-allowed-value t))
  12594. (defun org-property-next-allowed-value (&optional previous)
  12595. "Switch to the next allowed value for this property."
  12596. (interactive)
  12597. (unless (org-at-property-p)
  12598. (user-error "Not at a property"))
  12599. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12600. (key (match-string 2))
  12601. (value (match-string 3))
  12602. (allowed (or (org-property-get-allowed-values (point) key)
  12603. (and (member value '("[ ]" "[-]" "[X]"))
  12604. '("[ ]" "[X]"))))
  12605. (heading (save-match-data (nth 4 (org-heading-components))))
  12606. nval)
  12607. (unless allowed
  12608. (user-error "Allowed values for this property have not been defined"))
  12609. (when previous (setq allowed (reverse allowed)))
  12610. (when (member value allowed)
  12611. (setq nval (car (cdr (member value allowed)))))
  12612. (setq nval (or nval (car allowed)))
  12613. (when (equal nval value)
  12614. (user-error "Only one allowed value for this property"))
  12615. (org-at-property-p)
  12616. (replace-match (concat " :" key ": " nval) t t)
  12617. (org-indent-line)
  12618. (beginning-of-line 1)
  12619. (skip-chars-forward " \t")
  12620. (when (equal prop org-effort-property)
  12621. (org-refresh-property
  12622. '((effort . identity)
  12623. (effort-minutes . org-duration-to-minutes))
  12624. nval)
  12625. (when (string= org-clock-current-task heading)
  12626. (setq org-clock-effort nval)
  12627. (org-clock-update-mode-line)))
  12628. (run-hook-with-args 'org-property-changed-functions key nval)))
  12629. (defun org-find-olp (path &optional this-buffer)
  12630. "Return a marker pointing to the entry at outline path OLP.
  12631. If anything goes wrong, throw an error.
  12632. You can wrap this call to catch the error like this:
  12633. (condition-case msg
  12634. (org-mobile-locate-entry (match-string 4))
  12635. (error (nth 1 msg)))
  12636. The return value will then be either a string with the error message,
  12637. or a marker if everything is OK.
  12638. If THIS-BUFFER is set, the outline path does not contain a file,
  12639. only headings."
  12640. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12641. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12642. (level 1)
  12643. (lmin 1)
  12644. (lmax 1)
  12645. end found flevel)
  12646. (unless buffer (error "File not found :%s" file))
  12647. (with-current-buffer buffer
  12648. (unless (derived-mode-p 'org-mode)
  12649. (error "Buffer %s needs to be in Org mode" buffer))
  12650. (org-with-wide-buffer
  12651. (goto-char (point-min))
  12652. (dolist (heading path)
  12653. (let ((re (format org-complex-heading-regexp-format
  12654. (regexp-quote heading)))
  12655. (cnt 0))
  12656. (while (re-search-forward re end t)
  12657. (setq level (- (match-end 1) (match-beginning 1)))
  12658. (when (and (>= level lmin) (<= level lmax))
  12659. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12660. (when (= cnt 0)
  12661. (error "Heading not found on level %d: %s" lmax heading))
  12662. (when (> cnt 1)
  12663. (error "Heading not unique on level %d: %s" lmax heading))
  12664. (goto-char found)
  12665. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12666. (setq end (save-excursion (org-end-of-subtree t t)))))
  12667. (when (org-at-heading-p)
  12668. (point-marker))))))
  12669. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12670. "Find node HEADING in BUFFER.
  12671. Return a marker to the heading if it was found, or nil if not.
  12672. If POS-ONLY is set, return just the position instead of a marker.
  12673. The heading text must match exact, but it may have a TODO keyword,
  12674. a priority cookie and tags in the standard locations."
  12675. (with-current-buffer (or buffer (current-buffer))
  12676. (org-with-wide-buffer
  12677. (goto-char (point-min))
  12678. (let (case-fold-search)
  12679. (when (re-search-forward
  12680. (format org-complex-heading-regexp-format
  12681. (regexp-quote heading)) nil t)
  12682. (if pos-only
  12683. (match-beginning 0)
  12684. (move-marker (make-marker) (match-beginning 0))))))))
  12685. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12686. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12687. When the target headline is found, return a marker to this location."
  12688. (let ((files (directory-files (or dir default-directory)
  12689. t "\\`[^.#].*\\.org\\'"))
  12690. visiting m buffer)
  12691. (catch 'found
  12692. (dolist (file files)
  12693. (message "trying %s" file)
  12694. (setq visiting (org-find-base-buffer-visiting file))
  12695. (setq buffer (or visiting (find-file-noselect file)))
  12696. (setq m (org-find-exact-headline-in-buffer
  12697. heading buffer))
  12698. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12699. (and m (throw 'found m))))))
  12700. (defun org-find-entry-with-id (ident)
  12701. "Locate the entry that contains the ID property with exact value IDENT.
  12702. IDENT can be a string, a symbol or a number, this function will search for
  12703. the string representation of it.
  12704. Return the position where this entry starts, or nil if there is no such entry."
  12705. (interactive "sID: ")
  12706. (let ((id (cond
  12707. ((stringp ident) ident)
  12708. ((symbolp ident) (symbol-name ident))
  12709. ((numberp ident) (number-to-string ident))
  12710. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12711. (org-with-wide-buffer (org-find-property "ID" id))))
  12712. ;;;; Timestamps
  12713. (defvar org-last-changed-timestamp nil)
  12714. (defvar org-last-inserted-timestamp nil
  12715. "The last time stamp inserted with `org-insert-time-stamp'.")
  12716. (defun org-time-stamp (arg &optional inactive)
  12717. "Prompt for a date/time and insert a time stamp.
  12718. If the user specifies a time like HH:MM or if this command is
  12719. called with at least one prefix argument, the time stamp contains
  12720. the date and the time. Otherwise, only the date is included.
  12721. All parts of a date not specified by the user are filled in from
  12722. the timestamp at point, if any, or the current date/time
  12723. otherwise.
  12724. If there is already a timestamp at the cursor, it is replaced.
  12725. With two universal prefix arguments, insert an active timestamp
  12726. with the current time without prompting the user.
  12727. When called from lisp, the timestamp is inactive if INACTIVE is
  12728. non-nil."
  12729. (interactive "P")
  12730. (let* ((ts (cond
  12731. ((org-at-date-range-p t)
  12732. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12733. ((org-at-timestamp-p 'lax) (match-string 0))))
  12734. ;; Default time is either the timestamp at point or today.
  12735. ;; When entering a range, only the range start is considered.
  12736. (default-time (and ts
  12737. (apply #'encode-time (org-parse-time-string ts))))
  12738. (default-input (and ts (org-get-compact-tod ts)))
  12739. (repeater (and ts
  12740. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12741. (match-string 0 ts)))
  12742. org-time-was-given
  12743. org-end-time-was-given
  12744. (time
  12745. (if (equal arg '(16)) (current-time)
  12746. ;; Preserve `this-command' and `last-command'.
  12747. (let ((this-command this-command)
  12748. (last-command last-command))
  12749. (org-read-date
  12750. arg 'totime nil nil default-time default-input
  12751. inactive)))))
  12752. (cond
  12753. ((and ts
  12754. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12755. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12756. (insert "--")
  12757. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12758. (ts
  12759. ;; Make sure we're on a timestamp. When in the middle of a date
  12760. ;; range, move arbitrarily to range end.
  12761. (unless (org-at-timestamp-p 'lax)
  12762. (skip-chars-forward "-")
  12763. (org-at-timestamp-p 'lax))
  12764. (replace-match "")
  12765. (setq org-last-changed-timestamp
  12766. (org-insert-time-stamp
  12767. time (or org-time-was-given arg)
  12768. inactive nil nil (list org-end-time-was-given)))
  12769. (when repeater
  12770. (backward-char)
  12771. (insert " " repeater)
  12772. (setq org-last-changed-timestamp
  12773. (concat (substring org-last-inserted-timestamp 0 -1)
  12774. " " repeater ">")))
  12775. (message "Timestamp updated"))
  12776. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12777. (t (org-insert-time-stamp
  12778. time (or org-time-was-given arg) inactive nil nil
  12779. (list org-end-time-was-given))))))
  12780. ;; FIXME: can we use this for something else, like computing time differences?
  12781. (defun org-get-compact-tod (s)
  12782. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12783. (let* ((t1 (match-string 1 s))
  12784. (h1 (string-to-number (match-string 2 s)))
  12785. (m1 (string-to-number (match-string 3 s)))
  12786. (t2 (and (match-end 4) (match-string 5 s)))
  12787. (h2 (and t2 (string-to-number (match-string 6 s))))
  12788. (m2 (and t2 (string-to-number (match-string 7 s))))
  12789. dh dm)
  12790. (if (not t2)
  12791. t1
  12792. (setq dh (- h2 h1) dm (- m2 m1))
  12793. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12794. (concat t1 "+" (number-to-string dh)
  12795. (and (/= 0 dm) (format ":%02d" dm)))))))
  12796. (defun org-time-stamp-inactive (&optional arg)
  12797. "Insert an inactive time stamp.
  12798. An inactive time stamp is enclosed in square brackets instead of angle
  12799. brackets. It is inactive in the sense that it does not trigger agenda entries,
  12800. does not link to the calendar and cannot be changed with the S-cursor keys.
  12801. So these are more for recording a certain time/date.
  12802. If the user specifies a time like HH:MM or if this command is called with
  12803. at least one prefix argument, the time stamp contains the date and the time.
  12804. Otherwise, only the date is included.
  12805. When called with two universal prefix arguments, insert an active time stamp
  12806. with the current time without prompting the user."
  12807. (interactive "P")
  12808. (org-time-stamp arg 'inactive))
  12809. (defvar org-date-ovl (make-overlay 1 1))
  12810. (overlay-put org-date-ovl 'face 'org-date-selected)
  12811. (delete-overlay org-date-ovl)
  12812. (defvar org-ans1) ; dynamically scoped parameter
  12813. (defvar org-ans2) ; dynamically scoped parameter
  12814. (defvar org-plain-time-of-day-regexp) ; defined below
  12815. (defvar org-overriding-default-time nil) ; dynamically scoped
  12816. (defvar org-read-date-overlay nil)
  12817. (defvar org-dcst nil) ; dynamically scoped
  12818. (defvar org-read-date-history nil)
  12819. (defvar org-read-date-final-answer nil)
  12820. (defvar org-read-date-analyze-futurep nil)
  12821. (defvar org-read-date-analyze-forced-year nil)
  12822. (defvar org-read-date-inactive)
  12823. (defvar org-def)
  12824. (defvar org-defdecode)
  12825. (defvar org-with-time)
  12826. (defvar calendar-setup) ; Dynamically scoped.
  12827. (defun org-read-date (&optional with-time to-time from-string prompt
  12828. default-time default-input inactive)
  12829. "Read a date, possibly a time, and make things smooth for the user.
  12830. The prompt will suggest to enter an ISO date, but you can also enter anything
  12831. which will at least partially be understood by `parse-time-string'.
  12832. Unrecognized parts of the date will default to the current day, month, year,
  12833. hour and minute. If this command is called to replace a timestamp at point,
  12834. or to enter the second timestamp of a range, the default time is taken
  12835. from the existing stamp. Furthermore, the command prefers the future,
  12836. so if you are giving a date where the year is not given, and the day-month
  12837. combination is already past in the current year, it will assume you
  12838. mean next year. For details, see the manual. A few examples:
  12839. 3-2-5 --> 2003-02-05
  12840. feb 15 --> currentyear-02-15
  12841. 2/15 --> currentyear-02-15
  12842. sep 12 9 --> 2009-09-12
  12843. 12:45 --> today 12:45
  12844. 22 sept 0:34 --> currentyear-09-22 0:34
  12845. 12 --> currentyear-currentmonth-12
  12846. Fri --> nearest Friday after today
  12847. -Tue --> last Tuesday
  12848. etc.
  12849. Furthermore you can specify a relative date by giving, as the *first* thing
  12850. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12851. change in days weeks, months, years.
  12852. With a single plus or minus, the date is relative to today. With a double
  12853. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12854. +4d --> four days from today
  12855. +4 --> same as above
  12856. +2w --> two weeks from today
  12857. ++5 --> five days from default date
  12858. The function understands only English month and weekday abbreviations.
  12859. While prompting, a calendar is popped up - you can also select the
  12860. date with the mouse (button 1). The calendar shows a period of three
  12861. months. To scroll it to other months, use the keys `>' and `<'.
  12862. If you don't like the calendar, turn it off with
  12863. (setq org-read-date-popup-calendar nil)
  12864. With optional argument TO-TIME, the date will immediately be converted
  12865. to an internal time.
  12866. With an optional argument WITH-TIME, the prompt will suggest to
  12867. also insert a time. Note that when WITH-TIME is not set, you can
  12868. still enter a time, and this function will inform the calling routine
  12869. about this change. The calling routine may then choose to change the
  12870. format used to insert the time stamp into the buffer to include the time.
  12871. With optional argument FROM-STRING, read from this string instead from
  12872. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12873. the time/date that is used for everything that is not specified by the
  12874. user."
  12875. (require 'parse-time)
  12876. (let* ((org-with-time with-time)
  12877. (org-time-stamp-rounding-minutes
  12878. (if (equal org-with-time '(16))
  12879. '(0 0)
  12880. org-time-stamp-rounding-minutes))
  12881. (org-dcst org-display-custom-times)
  12882. (ct (org-current-time))
  12883. (org-def (or org-overriding-default-time default-time ct))
  12884. (org-defdecode (decode-time org-def))
  12885. (cur-frame (selected-frame))
  12886. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12887. (calendar-setup
  12888. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12889. (calendar-move-hook nil)
  12890. (calendar-view-diary-initially-flag nil)
  12891. (calendar-view-holidays-initially-flag nil)
  12892. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12893. ;; Rationalize `org-def' and `org-defdecode', if required.
  12894. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12895. (setf (nth 2 org-defdecode) -1)
  12896. (setf (nth 1 org-defdecode) 59)
  12897. (setq org-def (apply #'encode-time org-defdecode))
  12898. (setq org-defdecode (decode-time org-def)))
  12899. (let* ((timestr (format-time-string
  12900. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12901. org-def))
  12902. (prompt (concat (if prompt (concat prompt " ") "")
  12903. (format "Date+time [%s]: " timestr))))
  12904. (cond
  12905. (from-string (setq ans from-string))
  12906. (org-read-date-popup-calendar
  12907. (save-excursion
  12908. (save-window-excursion
  12909. (calendar)
  12910. (when (eq calendar-setup 'calendar-only)
  12911. (setq cal-frame
  12912. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12913. (select-frame cal-frame))
  12914. (org-eval-in-calendar '(setq cursor-type nil) t)
  12915. (unwind-protect
  12916. (progn
  12917. (calendar-forward-day (- (time-to-days org-def)
  12918. (calendar-absolute-from-gregorian
  12919. (calendar-current-date))))
  12920. (org-eval-in-calendar nil t)
  12921. (let* ((old-map (current-local-map))
  12922. (map (copy-keymap calendar-mode-map))
  12923. (minibuffer-local-map
  12924. (copy-keymap org-read-date-minibuffer-local-map)))
  12925. (org-defkey map (kbd "RET") 'org-calendar-select)
  12926. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12927. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12928. (unwind-protect
  12929. (progn
  12930. (use-local-map map)
  12931. (setq org-read-date-inactive inactive)
  12932. (add-hook 'post-command-hook 'org-read-date-display)
  12933. (setq org-ans0
  12934. (read-string prompt
  12935. default-input
  12936. 'org-read-date-history
  12937. nil))
  12938. ;; org-ans0: from prompt
  12939. ;; org-ans1: from mouse click
  12940. ;; org-ans2: from calendar motion
  12941. (setq ans
  12942. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12943. (remove-hook 'post-command-hook 'org-read-date-display)
  12944. (use-local-map old-map)
  12945. (when org-read-date-overlay
  12946. (delete-overlay org-read-date-overlay)
  12947. (setq org-read-date-overlay nil)))))
  12948. (bury-buffer "*Calendar*")
  12949. (when cal-frame
  12950. (delete-frame cal-frame)
  12951. (select-frame-set-input-focus cur-frame))))))
  12952. (t ; Naked prompt only
  12953. (unwind-protect
  12954. (setq ans (read-string prompt default-input
  12955. 'org-read-date-history timestr))
  12956. (when org-read-date-overlay
  12957. (delete-overlay org-read-date-overlay)
  12958. (setq org-read-date-overlay nil))))))
  12959. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12960. (when org-read-date-analyze-forced-year
  12961. (message "Year was forced into %s"
  12962. (if org-read-date-force-compatible-dates
  12963. "compatible range (1970-2037)"
  12964. "range representable on this machine"))
  12965. (ding))
  12966. ;; One round trip to get rid of 34th of August and stuff like that....
  12967. (setq final (decode-time (apply 'encode-time final)))
  12968. (setq org-read-date-final-answer ans)
  12969. (if to-time
  12970. (apply 'encode-time final)
  12971. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12972. (format "%04d-%02d-%02d %02d:%02d"
  12973. (nth 5 final) (nth 4 final) (nth 3 final)
  12974. (nth 2 final) (nth 1 final))
  12975. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12976. (defun org-read-date-display ()
  12977. "Display the current date prompt interpretation in the minibuffer."
  12978. (when org-read-date-display-live
  12979. (when org-read-date-overlay
  12980. (delete-overlay org-read-date-overlay))
  12981. (when (minibufferp (current-buffer))
  12982. (save-excursion
  12983. (end-of-line 1)
  12984. (while (not (equal (buffer-substring
  12985. (max (point-min) (- (point) 4)) (point))
  12986. " "))
  12987. (insert " ")))
  12988. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12989. " " (or org-ans1 org-ans2)))
  12990. (org-end-time-was-given nil)
  12991. (f (org-read-date-analyze ans org-def org-defdecode))
  12992. (fmts (if org-dcst
  12993. org-time-stamp-custom-formats
  12994. org-time-stamp-formats))
  12995. (fmt (if (or org-with-time
  12996. (and (boundp 'org-time-was-given) org-time-was-given))
  12997. (cdr fmts)
  12998. (car fmts)))
  12999. (txt (format-time-string fmt (apply 'encode-time f)))
  13000. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  13001. (txt (concat "=> " txt)))
  13002. (when (and org-end-time-was-given
  13003. (string-match org-plain-time-of-day-regexp txt))
  13004. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  13005. org-end-time-was-given
  13006. (substring txt (match-end 0)))))
  13007. (when org-read-date-analyze-futurep
  13008. (setq txt (concat txt " (=>F)")))
  13009. (setq org-read-date-overlay
  13010. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  13011. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  13012. (defun org-read-date-analyze (ans def defdecode)
  13013. "Analyze the combined answer of the date prompt."
  13014. ;; FIXME: cleanup and comment
  13015. (let ((org-def def)
  13016. (org-defdecode defdecode)
  13017. (nowdecode (decode-time))
  13018. delta deltan deltaw deltadef year month day
  13019. hour minute second wday pm h2 m2 tl wday1
  13020. iso-year iso-weekday iso-week iso-date futurep kill-year)
  13021. (setq org-read-date-analyze-futurep nil
  13022. org-read-date-analyze-forced-year nil)
  13023. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  13024. (setq ans "+0"))
  13025. (when (setq delta (org-read-date-get-relative ans nil org-def))
  13026. (setq ans (replace-match "" t t ans)
  13027. deltan (car delta)
  13028. deltaw (nth 1 delta)
  13029. deltadef (nth 2 delta)))
  13030. ;; Check if there is an iso week date in there. If yes, store the
  13031. ;; info and postpone interpreting it until the rest of the parsing
  13032. ;; is done.
  13033. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  13034. (setq iso-year (when (match-end 1)
  13035. (org-small-year-to-year
  13036. (string-to-number (match-string 1 ans))))
  13037. iso-weekday (when (match-end 3)
  13038. (string-to-number (match-string 3 ans)))
  13039. iso-week (string-to-number (match-string 2 ans)))
  13040. (setq ans (replace-match "" t t ans)))
  13041. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  13042. (when (string-match
  13043. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  13044. (setq year (if (match-end 2)
  13045. (string-to-number (match-string 2 ans))
  13046. (progn (setq kill-year t)
  13047. (string-to-number (format-time-string "%Y"))))
  13048. month (string-to-number (match-string 3 ans))
  13049. day (string-to-number (match-string 4 ans)))
  13050. (setq year (org-small-year-to-year year))
  13051. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13052. t nil ans)))
  13053. ;; Help matching dotted european dates
  13054. (when (string-match
  13055. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  13056. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  13057. (setq kill-year t)
  13058. (string-to-number (format-time-string "%Y")))
  13059. day (string-to-number (match-string 1 ans))
  13060. month (string-to-number (match-string 2 ans))
  13061. ans (replace-match (format "%04d-%02d-%02d" year month day)
  13062. t nil ans)))
  13063. ;; Help matching american dates, like 5/30 or 5/30/7
  13064. (when (string-match
  13065. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  13066. (setq year (if (match-end 4)
  13067. (string-to-number (match-string 4 ans))
  13068. (progn (setq kill-year t)
  13069. (string-to-number (format-time-string "%Y"))))
  13070. month (string-to-number (match-string 1 ans))
  13071. day (string-to-number (match-string 2 ans)))
  13072. (setq year (org-small-year-to-year year))
  13073. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13074. t nil ans)))
  13075. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  13076. ;; If there is a time with am/pm, and *no* time without it, we convert
  13077. ;; so that matching will be successful.
  13078. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  13079. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  13080. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  13081. (setq hour (string-to-number (match-string 1 ans))
  13082. minute (if (match-end 3)
  13083. (string-to-number (match-string 3 ans))
  13084. 0)
  13085. pm (equal ?p
  13086. (string-to-char (downcase (match-string 4 ans)))))
  13087. (if (and (= hour 12) (not pm))
  13088. (setq hour 0)
  13089. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  13090. (setq ans (replace-match (format "%02d:%02d" hour minute)
  13091. t t ans))))
  13092. ;; Check if a time range is given as a duration
  13093. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  13094. (setq hour (string-to-number (match-string 1 ans))
  13095. h2 (+ hour (string-to-number (match-string 3 ans)))
  13096. minute (string-to-number (match-string 2 ans))
  13097. m2 (+ minute (if (match-end 5) (string-to-number
  13098. (match-string 5 ans))0)))
  13099. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  13100. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  13101. t t ans)))
  13102. ;; Check if there is a time range
  13103. (when (boundp 'org-end-time-was-given)
  13104. (setq org-time-was-given nil)
  13105. (when (and (string-match org-plain-time-of-day-regexp ans)
  13106. (match-end 8))
  13107. (setq org-end-time-was-given (match-string 8 ans))
  13108. (setq ans (concat (substring ans 0 (match-beginning 7))
  13109. (substring ans (match-end 7))))))
  13110. (setq tl (parse-time-string ans)
  13111. day (or (nth 3 tl) (nth 3 org-defdecode))
  13112. month
  13113. (cond ((nth 4 tl))
  13114. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  13115. ;; Day was specified. Make sure DAY+MONTH
  13116. ;; combination happens in the future.
  13117. ((nth 3 tl)
  13118. (setq futurep t)
  13119. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  13120. (nth 4 nowdecode)))
  13121. (t (nth 4 org-defdecode)))
  13122. year
  13123. (cond ((and (not kill-year) (nth 5 tl)))
  13124. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  13125. ;; Month was guessed in the future and is at least
  13126. ;; equal to NOWDECODE's. Fix year accordingly.
  13127. (futurep
  13128. (if (or (> month (nth 4 nowdecode))
  13129. (>= day (nth 3 nowdecode)))
  13130. (nth 5 nowdecode)
  13131. (1+ (nth 5 nowdecode))))
  13132. ;; Month was specified. Make sure MONTH+YEAR
  13133. ;; combination happens in the future.
  13134. ((nth 4 tl)
  13135. (setq futurep t)
  13136. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  13137. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  13138. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  13139. (t (nth 5 nowdecode))))
  13140. (t (nth 5 org-defdecode)))
  13141. hour (or (nth 2 tl) (nth 2 org-defdecode))
  13142. minute (or (nth 1 tl) (nth 1 org-defdecode))
  13143. second (or (nth 0 tl) 0)
  13144. wday (nth 6 tl))
  13145. (when (and (eq org-read-date-prefer-future 'time)
  13146. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  13147. (equal day (nth 3 nowdecode))
  13148. (equal month (nth 4 nowdecode))
  13149. (equal year (nth 5 nowdecode))
  13150. (nth 2 tl)
  13151. (or (< (nth 2 tl) (nth 2 nowdecode))
  13152. (and (= (nth 2 tl) (nth 2 nowdecode))
  13153. (nth 1 tl)
  13154. (< (nth 1 tl) (nth 1 nowdecode)))))
  13155. (setq day (1+ day)
  13156. futurep t))
  13157. ;; Special date definitions below
  13158. (cond
  13159. (iso-week
  13160. ;; There was an iso week
  13161. (require 'cal-iso)
  13162. (setq futurep nil)
  13163. (setq year (or iso-year year)
  13164. day (or iso-weekday wday 1)
  13165. wday nil ; to make sure that the trigger below does not match
  13166. iso-date (calendar-gregorian-from-absolute
  13167. (calendar-iso-to-absolute
  13168. (list iso-week day year))))
  13169. ; FIXME: Should we also push ISO weeks into the future?
  13170. ; (when (and org-read-date-prefer-future
  13171. ; (not iso-year)
  13172. ; (< (calendar-absolute-from-gregorian iso-date)
  13173. ; (time-to-days nil)))
  13174. ; (setq year (1+ year)
  13175. ; iso-date (calendar-gregorian-from-absolute
  13176. ; (calendar-iso-to-absolute
  13177. ; (list iso-week day year)))))
  13178. (setq month (car iso-date)
  13179. year (nth 2 iso-date)
  13180. day (nth 1 iso-date)))
  13181. (deltan
  13182. (setq futurep nil)
  13183. (unless deltadef
  13184. (let ((now (decode-time)))
  13185. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  13186. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  13187. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  13188. ((equal deltaw "m") (setq month (+ month deltan)))
  13189. ((equal deltaw "y") (setq year (+ year deltan)))))
  13190. ((and wday (not (nth 3 tl)))
  13191. ;; Weekday was given, but no day, so pick that day in the week
  13192. ;; on or after the derived date.
  13193. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  13194. (unless (equal wday wday1)
  13195. (setq day (+ day (% (- wday wday1 -7) 7))))))
  13196. (when (and (boundp 'org-time-was-given)
  13197. (nth 2 tl))
  13198. (setq org-time-was-given t))
  13199. (when (< year 100) (setq year (+ 2000 year)))
  13200. ;; Check of the date is representable
  13201. (if org-read-date-force-compatible-dates
  13202. (progn
  13203. (when (< year 1970)
  13204. (setq year 1970 org-read-date-analyze-forced-year t))
  13205. (when (> year 2037)
  13206. (setq year 2037 org-read-date-analyze-forced-year t)))
  13207. (condition-case nil
  13208. (ignore (encode-time second minute hour day month year))
  13209. (error
  13210. (setq year (nth 5 org-defdecode))
  13211. (setq org-read-date-analyze-forced-year t))))
  13212. (setq org-read-date-analyze-futurep futurep)
  13213. (list second minute hour day month year)))
  13214. (defvar parse-time-weekdays)
  13215. (defun org-read-date-get-relative (s today default)
  13216. "Check string S for special relative date string.
  13217. TODAY and DEFAULT are internal times, for today and for a default.
  13218. Return shift list (N what def-flag)
  13219. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  13220. N is the number of WHATs to shift.
  13221. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  13222. the DEFAULT date rather than TODAY."
  13223. (require 'parse-time)
  13224. (when (and
  13225. (string-match
  13226. (concat
  13227. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  13228. "\\([0-9]+\\)?"
  13229. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  13230. "\\([ \t]\\|$\\)") s)
  13231. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  13232. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  13233. (string-to-char (substring (match-string 1 s) -1))
  13234. ?+))
  13235. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  13236. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  13237. (what (if (match-end 3) (match-string 3 s) "d"))
  13238. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  13239. (date (if rel default today))
  13240. (wday (nth 6 (decode-time date)))
  13241. delta)
  13242. (if wday1
  13243. (progn
  13244. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  13245. (when (= delta 0) (setq delta 7))
  13246. (when (= dir ?-)
  13247. (setq delta (- delta 7))
  13248. (when (= delta 0) (setq delta -7)))
  13249. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  13250. (list delta "d" rel))
  13251. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  13252. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  13253. "Turn a user-specified date into the internal representation.
  13254. The internal representation needed by the calendar is (month day year).
  13255. This is a wrapper to handle the brain-dead convention in calendar that
  13256. user function argument order change dependent on argument order."
  13257. (pcase calendar-date-style
  13258. (`american (list arg1 arg2 arg3))
  13259. (`european (list arg2 arg1 arg3))
  13260. (`iso (list arg2 arg3 arg1))))
  13261. (defun org-eval-in-calendar (form &optional keepdate)
  13262. "Eval FORM in the calendar window and return to current window.
  13263. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  13264. (let ((sf (selected-frame))
  13265. (sw (selected-window)))
  13266. (select-window (get-buffer-window "*Calendar*" t))
  13267. (eval form)
  13268. (when (and (not keepdate) (calendar-cursor-to-date))
  13269. (let* ((date (calendar-cursor-to-date))
  13270. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13271. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  13272. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  13273. (select-window sw)
  13274. (select-frame-set-input-focus sf)))
  13275. (defun org-calendar-select ()
  13276. "Return to `org-read-date' with the date currently selected.
  13277. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13278. (interactive)
  13279. (when (calendar-cursor-to-date)
  13280. (let* ((date (calendar-cursor-to-date))
  13281. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13282. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13283. (when (active-minibuffer-window) (exit-minibuffer))))
  13284. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  13285. "Insert a date stamp for the date given by the internal TIME.
  13286. See `format-time-string' for the format of TIME.
  13287. WITH-HM means use the stamp format that includes the time of the day.
  13288. INACTIVE means use square brackets instead of angular ones, so that the
  13289. stamp will not contribute to the agenda.
  13290. PRE and POST are optional strings to be inserted before and after the
  13291. stamp.
  13292. The command returns the inserted time stamp."
  13293. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  13294. stamp)
  13295. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  13296. (insert-before-markers (or pre ""))
  13297. (when (listp extra)
  13298. (setq extra (car extra))
  13299. (if (and (stringp extra)
  13300. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  13301. (setq extra (format "-%02d:%02d"
  13302. (string-to-number (match-string 1 extra))
  13303. (string-to-number (match-string 2 extra))))
  13304. (setq extra nil)))
  13305. (when extra
  13306. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  13307. (insert-before-markers (setq stamp (format-time-string fmt time)))
  13308. (insert-before-markers (or post ""))
  13309. (setq org-last-inserted-timestamp stamp)))
  13310. (defun org-toggle-time-stamp-overlays ()
  13311. "Toggle the use of custom time stamp formats."
  13312. (interactive)
  13313. (setq org-display-custom-times (not org-display-custom-times))
  13314. (unless org-display-custom-times
  13315. (let ((p (point-min)) (bmp (buffer-modified-p)))
  13316. (while (setq p (next-single-property-change p 'display))
  13317. (when (and (get-text-property p 'display)
  13318. (eq (get-text-property p 'face) 'org-date))
  13319. (remove-text-properties
  13320. p (setq p (next-single-property-change p 'display))
  13321. '(display t))))
  13322. (set-buffer-modified-p bmp)))
  13323. (org-restart-font-lock)
  13324. (setq org-table-may-need-update t)
  13325. (if org-display-custom-times
  13326. (message "Time stamps are overlaid with custom format")
  13327. (message "Time stamp overlays removed")))
  13328. (defun org-display-custom-time (beg end)
  13329. "Overlay modified time stamp format over timestamp between BEG and END."
  13330. (let* ((ts (buffer-substring beg end))
  13331. t1 with-hm tf time str (off 0))
  13332. (save-match-data
  13333. (setq t1 (org-parse-time-string ts t))
  13334. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  13335. (setq off (- (match-end 0) (match-beginning 0)))))
  13336. (setq end (- end off))
  13337. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  13338. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  13339. time (org-fix-decoded-time t1)
  13340. str (org-add-props
  13341. (format-time-string
  13342. (substring tf 1 -1) (apply 'encode-time time))
  13343. nil 'mouse-face 'highlight))
  13344. (put-text-property beg end 'display str)))
  13345. (defun org-fix-decoded-time (time)
  13346. "Set 0 instead of nil for the first 6 elements of time.
  13347. Don't touch the rest."
  13348. (let ((n 0))
  13349. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  13350. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  13351. "Difference between TIMESTAMP-STRING and now in days.
  13352. If SECONDS is non-nil, return the difference in seconds."
  13353. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  13354. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  13355. (funcall fdiff nil))))
  13356. (defun org-deadline-close-p (timestamp-string &optional ndays)
  13357. "Is the time in TIMESTAMP-STRING close to the current date?"
  13358. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  13359. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  13360. (not (org-entry-is-done-p))))
  13361. (defun org-get-wdays (ts &optional delay zero-delay)
  13362. "Get the deadline lead time appropriate for timestring TS.
  13363. When DELAY is non-nil, get the delay time for scheduled items
  13364. instead of the deadline lead time. When ZERO-DELAY is non-nil
  13365. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  13366. don't try to find the delay cookie in the scheduled timestamp."
  13367. (let ((tv (if delay org-scheduled-delay-days
  13368. org-deadline-warning-days)))
  13369. (cond
  13370. ((or (and delay (< tv 0))
  13371. (and delay zero-delay (<= tv 0))
  13372. (and (not delay) (<= tv 0)))
  13373. ;; Enforce this value no matter what
  13374. (- tv))
  13375. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  13376. ;; lead time is specified.
  13377. (floor (* (string-to-number (match-string 1 ts))
  13378. (cdr (assoc (match-string 2 ts)
  13379. '(("d" . 1) ("w" . 7)
  13380. ("m" . 30.4) ("y" . 365.25)
  13381. ("h" . 0.041667)))))))
  13382. ;; go for the default.
  13383. (t tv))))
  13384. (defun org-calendar-select-mouse (ev)
  13385. "Return to `org-read-date' with the date currently selected.
  13386. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13387. (interactive "e")
  13388. (mouse-set-point ev)
  13389. (when (calendar-cursor-to-date)
  13390. (let* ((date (calendar-cursor-to-date))
  13391. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13392. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13393. (when (active-minibuffer-window) (exit-minibuffer))))
  13394. (defun org-check-deadlines (ndays)
  13395. "Check if there are any deadlines due or past due.
  13396. A deadline is considered due if it happens within `org-deadline-warning-days'
  13397. days from today's date. If the deadline appears in an entry marked DONE,
  13398. it is not shown. A numeric prefix argument NDAYS can be used to test that
  13399. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  13400. are shown."
  13401. (interactive "P")
  13402. (let* ((org-warn-days
  13403. (cond
  13404. ((equal ndays '(4)) 100000)
  13405. (ndays (prefix-numeric-value ndays))
  13406. (t (abs org-deadline-warning-days))))
  13407. (case-fold-search nil)
  13408. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  13409. (callback
  13410. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  13411. (message "%d deadlines past-due or due within %d days"
  13412. (org-occur regexp nil callback)
  13413. org-warn-days)))
  13414. (defsubst org-re-timestamp (type)
  13415. "Return a regexp for timestamp TYPE.
  13416. Allowed values for TYPE are:
  13417. all: all timestamps
  13418. active: only active timestamps (<...>)
  13419. inactive: only inactive timestamps ([...])
  13420. scheduled: only scheduled timestamps
  13421. deadline: only deadline timestamps
  13422. closed: only closed time-stamps
  13423. When TYPE is nil, fall back on returning a regexp that matches
  13424. both scheduled and deadline timestamps."
  13425. (cl-case type
  13426. (all org-ts-regexp-both)
  13427. (active org-ts-regexp)
  13428. (inactive org-ts-regexp-inactive)
  13429. (scheduled org-scheduled-time-regexp)
  13430. (deadline org-deadline-time-regexp)
  13431. (closed org-closed-time-regexp)
  13432. (otherwise
  13433. (concat "\\<"
  13434. (regexp-opt (list org-deadline-string org-scheduled-string))
  13435. " *<\\([^>]+\\)>"))))
  13436. (defun org-check-before-date (d)
  13437. "Check if there are deadlines or scheduled entries before date D."
  13438. (interactive (list (org-read-date)))
  13439. (let* ((case-fold-search nil)
  13440. (regexp (org-re-timestamp org-ts-type))
  13441. (ts-type org-ts-type)
  13442. (callback
  13443. (lambda ()
  13444. (let ((match (match-string 1)))
  13445. (and (if (memq ts-type '(active inactive all))
  13446. (eq (org-element-type (save-excursion
  13447. (backward-char)
  13448. (org-element-context)))
  13449. 'timestamp)
  13450. (org-at-planning-p))
  13451. (time-less-p
  13452. (org-time-string-to-time match)
  13453. (org-time-string-to-time d)))))))
  13454. (message "%d entries before %s"
  13455. (org-occur regexp nil callback)
  13456. d)))
  13457. (defun org-check-after-date (d)
  13458. "Check if there are deadlines or scheduled entries after date D."
  13459. (interactive (list (org-read-date)))
  13460. (let* ((case-fold-search nil)
  13461. (regexp (org-re-timestamp org-ts-type))
  13462. (ts-type org-ts-type)
  13463. (callback
  13464. (lambda ()
  13465. (let ((match (match-string 1)))
  13466. (and (if (memq ts-type '(active inactive all))
  13467. (eq (org-element-type (save-excursion
  13468. (backward-char)
  13469. (org-element-context)))
  13470. 'timestamp)
  13471. (org-at-planning-p))
  13472. (not (time-less-p
  13473. (org-time-string-to-time match)
  13474. (org-time-string-to-time d))))))))
  13475. (message "%d entries after %s"
  13476. (org-occur regexp nil callback)
  13477. d)))
  13478. (defun org-check-dates-range (start-date end-date)
  13479. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13480. (interactive (list (org-read-date nil nil nil "Range starts")
  13481. (org-read-date nil nil nil "Range end")))
  13482. (let ((case-fold-search nil)
  13483. (regexp (org-re-timestamp org-ts-type))
  13484. (callback
  13485. (let ((type org-ts-type))
  13486. (lambda ()
  13487. (let ((match (match-string 1)))
  13488. (and
  13489. (if (memq type '(active inactive all))
  13490. (eq (org-element-type (save-excursion
  13491. (backward-char)
  13492. (org-element-context)))
  13493. 'timestamp)
  13494. (org-at-planning-p))
  13495. (not (time-less-p
  13496. (org-time-string-to-time match)
  13497. (org-time-string-to-time start-date)))
  13498. (time-less-p
  13499. (org-time-string-to-time match)
  13500. (org-time-string-to-time end-date))))))))
  13501. (message "%d entries between %s and %s"
  13502. (org-occur regexp nil callback) start-date end-date)))
  13503. (defun org-evaluate-time-range (&optional to-buffer)
  13504. "Evaluate a time range by computing the difference between start and end.
  13505. Normally the result is just printed in the echo area, but with prefix arg
  13506. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13507. If the time range is actually in a table, the result is inserted into the
  13508. next column.
  13509. For time difference computation, a year is assumed to be exactly 365
  13510. days in order to avoid rounding problems."
  13511. (interactive "P")
  13512. (or
  13513. (org-clock-update-time-maybe)
  13514. (save-excursion
  13515. (unless (org-at-date-range-p t)
  13516. (goto-char (point-at-bol))
  13517. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13518. (unless (org-at-date-range-p t)
  13519. (user-error "Not at a time-stamp range, and none found in current line")))
  13520. (let* ((ts1 (match-string 1))
  13521. (ts2 (match-string 2))
  13522. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13523. (match-end (match-end 0))
  13524. (time1 (org-time-string-to-time ts1))
  13525. (time2 (org-time-string-to-time ts2))
  13526. (diff (abs (float-time (time-subtract time2 time1))))
  13527. (negative (time-less-p time2 time1))
  13528. ;; (ys (floor (* 365 24 60 60)))
  13529. (ds (* 24 60 60))
  13530. (hs (* 60 60))
  13531. (fy "%dy %dd %02d:%02d")
  13532. (fy1 "%dy %dd")
  13533. (fd "%dd %02d:%02d")
  13534. (fd1 "%dd")
  13535. (fh "%02d:%02d")
  13536. y d h m align)
  13537. (if havetime
  13538. (setq ; y (floor diff ys) diff (mod diff ys)
  13539. y 0
  13540. d (floor diff ds) diff (mod diff ds)
  13541. h (floor diff hs) diff (mod diff hs)
  13542. m (floor diff 60))
  13543. (setq ; y (floor diff ys) diff (mod diff ys)
  13544. y 0
  13545. d (round diff ds)
  13546. h 0 m 0))
  13547. (if (not to-buffer)
  13548. (message "%s" (org-make-tdiff-string y d h m))
  13549. (if (org-at-table-p)
  13550. (progn
  13551. (goto-char match-end)
  13552. (setq align t)
  13553. (and (looking-at " *|") (goto-char (match-end 0))))
  13554. (goto-char match-end))
  13555. (when (looking-at
  13556. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13557. (replace-match ""))
  13558. (when negative (insert " -"))
  13559. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13560. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13561. (insert " " (format fh h m))))
  13562. (when align (org-table-align))
  13563. (message "Time difference inserted")))))
  13564. (defun org-make-tdiff-string (y d h m)
  13565. (let ((fmt "")
  13566. (l nil))
  13567. (when (> y 0)
  13568. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13569. (push y l))
  13570. (when (> d 0)
  13571. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13572. (push d l))
  13573. (when (> h 0)
  13574. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13575. (push h l))
  13576. (when (> m 0)
  13577. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13578. (push m l))
  13579. (apply 'format fmt (nreverse l))))
  13580. (defun org-time-string-to-time (s)
  13581. "Convert timestamp string S into internal time."
  13582. (apply #'encode-time (org-parse-time-string s)))
  13583. (defun org-time-string-to-seconds (s)
  13584. "Convert a timestamp string S into a number of seconds."
  13585. (float-time (org-time-string-to-time s)))
  13586. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13587. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13588. "Convert time stamp S to an absolute day number.
  13589. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13590. stamp, get the closest date to DAYNR. If PREFER is
  13591. `past' (respectively `future') return a date past (respectively
  13592. after) or equal to DAYNR.
  13593. POS is the location of time stamp S, as a buffer position in
  13594. BUFFER.
  13595. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13596. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13597. signaled."
  13598. (cond
  13599. ((string-match "\\`%%\\((.*)\\)" s)
  13600. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13601. ;; only able to match individual dates. If it fails, raise an
  13602. ;; error.
  13603. (if (and daynr
  13604. (org-diary-sexp-entry
  13605. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13606. daynr
  13607. (signal 'org-diary-sexp-no-match (list s))))
  13608. (daynr (org-closest-date s daynr prefer))
  13609. (t (time-to-days
  13610. (condition-case errdata
  13611. (apply #'encode-time (org-parse-time-string s))
  13612. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13613. s
  13614. (if (not (and buffer pos)) ""
  13615. (format-message " at %d in buffer `%s'" pos buffer))
  13616. (cdr errdata))))))))
  13617. (defun org-days-to-iso-week (days)
  13618. "Return the iso week number."
  13619. (require 'cal-iso)
  13620. (car (calendar-iso-from-absolute days)))
  13621. (defun org-small-year-to-year (year)
  13622. "Convert 2-digit years into 4-digit years.
  13623. YEAR is expanded into one of the 30 next years, if possible, or
  13624. into a past one. Any year larger than 99 is returned unchanged."
  13625. (if (>= year 100) year
  13626. (let* ((current (string-to-number (format-time-string "%Y")))
  13627. (century (/ current 100))
  13628. (offset (- year (% current 100))))
  13629. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13630. ((> offset -70) (+ (* century 100) year))
  13631. (t (+ (* (1+ century) 100) year))))))
  13632. (defun org-time-from-absolute (d)
  13633. "Return the time corresponding to date D.
  13634. D may be an absolute day number, or a calendar-type list (month day year)."
  13635. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13636. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13637. (defvar org-agenda-current-date)
  13638. (defun org-calendar-holiday ()
  13639. "List of holidays, for Diary display in Org mode."
  13640. (require 'holidays)
  13641. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13642. (and hl (mapconcat #'identity hl "; "))))
  13643. (defun org-diary-sexp-entry (sexp entry d)
  13644. "Process a SEXP diary ENTRY for date D."
  13645. (require 'diary-lib)
  13646. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13647. ;; dynamically.
  13648. (let* ((sexp `(let ((entry ,entry)
  13649. (date ',d))
  13650. ,(car (read-from-string sexp))))
  13651. (result (if calendar-debug-sexp (eval sexp)
  13652. (condition-case nil
  13653. (eval sexp)
  13654. (error
  13655. (beep)
  13656. (message "Bad sexp at line %d in %s: %s"
  13657. (org-current-line)
  13658. (buffer-file-name) sexp)
  13659. (sleep-for 2))))))
  13660. (cond ((stringp result) (split-string result "; "))
  13661. ((and (consp result)
  13662. (not (consp (cdr result)))
  13663. (stringp (cdr result))) (cdr result))
  13664. ((and (consp result)
  13665. (stringp (car result))) result)
  13666. (result entry))))
  13667. (defun org-diary-to-ical-string (frombuf)
  13668. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13669. This uses the icalendar.el library."
  13670. (let* ((tmpdir temporary-file-directory)
  13671. (tmpfile (make-temp-name
  13672. (expand-file-name "orgics" tmpdir)))
  13673. buf rtn b e)
  13674. (with-current-buffer frombuf
  13675. (icalendar-export-region (point-min) (point-max) tmpfile)
  13676. (setq buf (find-buffer-visiting tmpfile))
  13677. (set-buffer buf)
  13678. (goto-char (point-min))
  13679. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13680. (setq b (match-beginning 0)))
  13681. (goto-char (point-max))
  13682. (when (re-search-backward "^END:VEVENT" nil t)
  13683. (setq e (match-end 0)))
  13684. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13685. (kill-buffer buf)
  13686. (delete-file tmpfile)
  13687. rtn))
  13688. (defun org-closest-date (start current prefer)
  13689. "Return closest date to CURRENT starting from START.
  13690. CURRENT and START are both time stamps.
  13691. When PREFER is `past', return a date that is either CURRENT or
  13692. past. When PREFER is `future', return a date that is either
  13693. CURRENT or future.
  13694. Only time stamps with a repeater are modified. Any other time
  13695. stamp stay unchanged. In any case, return value is an absolute
  13696. day number."
  13697. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13698. ;; No repeater. Do not shift time stamp.
  13699. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  13700. (let ((value (string-to-number (match-string 1 start)))
  13701. (type (match-string 2 start)))
  13702. (if (= 0 value)
  13703. ;; Repeater with a 0-value is considered as void.
  13704. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  13705. (let* ((base (org-date-to-gregorian start))
  13706. (target (org-date-to-gregorian current))
  13707. (sday (calendar-absolute-from-gregorian base))
  13708. (cday (calendar-absolute-from-gregorian target))
  13709. n1 n2)
  13710. ;; If START is already past CURRENT, just return START.
  13711. (if (<= cday sday) sday
  13712. ;; Compute closest date before (N1) and closest date past
  13713. ;; (N2) CURRENT.
  13714. (pcase type
  13715. ("h"
  13716. (let ((missing-hours
  13717. (mod (+ (- (* 24 (- cday sday))
  13718. (nth 2 (org-parse-time-string start)))
  13719. org-extend-today-until)
  13720. value)))
  13721. (setf n1 (if (= missing-hours 0) cday
  13722. (- cday (1+ (/ missing-hours 24)))))
  13723. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13724. ((or "d" "w")
  13725. (let ((value (if (equal type "w") (* 7 value) value)))
  13726. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13727. (setf n2 (+ n1 value))))
  13728. ("m"
  13729. (let* ((add-months
  13730. (lambda (d n)
  13731. ;; Add N months to gregorian date D, i.e.,
  13732. ;; a list (MONTH DAY YEAR). Return a valid
  13733. ;; gregorian date.
  13734. (let ((m (+ (nth 0 d) n)))
  13735. (list (mod m 12)
  13736. (nth 1 d)
  13737. (+ (/ m 12) (nth 2 d))))))
  13738. (months ; Complete months to TARGET.
  13739. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13740. (- (nth 0 target) (nth 0 base))
  13741. ;; If START's day is greater than
  13742. ;; TARGET's, remove incomplete month.
  13743. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13744. value)
  13745. value))
  13746. (before (funcall add-months base months)))
  13747. (setf n1 (calendar-absolute-from-gregorian before))
  13748. (setf n2
  13749. (calendar-absolute-from-gregorian
  13750. (funcall add-months before value)))))
  13751. (_
  13752. (let* ((d (nth 1 base))
  13753. (m (nth 0 base))
  13754. (y (nth 2 base))
  13755. (years ; Complete years to TARGET.
  13756. (* (/ (- (nth 2 target)
  13757. y
  13758. ;; If START's month and day are
  13759. ;; greater than TARGET's, remove
  13760. ;; incomplete year.
  13761. (if (or (> (nth 0 target) m)
  13762. (and (= (nth 0 target) m)
  13763. (> (nth 1 target) d)))
  13764. 0
  13765. 1))
  13766. value)
  13767. value))
  13768. (before (list m d (+ y years))))
  13769. (setf n1 (calendar-absolute-from-gregorian before))
  13770. (setf n2 (calendar-absolute-from-gregorian
  13771. (list m d (+ (nth 2 before) value)))))))
  13772. ;; Handle PREFER parameter, if any.
  13773. (cond
  13774. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13775. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13776. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13777. (defun org-date-to-gregorian (d)
  13778. "Turn any specification of date D into a Gregorian date for the calendar."
  13779. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13780. ((and (listp d) (= (length d) 3)) d)
  13781. ((stringp d)
  13782. (let ((d (org-parse-time-string d)))
  13783. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13784. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13785. (defun org-timestamp-up (&optional arg)
  13786. "Increase the date item at the cursor by one.
  13787. If the cursor is on the year, change the year. If it is on the month,
  13788. the day or the time, change that. If the cursor is on the enclosing
  13789. bracket, change the timestamp type.
  13790. With prefix ARG, change by that many units."
  13791. (interactive "p")
  13792. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13793. (defun org-timestamp-down (&optional arg)
  13794. "Decrease the date item at the cursor by one.
  13795. If the cursor is on the year, change the year. If it is on the month,
  13796. the day or the time, change that. If the cursor is on the enclosing
  13797. bracket, change the timestamp type.
  13798. With prefix ARG, change by that many units."
  13799. (interactive "p")
  13800. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13801. (defun org-timestamp-up-day (&optional arg)
  13802. "Increase the date in the time stamp by one day.
  13803. With prefix ARG, change that many days."
  13804. (interactive "p")
  13805. (if (and (not (org-at-timestamp-p 'lax))
  13806. (org-at-heading-p))
  13807. (org-todo 'up)
  13808. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13809. (defun org-timestamp-down-day (&optional arg)
  13810. "Decrease the date in the time stamp by one day.
  13811. With prefix ARG, change that many days."
  13812. (interactive "p")
  13813. (if (and (not (org-at-timestamp-p 'lax))
  13814. (org-at-heading-p))
  13815. (org-todo 'down)
  13816. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13817. (defun org-at-timestamp-p (&optional extended)
  13818. "Non-nil if point is inside a timestamp.
  13819. By default, the function only consider syntactically valid active
  13820. timestamps. However, the caller may have a broader definition
  13821. for timestamps. As a consequence, optional argument EXTENDED can
  13822. be set to the following values
  13823. `inactive'
  13824. Include also syntactically valid inactive timestamps.
  13825. `agenda'
  13826. Include timestamps allowed in Agenda, i.e., those in
  13827. properties drawers, planning lines and clock lines.
  13828. `lax'
  13829. Ignore context. The function matches any part of the
  13830. document looking like a timestamp. This includes comments,
  13831. example blocks...
  13832. For backward-compatibility with Org 9.0, every other non-nil
  13833. value is equivalent to `inactive'.
  13834. When at a timestamp, return the position of the point as a symbol
  13835. among `bracket', `after', `year', `month', `hour', `minute',
  13836. `day' or a number of character from the last know part of the
  13837. time stamp.
  13838. When matching, the match groups are the following:
  13839. group 1: year
  13840. group 2: month
  13841. group 3: day number
  13842. group 4: day name
  13843. group 5: hours, if any
  13844. group 6: minutes, if any"
  13845. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13846. (pos (point))
  13847. (match?
  13848. (let ((boundaries (org-in-regexp regexp)))
  13849. (save-match-data
  13850. (cond ((null boundaries) nil)
  13851. ((eq extended 'lax) t)
  13852. (t
  13853. (or (and (eq extended 'agenda)
  13854. (or (org-at-planning-p)
  13855. (org-at-property-p)
  13856. (and (bound-and-true-p
  13857. org-agenda-include-inactive-timestamps)
  13858. (org-at-clock-log-p))))
  13859. (eq 'timestamp
  13860. (save-excursion
  13861. (when (= pos (cdr boundaries)) (forward-char -1))
  13862. (org-element-type (org-element-context)))))))))))
  13863. (cond
  13864. ((not match?) nil)
  13865. ((= pos (match-beginning 0)) 'bracket)
  13866. ;; Distinguish location right before the closing bracket from
  13867. ;; right after it.
  13868. ((= pos (1- (match-end 0))) 'bracket)
  13869. ((= pos (match-end 0)) 'after)
  13870. ((org-pos-in-match-range pos 2) 'year)
  13871. ((org-pos-in-match-range pos 3) 'month)
  13872. ((org-pos-in-match-range pos 7) 'hour)
  13873. ((org-pos-in-match-range pos 8) 'minute)
  13874. ((or (org-pos-in-match-range pos 4)
  13875. (org-pos-in-match-range pos 5)) 'day)
  13876. ((and (> pos (or (match-end 8) (match-end 5)))
  13877. (< pos (match-end 0)))
  13878. (- pos (or (match-end 8) (match-end 5))))
  13879. (t 'day))))
  13880. (defun org-toggle-timestamp-type ()
  13881. "Toggle the type (<active> or [inactive]) of a time stamp."
  13882. (interactive)
  13883. (when (org-at-timestamp-p 'lax)
  13884. (let ((beg (match-beginning 0)) (end (match-end 0))
  13885. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13886. (save-excursion
  13887. (goto-char beg)
  13888. (while (re-search-forward "[][<>]" end t)
  13889. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13890. t t)))
  13891. (message "Timestamp is now %sactive"
  13892. (if (equal (char-after beg) ?<) "" "in")))))
  13893. (defun org-at-clock-log-p ()
  13894. "Non-nil if point is on a clock log line."
  13895. (and (org-match-line org-clock-line-re)
  13896. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13897. (defvar org-clock-history) ; defined in org-clock.el
  13898. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13899. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13900. "Change the date in the time stamp at point.
  13901. The date is changed by N times WHAT. WHAT can be `day', `month',
  13902. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13903. position in the timestamp determines what is changed.
  13904. When optional argument UPDOWN is non-nil, minutes are rounded
  13905. according to `org-time-stamp-rounding-minutes'.
  13906. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13907. \"--2d\"."
  13908. (let ((origin (point))
  13909. (timestamp? (org-at-timestamp-p 'lax))
  13910. origin-cat
  13911. with-hm inactive
  13912. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13913. extra rem
  13914. ts time time0 fixnext clrgx)
  13915. (unless timestamp? (user-error "Not at a timestamp"))
  13916. (if (and (not what) (eq timestamp? 'bracket))
  13917. (org-toggle-timestamp-type)
  13918. ;; Point isn't on brackets. Remember the part of the time-stamp
  13919. ;; the point was in. Indeed, size of time-stamps may change,
  13920. ;; but point must be kept in the same category nonetheless.
  13921. (setq origin-cat timestamp?)
  13922. (when (and (not what) (not (eq timestamp? 'day))
  13923. org-display-custom-times
  13924. (get-text-property (point) 'display)
  13925. (not (get-text-property (1- (point)) 'display)))
  13926. (setq timestamp? 'day))
  13927. (setq timestamp? (or what timestamp?)
  13928. inactive (= (char-after (match-beginning 0)) ?\[)
  13929. ts (match-string 0))
  13930. (replace-match "")
  13931. (when (string-match
  13932. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13933. ts)
  13934. (setq extra (match-string 1 ts))
  13935. (when suppress-tmp-delay
  13936. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13937. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13938. (setq with-hm t))
  13939. (setq time0 (org-parse-time-string ts))
  13940. (when (and updown
  13941. (eq timestamp? 'minute)
  13942. (not current-prefix-arg))
  13943. ;; This looks like s-up and s-down. Change by one rounding step.
  13944. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13945. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13946. (setcar (cdr time0) (+ (nth 1 time0)
  13947. (if (> n 0) (- rem) (- dm rem))))))
  13948. (setq time
  13949. (apply #'encode-time
  13950. (or (car time0) 0)
  13951. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13952. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13953. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13954. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13955. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13956. (nthcdr 6 time0)))
  13957. (when (and (memq timestamp? '(hour minute))
  13958. extra
  13959. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13960. (setq extra (org-modify-ts-extra
  13961. extra
  13962. (if (eq timestamp? 'hour) 2 5)
  13963. n dm)))
  13964. (when (integerp timestamp?)
  13965. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13966. (when (eq what 'calendar)
  13967. (let ((cal-date (org-get-date-from-calendar)))
  13968. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13969. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13970. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13971. (setcar time0 (or (car time0) 0))
  13972. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13973. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13974. (setq time (apply 'encode-time time0))))
  13975. ;; Insert the new time-stamp, and ensure point stays in the same
  13976. ;; category as before (i.e. not after the last position in that
  13977. ;; category).
  13978. (let ((pos (point)))
  13979. ;; Stay before inserted string. `save-excursion' is of no use.
  13980. (setq org-last-changed-timestamp
  13981. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13982. (goto-char pos))
  13983. (save-match-data
  13984. (looking-at org-ts-regexp3)
  13985. (goto-char
  13986. (pcase origin-cat
  13987. ;; `day' category ends before `hour' if any, or at the end
  13988. ;; of the day name.
  13989. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13990. (`hour (min (match-end 7) origin))
  13991. (`minute (min (1- (match-end 8)) origin))
  13992. ((pred integerp) (min (1- (match-end 0)) origin))
  13993. ;; Point was right after the time-stamp. However, the
  13994. ;; time-stamp length might have changed, so refer to
  13995. ;; (match-end 0) instead.
  13996. (`after (match-end 0))
  13997. ;; `year' and `month' have both fixed size: point couldn't
  13998. ;; have moved into another part.
  13999. (_ origin))))
  14000. ;; Update clock if on a CLOCK line.
  14001. (org-clock-update-time-maybe)
  14002. ;; Maybe adjust the closest clock in `org-clock-history'
  14003. (when org-clock-adjust-closest
  14004. (if (not (and (org-at-clock-log-p)
  14005. (< 1 (length (delq nil (mapcar 'marker-position
  14006. org-clock-history))))))
  14007. (message "No clock to adjust")
  14008. (cond ((save-excursion ; fix previous clock?
  14009. (re-search-backward org-ts-regexp0 nil t)
  14010. (looking-back (concat org-clock-string " \\[")
  14011. (line-beginning-position)))
  14012. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  14013. ((save-excursion ; fix next clock?
  14014. (re-search-backward org-ts-regexp0 nil t)
  14015. (looking-at (concat org-ts-regexp0 "\\] =>")))
  14016. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  14017. (save-window-excursion
  14018. ;; Find closest clock to point, adjust the previous/next one in history
  14019. (let* ((p (save-excursion (org-back-to-heading t)))
  14020. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  14021. (clfixnth
  14022. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  14023. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  14024. (if (not clfixpos)
  14025. (message "No clock to adjust")
  14026. (save-excursion
  14027. (org-goto-marker-or-bmk clfixpos)
  14028. (org-show-subtree)
  14029. (when (re-search-forward clrgx nil t)
  14030. (goto-char (match-beginning 1))
  14031. (let (org-clock-adjust-closest)
  14032. (org-timestamp-change n timestamp? updown))
  14033. (message "Clock adjusted in %s for heading: %s"
  14034. (file-name-nondirectory (buffer-file-name))
  14035. (org-get-heading t t)))))))))
  14036. ;; Try to recenter the calendar window, if any.
  14037. (when (and org-calendar-follow-timestamp-change
  14038. (get-buffer-window "*Calendar*" t)
  14039. (memq timestamp? '(day month year)))
  14040. (org-recenter-calendar (time-to-days time))))))
  14041. (defun org-modify-ts-extra (s pos n dm)
  14042. "Change the different parts of the lead-time and repeat fields in timestamp."
  14043. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  14044. ng h m new rem)
  14045. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  14046. (cond
  14047. ((or (org-pos-in-match-range pos 2)
  14048. (org-pos-in-match-range pos 3))
  14049. (setq m (string-to-number (match-string 3 s))
  14050. h (string-to-number (match-string 2 s)))
  14051. (if (org-pos-in-match-range pos 2)
  14052. (setq h (+ h n))
  14053. (setq n (* dm (with-no-warnings (cl-signum n))))
  14054. (unless (= 0 (setq rem (% m dm)))
  14055. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  14056. (setq m (+ m n)))
  14057. (when (< m 0) (setq m (+ m 60) h (1- h)))
  14058. (when (> m 59) (setq m (- m 60) h (1+ h)))
  14059. (setq h (mod h 24))
  14060. (setq ng 1 new (format "-%02d:%02d" h m)))
  14061. ((org-pos-in-match-range pos 6)
  14062. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  14063. ((org-pos-in-match-range pos 5)
  14064. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  14065. ((org-pos-in-match-range pos 9)
  14066. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  14067. ((org-pos-in-match-range pos 8)
  14068. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  14069. (when ng
  14070. (setq s (concat
  14071. (substring s 0 (match-beginning ng))
  14072. new
  14073. (substring s (match-end ng))))))
  14074. s))
  14075. (defun org-recenter-calendar (d)
  14076. "If the calendar is visible, recenter it to date D."
  14077. (let ((cwin (get-buffer-window "*Calendar*" t)))
  14078. (when cwin
  14079. (let ((calendar-move-hook nil))
  14080. (with-selected-window cwin
  14081. (calendar-goto-date
  14082. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  14083. (defun org-goto-calendar (&optional arg)
  14084. "Go to the Emacs calendar at the current date.
  14085. If there is a time stamp in the current line, go to that date.
  14086. A prefix ARG can be used to force the current date."
  14087. (interactive "P")
  14088. (let ((calendar-move-hook nil)
  14089. (calendar-view-holidays-initially-flag nil)
  14090. (calendar-view-diary-initially-flag nil)
  14091. diff)
  14092. (when (or (org-at-timestamp-p 'lax)
  14093. (org-match-line (concat ".*" org-ts-regexp)))
  14094. (let ((d1 (time-to-days nil))
  14095. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  14096. (setq diff (- d2 d1))))
  14097. (calendar)
  14098. (calendar-goto-today)
  14099. (when (and diff (not arg)) (calendar-forward-day diff))))
  14100. (defun org-get-date-from-calendar ()
  14101. "Return a list (month day year) of date at point in calendar."
  14102. (with-current-buffer "*Calendar*"
  14103. (save-match-data
  14104. (calendar-cursor-to-date))))
  14105. (defun org-date-from-calendar ()
  14106. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  14107. If there is already a time stamp at the cursor position, update it."
  14108. (interactive)
  14109. (if (org-at-timestamp-p 'lax)
  14110. (org-timestamp-change 0 'calendar)
  14111. (let ((cal-date (org-get-date-from-calendar)))
  14112. (org-insert-time-stamp
  14113. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  14114. (defcustom org-image-actual-width t
  14115. "When non-nil, use the actual width of images when inlining them.
  14116. When set to a number, use imagemagick (when available) to set the
  14117. image's width to this value.
  14118. When set to a number in a list, try to get the width from any
  14119. #+ATTR.* keyword if it matches a width specification like
  14120. #+ATTR_HTML: :width 300px
  14121. and fall back on that number if none is found.
  14122. When set to nil, try to get the width from an #+ATTR.* keyword
  14123. and fall back on the original width if none is found.
  14124. When set to any other non-nil value, always use the image width.
  14125. This requires Emacs >= 24.1, built with imagemagick support."
  14126. :group 'org-appearance
  14127. :version "24.4"
  14128. :package-version '(Org . "8.0")
  14129. :type '(choice
  14130. (const :tag "Use the image width" t)
  14131. (integer :tag "Use a number of pixels")
  14132. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  14133. (const :tag "Use #+ATTR* or don't resize" nil)))
  14134. (defcustom org-agenda-inhibit-startup nil
  14135. "Inhibit startup when preparing agenda buffers.
  14136. When this variable is t, the initialization of the Org agenda
  14137. buffers is inhibited: e.g. the visibility state is not set, the
  14138. tables are not re-aligned, etc."
  14139. :type 'boolean
  14140. :version "24.3"
  14141. :group 'org-agenda)
  14142. (defcustom org-agenda-ignore-properties nil
  14143. "Avoid updating text properties when building the agenda.
  14144. Properties are used to prepare buffers for effort estimates,
  14145. appointments, statistics and subtree-local categories.
  14146. If you don't use these in the agenda, you can add them to this
  14147. list and agenda building will be a bit faster.
  14148. The value is a list, with zero or more of the symbols `effort', `appt',
  14149. `stats' or `category'."
  14150. :type '(set :greedy t
  14151. (const effort)
  14152. (const appt)
  14153. (const stats)
  14154. (const category))
  14155. :version "26.1"
  14156. :package-version '(Org . "8.3")
  14157. :group 'org-agenda)
  14158. ;;;; Files
  14159. (defun org-save-all-org-buffers ()
  14160. "Save all Org buffers without user confirmation."
  14161. (interactive)
  14162. (message "Saving all Org buffers...")
  14163. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  14164. (when (featurep 'org-id) (org-id-locations-save))
  14165. (message "Saving all Org buffers... done"))
  14166. (defun org-revert-all-org-buffers ()
  14167. "Revert all Org buffers.
  14168. Prompt for confirmation when there are unsaved changes.
  14169. Be sure you know what you are doing before letting this function
  14170. overwrite your changes.
  14171. This function is useful in a setup where one tracks Org files
  14172. with a version control system, to revert on one machine after pulling
  14173. changes from another. I believe the procedure must be like this:
  14174. 1. M-x org-save-all-org-buffers
  14175. 2. Pull changes from the other machine, resolve conflicts
  14176. 3. M-x org-revert-all-org-buffers"
  14177. (interactive)
  14178. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  14179. (user-error "Abort"))
  14180. (save-excursion
  14181. (save-window-excursion
  14182. (dolist (b (buffer-list))
  14183. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  14184. (with-current-buffer b buffer-file-name))
  14185. (pop-to-buffer-same-window b)
  14186. (revert-buffer t 'no-confirm)))
  14187. (when (and (featurep 'org-id) org-id-track-globally)
  14188. (org-id-locations-load)))))
  14189. ;;;; Agenda files
  14190. ;;;###autoload
  14191. (defun org-switchb (&optional arg)
  14192. "Switch between Org buffers.
  14193. With `\\[universal-argument]' prefix, restrict available buffers to files.
  14194. With `\\[universal-argument] \\[universal-argument]' \
  14195. prefix, restrict available buffers to agenda files."
  14196. (interactive "P")
  14197. (let ((blist (org-buffer-list
  14198. (cond ((equal arg '(4)) 'files)
  14199. ((equal arg '(16)) 'agenda)))))
  14200. (pop-to-buffer-same-window
  14201. (completing-read "Org buffer: "
  14202. (mapcar #'list (mapcar #'buffer-name blist))
  14203. nil t))))
  14204. (defun org-buffer-list (&optional predicate exclude-tmp)
  14205. "Return a list of Org buffers.
  14206. PREDICATE can be `export', `files' or `agenda'.
  14207. export restrict the list to Export buffers.
  14208. files restrict the list to buffers visiting Org files.
  14209. agenda restrict the list to buffers visiting agenda files.
  14210. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  14211. (let* ((bfn nil)
  14212. (agenda-files (and (eq predicate 'agenda)
  14213. (mapcar 'file-truename (org-agenda-files t))))
  14214. (filter
  14215. (cond
  14216. ((eq predicate 'files)
  14217. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  14218. ((eq predicate 'export)
  14219. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  14220. ((eq predicate 'agenda)
  14221. (lambda (b)
  14222. (with-current-buffer b
  14223. (and (derived-mode-p 'org-mode)
  14224. (setq bfn (buffer-file-name b))
  14225. (member (file-truename bfn) agenda-files)))))
  14226. (t (lambda (b) (with-current-buffer b
  14227. (or (derived-mode-p 'org-mode)
  14228. (string-match "\\*Org .*Export"
  14229. (buffer-name b)))))))))
  14230. (delq nil
  14231. (mapcar
  14232. (lambda(b)
  14233. (if (and (funcall filter b)
  14234. (or (not exclude-tmp)
  14235. (not (string-match "tmp" (buffer-name b)))))
  14236. b
  14237. nil))
  14238. (buffer-list)))))
  14239. (defun org-agenda-files (&optional unrestricted archives)
  14240. "Get the list of agenda files.
  14241. Optional UNRESTRICTED means return the full list even if a restriction
  14242. is currently in place.
  14243. When ARCHIVES is t, include all archive files that are really being
  14244. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  14245. `org-agenda-archives-mode' is t."
  14246. (let ((files
  14247. (cond
  14248. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  14249. ((stringp org-agenda-files) (org-read-agenda-file-list))
  14250. ((listp org-agenda-files) org-agenda-files)
  14251. (t (error "Invalid value of `org-agenda-files'")))))
  14252. (setq files (apply 'append
  14253. (mapcar (lambda (f)
  14254. (if (file-directory-p f)
  14255. (directory-files
  14256. f t org-agenda-file-regexp)
  14257. (list f)))
  14258. files)))
  14259. (when org-agenda-skip-unavailable-files
  14260. (setq files (delq nil
  14261. (mapcar (function
  14262. (lambda (file)
  14263. (and (file-readable-p file) file)))
  14264. files))))
  14265. (when (or (eq archives t)
  14266. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  14267. (setq files (org-add-archive-files files)))
  14268. files))
  14269. (defun org-agenda-file-p (&optional file)
  14270. "Return non-nil, if FILE is an agenda file.
  14271. If FILE is omitted, use the file associated with the current
  14272. buffer."
  14273. (let ((fname (or file (buffer-file-name))))
  14274. (and fname
  14275. (member (file-truename fname)
  14276. (mapcar #'file-truename (org-agenda-files t))))))
  14277. (defun org-edit-agenda-file-list ()
  14278. "Edit the list of agenda files.
  14279. Depending on setup, this either uses customize to edit the variable
  14280. `org-agenda-files', or it visits the file that is holding the list. In the
  14281. latter case, the buffer is set up in a way that saving it automatically kills
  14282. the buffer and restores the previous window configuration."
  14283. (interactive)
  14284. (if (stringp org-agenda-files)
  14285. (let ((cw (current-window-configuration)))
  14286. (find-file org-agenda-files)
  14287. (setq-local org-window-configuration cw)
  14288. (add-hook 'after-save-hook
  14289. (lambda ()
  14290. (set-window-configuration
  14291. (prog1 org-window-configuration
  14292. (kill-buffer (current-buffer))))
  14293. (org-install-agenda-files-menu)
  14294. (message "New agenda file list installed"))
  14295. nil 'local)
  14296. (message "%s" (substitute-command-keys
  14297. "Edit list and finish with \\[save-buffer]")))
  14298. (customize-variable 'org-agenda-files)))
  14299. (defun org-store-new-agenda-file-list (list)
  14300. "Set new value for the agenda file list and save it correctly."
  14301. (if (stringp org-agenda-files)
  14302. (let ((fe (org-read-agenda-file-list t)) b u)
  14303. (while (setq b (find-buffer-visiting org-agenda-files))
  14304. (kill-buffer b))
  14305. (with-temp-file org-agenda-files
  14306. (insert
  14307. (mapconcat
  14308. (lambda (f) ;; Keep un-expanded entries.
  14309. (if (setq u (assoc f fe))
  14310. (cdr u)
  14311. f))
  14312. list "\n")
  14313. "\n")))
  14314. (let ((org-mode-hook nil) (org-inhibit-startup t)
  14315. (org-insert-mode-line-in-empty-file nil))
  14316. (setq org-agenda-files list)
  14317. (customize-save-variable 'org-agenda-files org-agenda-files))))
  14318. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  14319. "Read the list of agenda files from a file.
  14320. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  14321. filenames, used by `org-store-new-agenda-file-list' to write back
  14322. un-expanded file names."
  14323. (when (file-directory-p org-agenda-files)
  14324. (error "`org-agenda-files' cannot be a single directory"))
  14325. (when (stringp org-agenda-files)
  14326. (with-temp-buffer
  14327. (insert-file-contents org-agenda-files)
  14328. (mapcar
  14329. (lambda (f)
  14330. (let ((e (expand-file-name (substitute-in-file-name f)
  14331. org-directory)))
  14332. (if pair-with-expansion
  14333. (cons e f)
  14334. e)))
  14335. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  14336. ;;;###autoload
  14337. (defun org-cycle-agenda-files ()
  14338. "Cycle through the files in `org-agenda-files'.
  14339. If the current buffer visits an agenda file, find the next one in the list.
  14340. If the current buffer does not, find the first agenda file."
  14341. (interactive)
  14342. (let* ((fs (or (org-agenda-files t)
  14343. (user-error "No agenda files")))
  14344. (files (copy-sequence fs))
  14345. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  14346. file)
  14347. (when tcf
  14348. (while (and (setq file (pop files))
  14349. (not (equal (file-truename file) tcf)))))
  14350. (find-file (car (or files fs)))
  14351. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  14352. (defun org-agenda-file-to-front (&optional to-end)
  14353. "Move/add the current file to the top of the agenda file list.
  14354. If the file is not present in the list, it is added to the front. If it is
  14355. present, it is moved there. With optional argument TO-END, add/move to the
  14356. end of the list."
  14357. (interactive "P")
  14358. (let ((org-agenda-skip-unavailable-files nil)
  14359. (file-alist (mapcar (lambda (x)
  14360. (cons (file-truename x) x))
  14361. (org-agenda-files t)))
  14362. (ctf (file-truename
  14363. (or buffer-file-name
  14364. (user-error "Please save the current buffer to a file"))))
  14365. x had)
  14366. (setq x (assoc ctf file-alist) had x)
  14367. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  14368. (if to-end
  14369. (setq file-alist (append (delq x file-alist) (list x)))
  14370. (setq file-alist (cons x (delq x file-alist))))
  14371. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  14372. (org-install-agenda-files-menu)
  14373. (message "File %s to %s of agenda file list"
  14374. (if had "moved" "added") (if to-end "end" "front"))))
  14375. (defun org-remove-file (&optional file)
  14376. "Remove current file from the list of files in variable `org-agenda-files'.
  14377. These are the files which are being checked for agenda entries.
  14378. Optional argument FILE means use this file instead of the current."
  14379. (interactive)
  14380. (let* ((org-agenda-skip-unavailable-files nil)
  14381. (file (or file buffer-file-name
  14382. (user-error "Current buffer does not visit a file")))
  14383. (true-file (file-truename file))
  14384. (afile (abbreviate-file-name file))
  14385. (files (delq nil (mapcar
  14386. (lambda (x)
  14387. (unless (equal true-file
  14388. (file-truename x))
  14389. x))
  14390. (org-agenda-files t)))))
  14391. (if (not (= (length files) (length (org-agenda-files t))))
  14392. (progn
  14393. (org-store-new-agenda-file-list files)
  14394. (org-install-agenda-files-menu)
  14395. (message "Removed from Org Agenda list: %s" afile))
  14396. (message "File was not in list: %s (not removed)" afile))))
  14397. (defun org-file-menu-entry (file)
  14398. (vector file (list 'find-file file) t))
  14399. (defun org-check-agenda-file (file)
  14400. "Make sure FILE exists. If not, ask user what to do."
  14401. (unless (file-exists-p file)
  14402. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  14403. (abbreviate-file-name file))
  14404. (let ((r (downcase (read-char-exclusive))))
  14405. (cond
  14406. ((equal r ?r)
  14407. (org-remove-file file)
  14408. (throw 'nextfile t))
  14409. (t (user-error "Abort"))))))
  14410. (defun org-get-agenda-file-buffer (file)
  14411. "Get an agenda buffer visiting FILE.
  14412. If the buffer needs to be created, add it to the list of buffers
  14413. which might be released later."
  14414. (let ((buf (org-find-base-buffer-visiting file)))
  14415. (if buf
  14416. buf ; just return it
  14417. ;; Make a new buffer and remember it
  14418. (setq buf (find-file-noselect file))
  14419. (when buf (push buf org-agenda-new-buffers))
  14420. buf)))
  14421. (defun org-release-buffers (blist)
  14422. "Release all buffers in list, asking the user for confirmation when needed.
  14423. When a buffer is unmodified, it is just killed. When modified, it is saved
  14424. \(if the user agrees) and then killed."
  14425. (let (file)
  14426. (dolist (buf blist)
  14427. (setq file (buffer-file-name buf))
  14428. (when (and (buffer-modified-p buf)
  14429. file
  14430. (y-or-n-p (format "Save file %s? " file)))
  14431. (with-current-buffer buf (save-buffer)))
  14432. (kill-buffer buf))))
  14433. (defun org-agenda-prepare-buffers (files)
  14434. "Create buffers for all agenda files, protect archived trees and comments."
  14435. (interactive)
  14436. (let ((pa '(:org-archived t))
  14437. (pc '(:org-comment t))
  14438. (pall '(:org-archived t :org-comment t))
  14439. (inhibit-read-only t)
  14440. (org-inhibit-startup org-agenda-inhibit-startup)
  14441. (rea (org-make-tag-string (list org-archive-tag)))
  14442. re pos)
  14443. (setq org-tag-alist-for-agenda nil
  14444. org-tag-groups-alist-for-agenda nil)
  14445. (save-excursion
  14446. (save-restriction
  14447. (dolist (file files)
  14448. (catch 'nextfile
  14449. (if (bufferp file)
  14450. (set-buffer file)
  14451. (org-check-agenda-file file)
  14452. (set-buffer (org-get-agenda-file-buffer file)))
  14453. (widen)
  14454. (org-set-regexps-and-options 'tags-only)
  14455. (setq pos (point))
  14456. (or (memq 'category org-agenda-ignore-properties)
  14457. (org-refresh-category-properties))
  14458. (or (memq 'stats org-agenda-ignore-properties)
  14459. (org-refresh-stats-properties))
  14460. (or (memq 'effort org-agenda-ignore-properties)
  14461. (org-refresh-effort-properties))
  14462. (or (memq 'appt org-agenda-ignore-properties)
  14463. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14464. (setq org-todo-keywords-for-agenda
  14465. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14466. (setq org-done-keywords-for-agenda
  14467. (append org-done-keywords-for-agenda org-done-keywords))
  14468. (setq org-todo-keyword-alist-for-agenda
  14469. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14470. (setq org-tag-alist-for-agenda
  14471. (org--tag-add-to-alist
  14472. org-tag-alist-for-agenda
  14473. org-current-tag-alist))
  14474. ;; Merge current file's tag groups into global
  14475. ;; `org-tag-groups-alist-for-agenda'.
  14476. (when org-group-tags
  14477. (dolist (alist org-tag-groups-alist)
  14478. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14479. (if old
  14480. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14481. (push alist org-tag-groups-alist-for-agenda)))))
  14482. (with-silent-modifications
  14483. (save-excursion
  14484. (remove-text-properties (point-min) (point-max) pall)
  14485. (when org-agenda-skip-archived-trees
  14486. (goto-char (point-min))
  14487. (while (re-search-forward rea nil t)
  14488. (when (org-at-heading-p t)
  14489. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  14490. (goto-char (point-min))
  14491. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  14492. (while (re-search-forward re nil t)
  14493. (when (save-match-data (org-in-commented-heading-p t))
  14494. (add-text-properties
  14495. (match-beginning 0) (org-end-of-subtree t) pc)))))
  14496. (goto-char pos)))))
  14497. (setq org-todo-keywords-for-agenda
  14498. (org-uniquify org-todo-keywords-for-agenda))
  14499. (setq org-todo-keyword-alist-for-agenda
  14500. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14501. ;;;; CDLaTeX minor mode
  14502. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14503. "Keymap for the minor `org-cdlatex-mode'.")
  14504. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14505. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14506. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14507. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14508. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14509. (defvar org-cdlatex-texmathp-advice-is-done nil
  14510. "Flag remembering if we have applied the advice to texmathp already.")
  14511. (define-minor-mode org-cdlatex-mode
  14512. "Toggle the minor `org-cdlatex-mode'.
  14513. This mode supports entering LaTeX environment and math in LaTeX fragments
  14514. in Org mode.
  14515. \\{org-cdlatex-mode-map}"
  14516. nil " OCDL" nil
  14517. (when org-cdlatex-mode
  14518. (require 'cdlatex)
  14519. (run-hooks 'cdlatex-mode-hook)
  14520. (cdlatex-compute-tables))
  14521. (unless org-cdlatex-texmathp-advice-is-done
  14522. (setq org-cdlatex-texmathp-advice-is-done t)
  14523. (defadvice texmathp (around org-math-always-on activate)
  14524. "Always return t in Org buffers.
  14525. This is because we want to insert math symbols without dollars even outside
  14526. the LaTeX math segments. If Org mode thinks that point is actually inside
  14527. an embedded LaTeX fragment, let `texmathp' do its job.
  14528. `\\[org-cdlatex-mode-map]'"
  14529. (interactive)
  14530. (let (p)
  14531. (cond
  14532. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14533. ((eq this-command 'cdlatex-math-symbol)
  14534. (setq ad-return-value t
  14535. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14536. (t
  14537. (let ((p (org-inside-LaTeX-fragment-p)))
  14538. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14539. (setq ad-return-value t
  14540. texmathp-why '("Org mode embedded math" . 0))
  14541. (when p ad-do-it)))))))))
  14542. (defun turn-on-org-cdlatex ()
  14543. "Unconditionally turn on `org-cdlatex-mode'."
  14544. (org-cdlatex-mode 1))
  14545. (defun org-try-cdlatex-tab ()
  14546. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14547. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14548. - inside a LaTeX fragment, or
  14549. - after the first word in a line, where an abbreviation expansion could
  14550. insert a LaTeX environment."
  14551. (when org-cdlatex-mode
  14552. (cond
  14553. ;; Before any word on the line: No expansion possible.
  14554. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14555. ;; Just after first word on the line: Expand it. Make sure it
  14556. ;; cannot happen on headlines, though.
  14557. ((save-excursion
  14558. (skip-chars-backward "a-zA-Z0-9*")
  14559. (skip-chars-backward " \t")
  14560. (and (bolp) (not (org-at-heading-p))))
  14561. (cdlatex-tab) t)
  14562. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14563. (defun org-cdlatex-underscore-caret (&optional _arg)
  14564. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14565. Revert to the normal definition outside of these fragments."
  14566. (interactive "P")
  14567. (if (org-inside-LaTeX-fragment-p)
  14568. (call-interactively 'cdlatex-sub-superscript)
  14569. (let (org-cdlatex-mode)
  14570. (call-interactively (key-binding (vector last-input-event))))))
  14571. (defun org-cdlatex-math-modify (&optional _arg)
  14572. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14573. Revert to the normal definition outside of these fragments."
  14574. (interactive "P")
  14575. (if (org-inside-LaTeX-fragment-p)
  14576. (call-interactively 'cdlatex-math-modify)
  14577. (let (org-cdlatex-mode)
  14578. (call-interactively (key-binding (vector last-input-event))))))
  14579. (defun org-cdlatex-environment-indent (&optional environment item)
  14580. "Execute `cdlatex-environment' and indent the inserted environment.
  14581. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14582. The inserted environment is indented to current indentation
  14583. unless point is at the beginning of the line, in which the
  14584. environment remains unintended."
  14585. (interactive)
  14586. ;; cdlatex-environment always return nil. Therefore, capture output
  14587. ;; first and determine if an environment was selected.
  14588. (let* ((beg (point-marker))
  14589. (end (copy-marker (point) t))
  14590. (inserted (progn
  14591. (ignore-errors (cdlatex-environment environment item))
  14592. (< beg end)))
  14593. ;; Figure out how many lines to move forward after the
  14594. ;; environment has been inserted.
  14595. (lines (when inserted
  14596. (save-excursion
  14597. (- (cl-loop while (< beg (point))
  14598. with x = 0
  14599. do (forward-line -1)
  14600. (cl-incf x)
  14601. finally return x)
  14602. (if (progn (goto-char beg)
  14603. (and (progn (skip-chars-forward " \t") (eolp))
  14604. (progn (skip-chars-backward " \t") (bolp))))
  14605. 1 0)))))
  14606. (env (org-trim (delete-and-extract-region beg end))))
  14607. (when inserted
  14608. ;; Get indentation of next line unless at column 0.
  14609. (let ((ind (if (bolp) 0
  14610. (save-excursion
  14611. (org-return-indent)
  14612. (prog1 (current-indentation)
  14613. (when (progn (skip-chars-forward " \t") (eolp))
  14614. (delete-region beg (point)))))))
  14615. (bol (progn (skip-chars-backward " \t") (bolp))))
  14616. ;; Insert a newline before environment unless at column zero
  14617. ;; to "escape" the current line. Insert a newline if
  14618. ;; something is one the same line as \end{ENVIRONMENT}.
  14619. (insert
  14620. (concat (unless bol "\n") env
  14621. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14622. (unless (zerop ind)
  14623. (save-excursion
  14624. (goto-char beg)
  14625. (while (< (point) end)
  14626. (unless (eolp) (indent-line-to ind))
  14627. (forward-line))))
  14628. (goto-char beg)
  14629. (forward-line lines)
  14630. (indent-line-to ind)))
  14631. (set-marker beg nil)
  14632. (set-marker end nil)))
  14633. ;;;; LaTeX fragments
  14634. (defun org-inside-LaTeX-fragment-p ()
  14635. "Test if point is inside a LaTeX fragment.
  14636. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14637. sequence appearing also before point.
  14638. Even though the matchers for math are configurable, this function assumes
  14639. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14640. delimiters are skipped when they have been removed by customization.
  14641. The return value is nil, or a cons cell with the delimiter and the
  14642. position of this delimiter.
  14643. This function does a reasonably good job, but can locally be fooled by
  14644. for example currency specifications. For example it will assume being in
  14645. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14646. fragments that are properly closed, but during editing, we have to live
  14647. with the uncertainty caused by missing closing delimiters. This function
  14648. looks only before point, not after."
  14649. (catch 'exit
  14650. (let ((pos (point))
  14651. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14652. (lim (save-excursion (org-backward-paragraph) (point)))
  14653. dd-on str (start 0) m re)
  14654. (goto-char pos)
  14655. (when dodollar
  14656. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14657. re (nth 1 (assoc "$" org-latex-regexps)))
  14658. (while (string-match re str start)
  14659. (cond
  14660. ((= (match-end 0) (length str))
  14661. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14662. ((= (match-end 0) (- (length str) 5))
  14663. (throw 'exit nil))
  14664. (t (setq start (match-end 0))))))
  14665. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14666. (goto-char pos)
  14667. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14668. (and (match-beginning 2) (throw 'exit nil))
  14669. ;; count $$
  14670. (while (re-search-backward "\\$\\$" lim t)
  14671. (setq dd-on (not dd-on)))
  14672. (goto-char pos)
  14673. (when dd-on (cons "$$" m))))))
  14674. (defun org-inside-latex-macro-p ()
  14675. "Is point inside a LaTeX macro or its arguments?"
  14676. (save-match-data
  14677. (org-in-regexp
  14678. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14679. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14680. "Build an overlay between BEG and END using IMAGE file.
  14681. Argument IMAGETYPE is the extension of the displayed image,
  14682. as a string. It defaults to \"png\"."
  14683. (let ((ov (make-overlay beg end))
  14684. (imagetype (or (intern imagetype) 'png)))
  14685. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14686. (overlay-put ov 'evaporate t)
  14687. (overlay-put ov
  14688. 'modification-hooks
  14689. (list (lambda (o _flag _beg _end &optional _l)
  14690. (delete-overlay o))))
  14691. (overlay-put ov
  14692. 'display
  14693. (list 'image :type imagetype :file image :ascent 'center))))
  14694. (defun org-clear-latex-preview (&optional beg end)
  14695. "Remove all overlays with LaTeX fragment images in current buffer.
  14696. When optional arguments BEG and END are non-nil, remove all
  14697. overlays between them instead. Return a non-nil value when some
  14698. overlays were removed, nil otherwise."
  14699. (let ((overlays
  14700. (cl-remove-if-not
  14701. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14702. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14703. (mapc #'delete-overlay overlays)
  14704. overlays))
  14705. (defun org--latex-preview-region (beg end)
  14706. "Preview LaTeX fragments between BEG and END.
  14707. BEG and END are buffer positions."
  14708. (let ((file (buffer-file-name (buffer-base-buffer))))
  14709. (save-excursion
  14710. (org-format-latex
  14711. (concat org-preview-latex-image-directory "org-ltximg")
  14712. beg end
  14713. ;; Emacs cannot overlay images from remote hosts. Create it in
  14714. ;; `temporary-file-directory' instead.
  14715. (if (or (not file) (file-remote-p file))
  14716. temporary-file-directory
  14717. default-directory)
  14718. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14719. (defun org-latex-preview (&optional arg)
  14720. "Toggle preview of the LaTeX fragment at point.
  14721. If the cursor is on a LaTeX fragment, create the image and
  14722. overlay it over the source code, if there is none. Remove it
  14723. otherwise. If there is no fragment at point, display images for
  14724. all fragments in the current section.
  14725. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14726. for all fragments
  14727. in the current section.
  14728. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14729. argument ARG, display image for all
  14730. fragments in the buffer.
  14731. With a `\\[universal-argument] \\[universal-argument] \
  14732. \\[universal-argument]' prefix argument ARG, clear image for all
  14733. fragments in the buffer."
  14734. (interactive "P")
  14735. (cond
  14736. ((not (display-graphic-p)) nil)
  14737. ;; Clear whole buffer.
  14738. ((equal arg '(64))
  14739. (org-clear-latex-preview (point-min) (point-max))
  14740. (message "LaTeX previews removed from buffer"))
  14741. ;; Preview whole buffer.
  14742. ((equal arg '(16))
  14743. (message "Creating LaTeX previews in buffer...")
  14744. (org--latex-preview-region (point-min) (point-max))
  14745. (message "Creating LaTeX previews in buffer... done."))
  14746. ;; Clear current section.
  14747. ((equal arg '(4))
  14748. (org-clear-latex-preview
  14749. (if (org-before-first-heading-p) (point-min)
  14750. (save-excursion
  14751. (org-with-limited-levels (org-back-to-heading t) (point))))
  14752. (org-with-limited-levels (org-entry-end-position))))
  14753. ;; Toggle preview on LaTeX code at point.
  14754. ((let ((datum (org-element-context)))
  14755. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14756. (let ((beg (org-element-property :begin datum))
  14757. (end (org-element-property :end datum)))
  14758. (if (org-clear-latex-preview beg end)
  14759. (message "LaTeX preview removed")
  14760. (message "Creating LaTeX preview...")
  14761. (org--latex-preview-region beg end)
  14762. (message "Creating LaTeX preview... done."))
  14763. t))))
  14764. ;; Preview current section.
  14765. (t
  14766. (let ((beg (if (org-before-first-heading-p) (point-min)
  14767. (save-excursion
  14768. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14769. (end (org-with-limited-levels (org-entry-end-position))))
  14770. (message "Creating LaTeX previews in section...")
  14771. (org--latex-preview-region beg end)
  14772. (message "Creating LaTeX previews in section... done.")))))
  14773. (defun org-format-latex
  14774. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14775. "Replace LaTeX fragments with links to an image.
  14776. The function takes care of creating the replacement image.
  14777. Only consider fragments between BEG and END when those are
  14778. provided.
  14779. When optional argument OVERLAYS is non-nil, display the image on
  14780. top of the fragment instead of replacing it.
  14781. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14782. Some of the options can be changed using the variable
  14783. `org-format-latex-options', which see."
  14784. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14785. (unless (eq processing-type 'verbatim)
  14786. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14787. (cnt 0)
  14788. checkdir-flag)
  14789. (goto-char (or beg (point-min)))
  14790. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14791. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14792. (overlay-recenter (or end (point-max))))
  14793. (while (re-search-forward math-regexp end t)
  14794. (unless (and overlays
  14795. (eq (get-char-property (point) 'org-overlay-type)
  14796. 'org-latex-overlay))
  14797. (let* ((context (org-element-context))
  14798. (type (org-element-type context)))
  14799. (when (memq type '(latex-environment latex-fragment))
  14800. (let ((block-type (eq type 'latex-environment))
  14801. (value (org-element-property :value context))
  14802. (beg (org-element-property :begin context))
  14803. (end (save-excursion
  14804. (goto-char (org-element-property :end context))
  14805. (skip-chars-backward " \r\t\n")
  14806. (point))))
  14807. (cond
  14808. ((eq processing-type 'mathjax)
  14809. ;; Prepare for MathJax processing.
  14810. (if (not (string-match "\\`\\$\\$?" value))
  14811. (goto-char end)
  14812. (delete-region beg end)
  14813. (if (string= (match-string 0 value) "$$")
  14814. (insert "\\[" (substring value 2 -2) "\\]")
  14815. (insert "\\(" (substring value 1 -1) "\\)"))))
  14816. ((assq processing-type org-preview-latex-process-alist)
  14817. ;; Process to an image.
  14818. (cl-incf cnt)
  14819. (goto-char beg)
  14820. (let* ((processing-info
  14821. (cdr (assq processing-type org-preview-latex-process-alist)))
  14822. (face (face-at-point))
  14823. ;; Get the colors from the face at point.
  14824. (fg
  14825. (let ((color (plist-get org-format-latex-options
  14826. :foreground)))
  14827. (if (and forbuffer (eq color 'auto))
  14828. (face-attribute face :foreground nil 'default)
  14829. color)))
  14830. (bg
  14831. (let ((color (plist-get org-format-latex-options
  14832. :background)))
  14833. (if (and forbuffer (eq color 'auto))
  14834. (face-attribute face :background nil 'default)
  14835. color)))
  14836. (hash (sha1 (prin1-to-string
  14837. (list org-format-latex-header
  14838. org-latex-default-packages-alist
  14839. org-latex-packages-alist
  14840. org-format-latex-options
  14841. forbuffer value fg bg))))
  14842. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14843. (absprefix (expand-file-name prefix dir))
  14844. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14845. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14846. (sep (and block-type "\n\n"))
  14847. (link (concat sep "[[file:" linkfile "]]" sep))
  14848. (options
  14849. (org-combine-plists
  14850. org-format-latex-options
  14851. `(:foreground ,fg :background ,bg))))
  14852. (when msg (message msg cnt))
  14853. (unless checkdir-flag ; Ensure the directory exists.
  14854. (setq checkdir-flag t)
  14855. (let ((todir (file-name-directory absprefix)))
  14856. (unless (file-directory-p todir)
  14857. (make-directory todir t))))
  14858. (unless (file-exists-p movefile)
  14859. (org-create-formula-image
  14860. value movefile options forbuffer processing-type))
  14861. (if overlays
  14862. (progn
  14863. (dolist (o (overlays-in beg end))
  14864. (when (eq (overlay-get o 'org-overlay-type)
  14865. 'org-latex-overlay)
  14866. (delete-overlay o)))
  14867. (org--make-preview-overlay beg end movefile imagetype)
  14868. (goto-char end))
  14869. (delete-region beg end)
  14870. (insert
  14871. (org-add-props link
  14872. (list 'org-latex-src
  14873. (replace-regexp-in-string "\"" "" value)
  14874. 'org-latex-src-embed-type
  14875. (if block-type 'paragraph 'character)))))))
  14876. ((eq processing-type 'mathml)
  14877. ;; Process to MathML.
  14878. (unless (org-format-latex-mathml-available-p)
  14879. (user-error "LaTeX to MathML converter not configured"))
  14880. (cl-incf cnt)
  14881. (when msg (message msg cnt))
  14882. (goto-char beg)
  14883. (delete-region beg end)
  14884. (insert (org-format-latex-as-mathml
  14885. value block-type prefix dir)))
  14886. (t
  14887. (error "Unknown conversion process %s for LaTeX fragments"
  14888. processing-type)))))))))))
  14889. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14890. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14891. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14892. sucessful, return the portion between \"<math...> </math>\"
  14893. elements otherwise return nil. When MATHML-FILE is specified,
  14894. write the results in to that file. When invoked as an
  14895. interactive command, prompt for LATEX-FRAG, with initial value
  14896. set to the current active region and echo the results for user
  14897. inspection."
  14898. (interactive (list (let ((frag (when (org-region-active-p)
  14899. (buffer-substring-no-properties
  14900. (region-beginning) (region-end)))))
  14901. (read-string "LaTeX Fragment: " frag nil frag))))
  14902. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14903. (let* ((tmp-in-file
  14904. (let ((file (file-relative-name
  14905. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14906. (write-region latex-frag nil file)
  14907. file))
  14908. (tmp-out-file (file-relative-name
  14909. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14910. (cmd (format-spec
  14911. org-latex-to-mathml-convert-command
  14912. `((?j . ,(and org-latex-to-mathml-jar-file
  14913. (shell-quote-argument
  14914. (expand-file-name
  14915. org-latex-to-mathml-jar-file))))
  14916. (?I . ,(shell-quote-argument tmp-in-file))
  14917. (?i . ,latex-frag)
  14918. (?o . ,(shell-quote-argument tmp-out-file)))))
  14919. mathml shell-command-output)
  14920. (when (called-interactively-p 'any)
  14921. (unless (org-format-latex-mathml-available-p)
  14922. (user-error "LaTeX to MathML converter not configured")))
  14923. (message "Running %s" cmd)
  14924. (setq shell-command-output (shell-command-to-string cmd))
  14925. (setq mathml
  14926. (when (file-readable-p tmp-out-file)
  14927. (with-current-buffer (find-file-noselect tmp-out-file t)
  14928. (goto-char (point-min))
  14929. (when (re-search-forward
  14930. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14931. (regexp-quote
  14932. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14933. nil t)
  14934. (prog1 (match-string 0) (kill-buffer))))))
  14935. (cond
  14936. (mathml
  14937. (setq mathml
  14938. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14939. (when mathml-file
  14940. (write-region mathml nil mathml-file))
  14941. (when (called-interactively-p 'any)
  14942. (message mathml)))
  14943. ((message "LaTeX to MathML conversion failed")
  14944. (message shell-command-output)))
  14945. (delete-file tmp-in-file)
  14946. (when (file-exists-p tmp-out-file)
  14947. (delete-file tmp-out-file))
  14948. mathml))
  14949. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14950. prefix &optional dir)
  14951. "Use `org-create-math-formula' but check local cache first."
  14952. (let* ((absprefix (expand-file-name prefix dir))
  14953. (print-length nil) (print-level nil)
  14954. (formula-id (concat
  14955. "formula-"
  14956. (sha1
  14957. (prin1-to-string
  14958. (list latex-frag
  14959. org-latex-to-mathml-convert-command)))))
  14960. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14961. (formula-cache-dir (file-name-directory formula-cache)))
  14962. (unless (file-directory-p formula-cache-dir)
  14963. (make-directory formula-cache-dir t))
  14964. (unless (file-exists-p formula-cache)
  14965. (org-create-math-formula latex-frag formula-cache))
  14966. (if (file-exists-p formula-cache)
  14967. ;; Successful conversion. Return the link to MathML file.
  14968. (org-add-props
  14969. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14970. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14971. 'org-latex-src-embed-type (if latex-frag-type
  14972. 'paragraph 'character)))
  14973. ;; Failed conversion. Return the LaTeX fragment verbatim
  14974. latex-frag)))
  14975. (defun org--get-display-dpi ()
  14976. "Get the DPI of the display.
  14977. The function assumes that the display has the same pixel width in
  14978. the horizontal and vertical directions."
  14979. (if (display-graphic-p)
  14980. (round (/ (display-pixel-height)
  14981. (/ (display-mm-height) 25.4)))
  14982. (error "Attempt to calculate the dpi of a non-graphic display")))
  14983. (defun org-create-formula-image
  14984. (string tofile options buffer &optional processing-type)
  14985. "Create an image from LaTeX source using external processes.
  14986. The LaTeX STRING is saved to a temporary LaTeX file, then
  14987. converted to an image file by process PROCESSING-TYPE defined in
  14988. `org-preview-latex-process-alist'. A nil value defaults to
  14989. `org-preview-latex-default-process'.
  14990. The generated image file is eventually moved to TOFILE.
  14991. The OPTIONS argument controls the size, foreground color and
  14992. background color of the generated image.
  14993. When BUFFER non-nil, this function is used for LaTeX previewing.
  14994. Otherwise, it is used to deal with LaTeX snippets showed in
  14995. a HTML file."
  14996. (let* ((processing-type (or processing-type
  14997. org-preview-latex-default-process))
  14998. (processing-info
  14999. (cdr (assq processing-type org-preview-latex-process-alist)))
  15000. (programs (plist-get processing-info :programs))
  15001. (error-message (or (plist-get processing-info :message) ""))
  15002. (image-input-type (plist-get processing-info :image-input-type))
  15003. (image-output-type (plist-get processing-info :image-output-type))
  15004. (post-clean (or (plist-get processing-info :post-clean)
  15005. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  15006. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  15007. (latex-header
  15008. (or (plist-get processing-info :latex-header)
  15009. (org-latex-make-preamble
  15010. (org-export-get-environment (org-export-get-backend 'latex))
  15011. org-format-latex-header
  15012. 'snippet)))
  15013. (latex-compiler (plist-get processing-info :latex-compiler))
  15014. (image-converter (plist-get processing-info :image-converter))
  15015. (tmpdir temporary-file-directory)
  15016. (texfilebase (make-temp-name
  15017. (expand-file-name "orgtex" tmpdir)))
  15018. (texfile (concat texfilebase ".tex"))
  15019. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  15020. '(1.0 . 1.0)))
  15021. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  15022. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  15023. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  15024. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  15025. "Black"))
  15026. (bg (or (plist-get options (if buffer :background :html-background))
  15027. "Transparent"))
  15028. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  15029. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  15030. (dolist (program programs)
  15031. (org-check-external-command program error-message))
  15032. (if (eq fg 'default)
  15033. (setq fg (org-latex-color :foreground))
  15034. (setq fg (org-latex-color-format fg)))
  15035. (if (eq bg 'default)
  15036. (setq bg (org-latex-color :background))
  15037. (setq bg (org-latex-color-format
  15038. (if (string= bg "Transparent") "white" bg))))
  15039. (with-temp-file texfile
  15040. (insert latex-header)
  15041. (insert "\n\\begin{document}\n"
  15042. "\\definecolor{fg}{rgb}{" fg "}\n"
  15043. "\\definecolor{bg}{rgb}{" bg "}\n"
  15044. "\n\\pagecolor{bg}\n"
  15045. "\n{\\color{fg}\n"
  15046. string
  15047. "\n}\n"
  15048. "\n\\end{document}\n"))
  15049. (let* ((err-msg (format "Please adjust `%s' part of \
  15050. `org-preview-latex-process-alist'."
  15051. processing-type))
  15052. (image-input-file
  15053. (org-compile-file
  15054. texfile latex-compiler image-input-type err-msg log-buf))
  15055. (image-output-file
  15056. (org-compile-file
  15057. image-input-file image-converter image-output-type err-msg log-buf
  15058. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  15059. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  15060. (copy-file image-output-file tofile 'replace)
  15061. (dolist (e post-clean)
  15062. (when (file-exists-p (concat texfilebase e))
  15063. (delete-file (concat texfilebase e))))
  15064. image-output-file)))
  15065. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  15066. "Fill a LaTeX header template TPL.
  15067. In the template, the following place holders will be recognized:
  15068. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  15069. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  15070. [PACKAGES] \\usepackage statements for PKG
  15071. [NO-PACKAGES] do not include PKG
  15072. [EXTRA] the string EXTRA
  15073. [NO-EXTRA] do not include EXTRA
  15074. For backward compatibility, if both the positive and the negative place
  15075. holder is missing, the positive one (without the \"NO-\") will be
  15076. assumed to be present at the end of the template.
  15077. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  15078. EXTRA is a string.
  15079. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  15080. (let (rpl (end ""))
  15081. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  15082. (setq rpl (if (or (match-end 1) (not def-pkg))
  15083. "" (org-latex-packages-to-string def-pkg snippets-p t))
  15084. tpl (replace-match rpl t t tpl))
  15085. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  15086. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  15087. (setq rpl (if (or (match-end 1) (not pkg))
  15088. "" (org-latex-packages-to-string pkg snippets-p t))
  15089. tpl (replace-match rpl t t tpl))
  15090. (when pkg (setq end
  15091. (concat end "\n"
  15092. (org-latex-packages-to-string pkg snippets-p)))))
  15093. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  15094. (setq rpl (if (or (match-end 1) (not extra))
  15095. "" (concat extra "\n"))
  15096. tpl (replace-match rpl t t tpl))
  15097. (when (and extra (string-match "\\S-" extra))
  15098. (setq end (concat end "\n" extra))))
  15099. (if (string-match "\\S-" end)
  15100. (concat tpl "\n" end)
  15101. tpl)))
  15102. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  15103. "Turn an alist of packages into a string with the \\usepackage macros."
  15104. (setq pkg (mapconcat (lambda(p)
  15105. (cond
  15106. ((stringp p) p)
  15107. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  15108. (format "%% Package %s omitted" (cadr p)))
  15109. ((equal "" (car p))
  15110. (format "\\usepackage{%s}" (cadr p)))
  15111. (t
  15112. (format "\\usepackage[%s]{%s}"
  15113. (car p) (cadr p)))))
  15114. pkg
  15115. "\n"))
  15116. (if newline (concat pkg "\n") pkg))
  15117. (defun org-dvipng-color (attr)
  15118. "Return a RGB color specification for dvipng."
  15119. (org-dvipng-color-format (face-attribute 'default attr nil)))
  15120. (defun org-dvipng-color-format (color-name)
  15121. "Convert COLOR-NAME to a RGB color value for dvipng."
  15122. (apply #'format "rgb %s %s %s"
  15123. (mapcar 'org-normalize-color
  15124. (color-values color-name))))
  15125. (defun org-latex-color (attr)
  15126. "Return a RGB color for the LaTeX color package."
  15127. (org-latex-color-format (face-attribute 'default attr nil)))
  15128. (defun org-latex-color-format (color-name)
  15129. "Convert COLOR-NAME to a RGB color value."
  15130. (apply #'format "%s,%s,%s"
  15131. (mapcar 'org-normalize-color
  15132. (color-values color-name))))
  15133. (defun org-normalize-color (value)
  15134. "Return string to be used as color value for an RGB component."
  15135. (format "%g" (/ value 65535.0)))
  15136. ;; Image display
  15137. (defvar-local org-inline-image-overlays nil)
  15138. (defun org-toggle-inline-images (&optional include-linked)
  15139. "Toggle the display of inline images.
  15140. INCLUDE-LINKED is passed to `org-display-inline-images'."
  15141. (interactive "P")
  15142. (if org-inline-image-overlays
  15143. (progn
  15144. (org-remove-inline-images)
  15145. (when (called-interactively-p 'interactive)
  15146. (message "Inline image display turned off")))
  15147. (org-display-inline-images include-linked)
  15148. (when (called-interactively-p 'interactive)
  15149. (message (if org-inline-image-overlays
  15150. (format "%d images displayed inline"
  15151. (length org-inline-image-overlays))
  15152. "No images to display inline")))))
  15153. (defun org-redisplay-inline-images ()
  15154. "Refresh the display of inline images."
  15155. (interactive)
  15156. (if (not org-inline-image-overlays)
  15157. (org-toggle-inline-images)
  15158. (org-toggle-inline-images)
  15159. (org-toggle-inline-images)))
  15160. ;; For without-x builds.
  15161. (declare-function image-refresh "image" (spec &optional frame))
  15162. (defun org-display-inline-images (&optional include-linked refresh beg end)
  15163. "Display inline images.
  15164. An inline image is a link which follows either of these
  15165. conventions:
  15166. 1. Its path is a file with an extension matching return value
  15167. from `image-file-name-regexp' and it has no contents.
  15168. 2. Its description consists in a single link of the previous
  15169. type. In this case, that link must be a well-formed plain
  15170. or angle link, i.e., it must have an explicit \"file\" type.
  15171. When optional argument INCLUDE-LINKED is non-nil, also links with
  15172. a text description part will be inlined. This can be nice for
  15173. a quick look at those images, but it does not reflect what
  15174. exported files will look like.
  15175. When optional argument REFRESH is non-nil, refresh existing
  15176. images between BEG and END. This will create new image displays
  15177. only if necessary. BEG and END default to the buffer
  15178. boundaries."
  15179. (interactive "P")
  15180. (when (display-graphic-p)
  15181. (unless refresh
  15182. (org-remove-inline-images)
  15183. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  15184. (org-with-point-at (or beg 1)
  15185. (let* ((case-fold-search t)
  15186. (file-extension-re (image-file-name-regexp))
  15187. (link-abbrevs (mapcar #'car
  15188. (append org-link-abbrev-alist-local
  15189. org-link-abbrev-alist)))
  15190. ;; Check absolute, relative file names and explicit
  15191. ;; "file:" links. Also check link abbreviations since
  15192. ;; some might expand to "file" links.
  15193. (file-types-re
  15194. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  15195. (if (not link-abbrevs) ""
  15196. (concat "\\|" (regexp-opt link-abbrevs))))))
  15197. (while (re-search-forward file-types-re end t)
  15198. (let* ((link (org-element-lineage
  15199. (save-match-data (org-element-context))
  15200. '(link) t))
  15201. (linktype (org-element-property :type link))
  15202. (inner-start (match-beginning 1))
  15203. (path
  15204. (cond
  15205. ;; No link at point; no inline image.
  15206. ((not link) nil)
  15207. ;; File link without a description. Also handle
  15208. ;; INCLUDE-LINKED here since it should have
  15209. ;; precedence over the next case. I.e., if link
  15210. ;; contains filenames in both the path and the
  15211. ;; description, prioritize the path only when
  15212. ;; INCLUDE-LINKED is non-nil.
  15213. ((or (not (org-element-property :contents-begin link))
  15214. include-linked)
  15215. (and (or (equal "file" linktype)
  15216. (equal "attachment" linktype))
  15217. (org-element-property :path link)))
  15218. ;; Link with a description. Check if description
  15219. ;; is a filename. Even if Org doesn't have syntax
  15220. ;; for those -- clickable image -- constructs, fake
  15221. ;; them, as in `org-export-insert-image-links'.
  15222. ((not inner-start) nil)
  15223. (t
  15224. (org-with-point-at inner-start
  15225. (and (looking-at
  15226. (if (char-equal ?< (char-after inner-start))
  15227. org-link-angle-re
  15228. org-link-plain-re))
  15229. ;; File name must fill the whole
  15230. ;; description.
  15231. (= (org-element-property :contents-end link)
  15232. (match-end 0))
  15233. (match-string 2)))))))
  15234. (when (and path (string-match-p file-extension-re path))
  15235. (let ((file (if (equal "attachment" linktype)
  15236. (progn
  15237. (require 'org-attach)
  15238. (org-attach-expand path))
  15239. (expand-file-name path))))
  15240. (when (file-exists-p file)
  15241. (let ((width
  15242. ;; Apply `org-image-actual-width' specifications.
  15243. (cond
  15244. ((not (image-type-available-p 'imagemagick)) nil)
  15245. ((eq org-image-actual-width t) nil)
  15246. ((listp org-image-actual-width)
  15247. (or
  15248. ;; First try to find a width among
  15249. ;; attributes associated to the paragraph
  15250. ;; containing link.
  15251. (pcase (org-element-lineage link '(paragraph))
  15252. (`nil nil)
  15253. (p
  15254. (let* ((case-fold-search t)
  15255. (end (org-element-property :post-affiliated p))
  15256. (re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"))
  15257. (when (org-with-point-at
  15258. (org-element-property :begin p)
  15259. (re-search-forward re end t))
  15260. (string-to-number (match-string 1))))))
  15261. ;; Otherwise, fall-back to provided number.
  15262. (car org-image-actual-width)))
  15263. ((numberp org-image-actual-width)
  15264. org-image-actual-width)))
  15265. (old (get-char-property-and-overlay
  15266. (org-element-property :begin link)
  15267. 'org-image-overlay)))
  15268. (if (and (car-safe old) refresh)
  15269. (image-refresh (overlay-get (cdr old) 'display))
  15270. (let ((image (create-image file
  15271. (and width 'imagemagick)
  15272. nil
  15273. :width width)))
  15274. (when image
  15275. (let ((ov (make-overlay
  15276. (org-element-property :begin link)
  15277. (progn
  15278. (goto-char
  15279. (org-element-property :end link))
  15280. (skip-chars-backward " \t")
  15281. (point)))))
  15282. (overlay-put ov 'display image)
  15283. (overlay-put ov 'face 'default)
  15284. (overlay-put ov 'org-image-overlay t)
  15285. (overlay-put
  15286. ov 'modification-hooks
  15287. (list 'org-display-inline-remove-overlay))
  15288. (push ov org-inline-image-overlays)))))))))))))))
  15289. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  15290. "Remove inline-display overlay if a corresponding region is modified."
  15291. (let ((inhibit-modification-hooks t))
  15292. (when (and ov after)
  15293. (delete ov org-inline-image-overlays)
  15294. (delete-overlay ov))))
  15295. (defun org-remove-inline-images ()
  15296. "Remove inline display of images."
  15297. (interactive)
  15298. (mapc #'delete-overlay org-inline-image-overlays)
  15299. (setq org-inline-image-overlays nil))
  15300. (defvar org-self-insert-command-undo-counter 0)
  15301. (defvar org-speed-command nil)
  15302. (defun org-self-insert-command (N)
  15303. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  15304. If the cursor is in a table looking at whitespace, the whitespace is
  15305. overwritten, and the table is not marked as requiring realignment."
  15306. (interactive "p")
  15307. (org-check-before-invisible-edit 'insert)
  15308. (cond
  15309. ((and org-use-speed-commands
  15310. (let ((kv (this-command-keys-vector)))
  15311. (setq org-speed-command
  15312. (run-hook-with-args-until-success
  15313. 'org-speed-command-hook
  15314. (make-string 1 (aref kv (1- (length kv))))))))
  15315. (cond
  15316. ((commandp org-speed-command)
  15317. (setq this-command org-speed-command)
  15318. (call-interactively org-speed-command))
  15319. ((functionp org-speed-command)
  15320. (funcall org-speed-command))
  15321. ((and org-speed-command (listp org-speed-command))
  15322. (eval org-speed-command))
  15323. (t (let (org-use-speed-commands)
  15324. (call-interactively 'org-self-insert-command)))))
  15325. ((and
  15326. (= N 1)
  15327. (not (org-region-active-p))
  15328. (org-at-table-p)
  15329. (progn
  15330. ;; Check if we blank the field, and if that triggers align.
  15331. (and (featurep 'org-table)
  15332. org-table-auto-blank-field
  15333. (memq last-command
  15334. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  15335. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  15336. ;; Got extra space, this field does not determine
  15337. ;; column width.
  15338. (let (org-table-may-need-update) (org-table-blank-field))
  15339. ;; No extra space, this field may determine column
  15340. ;; width.
  15341. (org-table-blank-field)))
  15342. t)
  15343. (looking-at "[^|\n]* |"))
  15344. ;; There is room for insertion without re-aligning the table.
  15345. (self-insert-command N)
  15346. (org-table-with-shrunk-field
  15347. (save-excursion
  15348. (skip-chars-forward "^|")
  15349. ;; Do not delete last space, which is
  15350. ;; `org-table-separator-space', but the regular space before
  15351. ;; it.
  15352. (delete-region (- (point) 2) (1- (point))))))
  15353. (t
  15354. (setq org-table-may-need-update t)
  15355. (self-insert-command N)
  15356. (org-fix-tags-on-the-fly)
  15357. (when org-self-insert-cluster-for-undo
  15358. (if (not (eq last-command 'org-self-insert-command))
  15359. (setq org-self-insert-command-undo-counter 1)
  15360. (if (>= org-self-insert-command-undo-counter 20)
  15361. (setq org-self-insert-command-undo-counter 1)
  15362. (and (> org-self-insert-command-undo-counter 0)
  15363. buffer-undo-list (listp buffer-undo-list)
  15364. (not (cadr buffer-undo-list)) ; remove nil entry
  15365. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15366. (setq org-self-insert-command-undo-counter
  15367. (1+ org-self-insert-command-undo-counter))))))))
  15368. (defun org-check-before-invisible-edit (kind)
  15369. "Check is editing if kind KIND would be dangerous with invisible text around.
  15370. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15371. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15372. (when (and org-catch-invisible-edits
  15373. (or (not (boundp 'visible-mode)) (not visible-mode))
  15374. (or (get-char-property (point) 'invisible)
  15375. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15376. ;; OK, we need to take a closer look. Do not consider
  15377. ;; invisibility obtained through text properties (e.g., link
  15378. ;; fontification), as it cannot be toggled.
  15379. (let* ((invisible-at-point
  15380. (pcase (get-char-property-and-overlay (point) 'invisible)
  15381. (`(,_ . ,(and (pred overlayp) o)) o)))
  15382. ;; Assume that point cannot land in the middle of an
  15383. ;; overlay, or between two overlays.
  15384. (invisible-before-point
  15385. (and (not invisible-at-point)
  15386. (not (bobp))
  15387. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15388. (`(,_ . ,(and (pred overlayp) o)) o))))
  15389. (border-and-ok-direction
  15390. (or
  15391. ;; Check if we are acting predictably before invisible
  15392. ;; text.
  15393. (and invisible-at-point
  15394. (memq kind '(insert delete-backward)))
  15395. ;; Check if we are acting predictably after invisible text
  15396. ;; This works not well, and I have turned it off. It seems
  15397. ;; better to always show and stop after invisible text.
  15398. ;; (and (not invisible-at-point) invisible-before-point
  15399. ;; (memq kind '(insert delete)))
  15400. )))
  15401. (when (or invisible-at-point invisible-before-point)
  15402. (when (eq org-catch-invisible-edits 'error)
  15403. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15404. (if (and org-custom-properties-overlays
  15405. (y-or-n-p "Display invisible properties in this buffer? "))
  15406. (org-toggle-custom-properties-visibility)
  15407. ;; Make the area visible
  15408. (save-excursion
  15409. (when invisible-before-point
  15410. (goto-char
  15411. (previous-single-char-property-change (point) 'invisible)))
  15412. ;; Remove whatever overlay is currently making yet-to-be
  15413. ;; edited text invisible. Also remove nested invisibility
  15414. ;; related overlays.
  15415. (delete-overlay (or invisible-at-point invisible-before-point))
  15416. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15417. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15418. (`(,_ . ,(and (pred overlayp) o))
  15419. (delete-overlay o)
  15420. t)))))
  15421. (cond
  15422. ((eq org-catch-invisible-edits 'show)
  15423. ;; That's it, we do the edit after showing
  15424. (message
  15425. "Unfolding invisible region around point before editing")
  15426. (sit-for 1))
  15427. ((and (eq org-catch-invisible-edits 'smart)
  15428. border-and-ok-direction)
  15429. (message "Unfolding invisible region around point before editing"))
  15430. (t
  15431. ;; Don't do the edit, make the user repeat it in full visibility
  15432. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15433. (defun org-fix-tags-on-the-fly ()
  15434. "Align tags in headline at point.
  15435. Unlike `org-align-tags', this function does nothing if point is
  15436. either not currently on a tagged headline or on a tag."
  15437. (when (and (org-match-line org-tag-line-re)
  15438. (< (point) (match-beginning 1)))
  15439. (org-align-tags)))
  15440. (defun org-delete-backward-char (N)
  15441. "Like `delete-backward-char', insert whitespace at field end in tables.
  15442. When deleting backwards, in tables this function will insert whitespace in
  15443. front of the next \"|\" separator, to keep the table aligned. The table will
  15444. still be marked for re-alignment if the field did fill the entire column,
  15445. because, in this case the deletion might narrow the column."
  15446. (interactive "p")
  15447. (save-match-data
  15448. (org-check-before-invisible-edit 'delete-backward)
  15449. (if (and (= N 1)
  15450. (not overwrite-mode)
  15451. (not (org-region-active-p))
  15452. (not (eq (char-before) ?|))
  15453. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15454. (looking-at-p ".*?|")
  15455. (org-at-table-p))
  15456. (progn (forward-char -1) (org-delete-char 1))
  15457. (backward-delete-char N)
  15458. (org-fix-tags-on-the-fly))))
  15459. (defun org-delete-char (N)
  15460. "Like `delete-char', but insert whitespace at field end in tables.
  15461. When deleting characters, in tables this function will insert whitespace in
  15462. front of the next \"|\" separator, to keep the table aligned. The table will
  15463. still be marked for re-alignment if the field did fill the entire column,
  15464. because, in this case the deletion might narrow the column."
  15465. (interactive "p")
  15466. (save-match-data
  15467. (org-check-before-invisible-edit 'delete)
  15468. (cond
  15469. ((or (/= N 1)
  15470. (eq (char-after) ?|)
  15471. (save-excursion (skip-chars-backward " \t") (bolp))
  15472. (not (org-at-table-p)))
  15473. (delete-char N)
  15474. (org-fix-tags-on-the-fly))
  15475. ((looking-at ".\\(.*?\\)|")
  15476. (let* ((update? org-table-may-need-update)
  15477. (noalign (looking-at-p ".*? |")))
  15478. (delete-char 1)
  15479. (org-table-with-shrunk-field
  15480. (save-excursion
  15481. ;; Last space is `org-table-separator-space', so insert
  15482. ;; a regular one before it instead.
  15483. (goto-char (- (match-end 0) 2))
  15484. (insert " ")))
  15485. ;; If there were two spaces at the end, this field does not
  15486. ;; determine the width of the column.
  15487. (when noalign (setq org-table-may-need-update update?))))
  15488. (t
  15489. (delete-char N)))))
  15490. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15491. (put 'org-self-insert-command 'delete-selection
  15492. (lambda ()
  15493. (not (run-hook-with-args-until-success
  15494. 'self-insert-uses-region-functions))))
  15495. (put 'orgtbl-self-insert-command 'delete-selection
  15496. (lambda ()
  15497. (not (run-hook-with-args-until-success
  15498. 'self-insert-uses-region-functions))))
  15499. (put 'org-delete-char 'delete-selection 'supersede)
  15500. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15501. (put 'org-yank 'delete-selection 'yank)
  15502. ;; Make `flyspell-mode' delay after some commands
  15503. (put 'org-self-insert-command 'flyspell-delayed t)
  15504. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15505. (put 'org-delete-char 'flyspell-delayed t)
  15506. (put 'org-delete-backward-char 'flyspell-delayed t)
  15507. ;; Make pabbrev-mode expand after Org mode commands
  15508. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15509. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15510. (defun org-transpose-words ()
  15511. "Transpose words for Org.
  15512. This uses the `org-mode-transpose-word-syntax-table' syntax
  15513. table, which interprets characters in `org-emphasis-alist' as
  15514. word constituents."
  15515. (interactive)
  15516. (with-syntax-table org-mode-transpose-word-syntax-table
  15517. (call-interactively 'transpose-words)))
  15518. (defvar org-ctrl-c-ctrl-c-hook nil
  15519. "Hook for functions attaching themselves to `C-c C-c'.
  15520. This can be used to add additional functionality to the C-c C-c
  15521. key which executes context-dependent commands. This hook is run
  15522. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15523. run after the last test.
  15524. Each function will be called with no arguments. The function
  15525. must check if the context is appropriate for it to act. If yes,
  15526. it should do its thing and then return a non-nil value. If the
  15527. context is wrong, just do nothing and return nil.")
  15528. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15529. "Hook for functions attaching themselves to `C-c C-c'.
  15530. This can be used to add additional functionality to the C-c C-c
  15531. key which executes context-dependent commands. This hook is run
  15532. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15533. before the first test.
  15534. Each function will be called with no arguments. The function
  15535. must check if the context is appropriate for it to act. If yes,
  15536. it should do its thing and then return a non-nil value. If the
  15537. context is wrong, just do nothing and return nil.")
  15538. (defvar org-tab-first-hook nil
  15539. "Hook for functions to attach themselves to TAB.
  15540. See `org-ctrl-c-ctrl-c-hook' for more information.
  15541. This hook runs as the first action when TAB is pressed, even before
  15542. `org-cycle' messes around with the `outline-regexp' to cater for
  15543. inline tasks and plain list item folding.
  15544. If any function in this hook returns t, any other actions that
  15545. would have been caused by TAB (such as table field motion or visibility
  15546. cycling) will not occur.")
  15547. (defvar org-tab-after-check-for-table-hook nil
  15548. "Hook for functions to attach themselves to TAB.
  15549. See `org-ctrl-c-ctrl-c-hook' for more information.
  15550. This hook runs after it has been established that the cursor is not in a
  15551. table, but before checking if the cursor is in a headline or if global cycling
  15552. should be done.
  15553. If any function in this hook returns t, not other actions like visibility
  15554. cycling will be done.")
  15555. (defvar org-tab-after-check-for-cycling-hook nil
  15556. "Hook for functions to attach themselves to TAB.
  15557. See `org-ctrl-c-ctrl-c-hook' for more information.
  15558. This hook runs after it has been established that not table field motion and
  15559. not visibility should be done because of current context. This is probably
  15560. the place where a package like yasnippets can hook in.")
  15561. (defvar org-tab-before-tab-emulation-hook nil
  15562. "Hook for functions to attach themselves to TAB.
  15563. See `org-ctrl-c-ctrl-c-hook' for more information.
  15564. This hook runs after every other options for TAB have been exhausted, but
  15565. before indentation and \t insertion takes place.")
  15566. (defvar org-metaleft-hook nil
  15567. "Hook for functions attaching themselves to `M-left'.
  15568. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15569. (defvar org-metaright-hook nil
  15570. "Hook for functions attaching themselves to `M-right'.
  15571. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15572. (defvar org-metaup-hook nil
  15573. "Hook for functions attaching themselves to `M-up'.
  15574. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15575. (defvar org-metadown-hook nil
  15576. "Hook for functions attaching themselves to `M-down'.
  15577. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15578. (defvar org-shiftmetaleft-hook nil
  15579. "Hook for functions attaching themselves to `M-S-left'.
  15580. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15581. (defvar org-shiftmetaright-hook nil
  15582. "Hook for functions attaching themselves to `M-S-right'.
  15583. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15584. (defvar org-shiftmetaup-hook nil
  15585. "Hook for functions attaching themselves to `M-S-up'.
  15586. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15587. (defvar org-shiftmetadown-hook nil
  15588. "Hook for functions attaching themselves to `M-S-down'.
  15589. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15590. (defvar org-metareturn-hook nil
  15591. "Hook for functions attaching themselves to `M-RET'.
  15592. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15593. (defvar org-shiftup-hook nil
  15594. "Hook for functions attaching themselves to `S-up'.
  15595. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15596. (defvar org-shiftup-final-hook nil
  15597. "Hook for functions attaching themselves to `S-up'.
  15598. This one runs after all other options except shift-select have been excluded.
  15599. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15600. (defvar org-shiftdown-hook nil
  15601. "Hook for functions attaching themselves to `S-down'.
  15602. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15603. (defvar org-shiftdown-final-hook nil
  15604. "Hook for functions attaching themselves to `S-down'.
  15605. This one runs after all other options except shift-select have been excluded.
  15606. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15607. (defvar org-shiftleft-hook nil
  15608. "Hook for functions attaching themselves to `S-left'.
  15609. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15610. (defvar org-shiftleft-final-hook nil
  15611. "Hook for functions attaching themselves to `S-left'.
  15612. This one runs after all other options except shift-select have been excluded.
  15613. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15614. (defvar org-shiftright-hook nil
  15615. "Hook for functions attaching themselves to `S-right'.
  15616. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15617. (defvar org-shiftright-final-hook nil
  15618. "Hook for functions attaching themselves to `S-right'.
  15619. This one runs after all other options except shift-select have been excluded.
  15620. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15621. (defun org-modifier-cursor-error ()
  15622. "Throw an error, a modified cursor command was applied in wrong context."
  15623. (user-error "This command is active in special context like tables, headlines or items"))
  15624. (defun org-shiftselect-error ()
  15625. "Throw an error because Shift-Cursor command was applied in wrong context."
  15626. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15627. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15628. (user-error "This command works only in special context like headlines or timestamps")))
  15629. (defun org-call-for-shift-select (cmd)
  15630. (let ((this-command-keys-shift-translated t))
  15631. (call-interactively cmd)))
  15632. (defun org-shifttab (&optional arg)
  15633. "Global visibility cycling or move to previous table field.
  15634. Call `org-table-previous-field' within a table.
  15635. When ARG is nil, cycle globally through visibility states.
  15636. When ARG is a numeric prefix, show contents of this level."
  15637. (interactive "P")
  15638. (cond
  15639. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15640. ((integerp arg)
  15641. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15642. (message "Content view to level: %d" arg)
  15643. (org-content (prefix-numeric-value arg2))
  15644. (org-cycle-show-empty-lines t)
  15645. (setq org-cycle-global-status 'overview)))
  15646. (t (call-interactively 'org-global-cycle))))
  15647. (defun org-shiftmetaleft ()
  15648. "Promote subtree or delete table column.
  15649. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15650. `org-table-delete-column', depending on context. See the
  15651. individual commands for more information."
  15652. (interactive)
  15653. (cond
  15654. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15655. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15656. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15657. ((if (not (org-region-active-p)) (org-at-item-p)
  15658. (save-excursion (goto-char (region-beginning))
  15659. (org-at-item-p)))
  15660. (call-interactively 'org-outdent-item-tree))
  15661. (t (org-modifier-cursor-error))))
  15662. (defun org-shiftmetaright ()
  15663. "Demote subtree or insert table column.
  15664. Calls `org-demote-subtree', `org-indent-item-tree', or
  15665. `org-table-insert-column', depending on context. See the
  15666. individual commands for more information."
  15667. (interactive)
  15668. (cond
  15669. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15670. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15671. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15672. ((if (not (org-region-active-p)) (org-at-item-p)
  15673. (save-excursion (goto-char (region-beginning))
  15674. (org-at-item-p)))
  15675. (call-interactively 'org-indent-item-tree))
  15676. (t (org-modifier-cursor-error))))
  15677. (defun org-shiftmetaup (&optional _arg)
  15678. "Drag the line at point up.
  15679. In a table, kill the current row.
  15680. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15681. but also adjust the previous clocked item in the clock history.
  15682. Everywhere else, drag the line at point up."
  15683. (interactive "P")
  15684. (cond
  15685. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15686. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15687. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15688. (call-interactively 'org-timestamp-up)))
  15689. (t (call-interactively 'org-drag-line-backward))))
  15690. (defun org-shiftmetadown (&optional _arg)
  15691. "Drag the line at point down.
  15692. In a table, insert an empty row at the current line.
  15693. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15694. but also adjust the previous clocked item in the clock history.
  15695. Everywhere else, drag the line at point down."
  15696. (interactive "P")
  15697. (cond
  15698. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15699. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15700. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15701. (call-interactively 'org-timestamp-down)))
  15702. (t (call-interactively 'org-drag-line-forward))))
  15703. (defsubst org-hidden-tree-error ()
  15704. (user-error
  15705. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15706. (defun org-metaleft (&optional _arg)
  15707. "Promote heading, list item at point or move table column left.
  15708. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15709. depending on context. With no specific context, calls the Emacs
  15710. default `backward-word'. See the individual commands for more
  15711. information.
  15712. This function runs the hook `org-metaleft-hook' as a first step,
  15713. and returns at first non-nil value."
  15714. (interactive "P")
  15715. (cond
  15716. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15717. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15718. ((org-with-limited-levels
  15719. (or (org-at-heading-p)
  15720. (and (org-region-active-p)
  15721. (save-excursion
  15722. (goto-char (region-beginning))
  15723. (org-at-heading-p)))))
  15724. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15725. (call-interactively 'org-do-promote))
  15726. ;; At an inline task.
  15727. ((org-at-heading-p)
  15728. (call-interactively 'org-inlinetask-promote))
  15729. ((or (org-at-item-p)
  15730. (and (org-region-active-p)
  15731. (save-excursion
  15732. (goto-char (region-beginning))
  15733. (org-at-item-p))))
  15734. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15735. (call-interactively 'org-outdent-item))
  15736. (t (call-interactively 'backward-word))))
  15737. (defun org-metaright (&optional _arg)
  15738. "Demote heading, list item at point or move table column right.
  15739. In front of a drawer or a block keyword, indent it correctly.
  15740. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15741. `org-indent-drawer' or `org-indent-block' depending on context.
  15742. With no specific context, calls the Emacs default `forward-word'.
  15743. See the individual commands for more information.
  15744. This function runs the hook `org-metaright-hook' as a first step,
  15745. and returns at first non-nil value."
  15746. (interactive "P")
  15747. (cond
  15748. ((run-hook-with-args-until-success 'org-metaright-hook))
  15749. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15750. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15751. ((org-at-block-p) (call-interactively 'org-indent-block))
  15752. ((org-with-limited-levels
  15753. (or (org-at-heading-p)
  15754. (and (org-region-active-p)
  15755. (save-excursion
  15756. (goto-char (region-beginning))
  15757. (org-at-heading-p)))))
  15758. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15759. (call-interactively 'org-do-demote))
  15760. ;; At an inline task.
  15761. ((org-at-heading-p)
  15762. (call-interactively 'org-inlinetask-demote))
  15763. ((or (org-at-item-p)
  15764. (and (org-region-active-p)
  15765. (save-excursion
  15766. (goto-char (region-beginning))
  15767. (org-at-item-p))))
  15768. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15769. (call-interactively 'org-indent-item))
  15770. (t (call-interactively 'forward-word))))
  15771. (defun org-check-for-hidden (what)
  15772. "Check if there are hidden headlines/items in the current visual line.
  15773. WHAT can be either `headlines' or `items'. If the current line is
  15774. an outline or item heading and it has a folded subtree below it,
  15775. this function returns t, nil otherwise."
  15776. (let ((re (cond
  15777. ((eq what 'headlines) org-outline-regexp-bol)
  15778. ((eq what 'items) (org-item-beginning-re))
  15779. (t (error "This should not happen"))))
  15780. beg end)
  15781. (save-excursion
  15782. (catch 'exit
  15783. (unless (org-region-active-p)
  15784. (setq beg (point-at-bol))
  15785. (beginning-of-line 2)
  15786. (while (and (not (eobp)) ;; this is like `next-line'
  15787. (get-char-property (1- (point)) 'invisible))
  15788. (beginning-of-line 2))
  15789. (setq end (point))
  15790. (goto-char beg)
  15791. (goto-char (point-at-eol))
  15792. (setq end (max end (point)))
  15793. (while (re-search-forward re end t)
  15794. (when (get-char-property (match-beginning 0) 'invisible)
  15795. (throw 'exit t))))
  15796. nil))))
  15797. (defun org-metaup (&optional _arg)
  15798. "Move subtree up or move table row up.
  15799. Calls `org-move-subtree-up' or `org-table-move-row' or
  15800. `org-move-item-up', depending on context. See the individual commands
  15801. for more information."
  15802. (interactive "P")
  15803. (cond
  15804. ((run-hook-with-args-until-success 'org-metaup-hook))
  15805. ((org-region-active-p)
  15806. (let* ((a (save-excursion
  15807. (goto-char (min (region-beginning) (region-end)))
  15808. (line-beginning-position)))
  15809. (b (save-excursion
  15810. (goto-char (max (region-beginning) (region-end)))
  15811. (if (bolp) (1- (point)) (line-end-position))))
  15812. (c (save-excursion
  15813. (goto-char a)
  15814. (move-beginning-of-line 0)
  15815. (point)))
  15816. (d (save-excursion
  15817. (goto-char a)
  15818. (move-end-of-line 0)
  15819. (point))))
  15820. (transpose-regions a b c d)
  15821. (goto-char c)))
  15822. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15823. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15824. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15825. (t (org-drag-element-backward))))
  15826. (defun org-metadown (&optional _arg)
  15827. "Move subtree down or move table row down.
  15828. Calls `org-move-subtree-down' or `org-table-move-row' or
  15829. `org-move-item-down', depending on context. See the individual
  15830. commands for more information."
  15831. (interactive "P")
  15832. (cond
  15833. ((run-hook-with-args-until-success 'org-metadown-hook))
  15834. ((org-region-active-p)
  15835. (let* ((a (save-excursion
  15836. (goto-char (min (region-beginning) (region-end)))
  15837. (line-beginning-position)))
  15838. (b (save-excursion
  15839. (goto-char (max (region-beginning) (region-end)))
  15840. (if (bolp) (1- (point)) (line-end-position))))
  15841. (c (save-excursion
  15842. (goto-char b)
  15843. (move-beginning-of-line (if (bolp) 1 2))
  15844. (point)))
  15845. (d (save-excursion
  15846. (goto-char b)
  15847. (move-end-of-line (if (bolp) 1 2))
  15848. (point))))
  15849. (transpose-regions a b c d)
  15850. (goto-char d)))
  15851. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15852. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15853. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15854. (t (org-drag-element-forward))))
  15855. (defun org-shiftup (&optional arg)
  15856. "Act on current element according to context.
  15857. Call `org-timestamp-up' or `org-priority-up', or
  15858. `org-previous-item', or `org-table-move-cell-up'. See the
  15859. individual commands for more information."
  15860. (interactive "P")
  15861. (cond
  15862. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15863. ((and org-support-shift-select (org-region-active-p))
  15864. (org-call-for-shift-select 'previous-line))
  15865. ((org-at-timestamp-p 'lax)
  15866. (call-interactively (if org-edit-timestamp-down-means-later
  15867. 'org-timestamp-down 'org-timestamp-up)))
  15868. ((and (not (eq org-support-shift-select 'always))
  15869. org-enable-priority-commands
  15870. (org-at-heading-p))
  15871. (call-interactively 'org-priority-up))
  15872. ((and (not org-support-shift-select) (org-at-item-p))
  15873. (call-interactively 'org-previous-item))
  15874. ((org-clocktable-try-shift 'up arg))
  15875. ((org-at-table-p) (org-table-move-cell-up))
  15876. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15877. (org-support-shift-select
  15878. (org-call-for-shift-select 'previous-line))
  15879. (t (org-shiftselect-error))))
  15880. (defun org-shiftdown (&optional arg)
  15881. "Act on current element according to context.
  15882. Call `org-timestamp-down' or `org-priority-down', or
  15883. `org-next-item', or `org-table-move-cell-down'. See the
  15884. individual commands for more information."
  15885. (interactive "P")
  15886. (cond
  15887. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15888. ((and org-support-shift-select (org-region-active-p))
  15889. (org-call-for-shift-select 'next-line))
  15890. ((org-at-timestamp-p 'lax)
  15891. (call-interactively (if org-edit-timestamp-down-means-later
  15892. 'org-timestamp-up 'org-timestamp-down)))
  15893. ((and (not (eq org-support-shift-select 'always))
  15894. org-enable-priority-commands
  15895. (org-at-heading-p))
  15896. (call-interactively 'org-priority-down))
  15897. ((and (not org-support-shift-select) (org-at-item-p))
  15898. (call-interactively 'org-next-item))
  15899. ((org-clocktable-try-shift 'down arg))
  15900. ((org-at-table-p) (org-table-move-cell-down))
  15901. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15902. (org-support-shift-select
  15903. (org-call-for-shift-select 'next-line))
  15904. (t (org-shiftselect-error))))
  15905. (defun org-shiftright (&optional arg)
  15906. "Act on the current element according to context.
  15907. This does one of the following:
  15908. - switch a timestamp at point one day into the future
  15909. - on a headline, switch to the next TODO keyword.
  15910. - on an item, switch entire list to the next bullet type
  15911. - on a property line, switch to the next allowed value
  15912. - on a clocktable definition line, move time block into the future
  15913. - in a table, move a single cell right"
  15914. (interactive "P")
  15915. (cond
  15916. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15917. ((and org-support-shift-select (org-region-active-p))
  15918. (org-call-for-shift-select 'forward-char))
  15919. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15920. ((and (not (eq org-support-shift-select 'always))
  15921. (org-at-heading-p))
  15922. (let ((org-inhibit-logging
  15923. (not org-treat-S-cursor-todo-selection-as-state-change))
  15924. (org-inhibit-blocking
  15925. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15926. (org-call-with-arg 'org-todo 'right)))
  15927. ((or (and org-support-shift-select
  15928. (not (eq org-support-shift-select 'always))
  15929. (org-at-item-bullet-p))
  15930. (and (not org-support-shift-select) (org-at-item-p)))
  15931. (org-call-with-arg 'org-cycle-list-bullet nil))
  15932. ((and (not (eq org-support-shift-select 'always))
  15933. (org-at-property-p))
  15934. (call-interactively 'org-property-next-allowed-value))
  15935. ((org-clocktable-try-shift 'right arg))
  15936. ((org-at-table-p) (org-table-move-cell-right))
  15937. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15938. (org-support-shift-select
  15939. (org-call-for-shift-select 'forward-char))
  15940. (t (org-shiftselect-error))))
  15941. (defun org-shiftleft (&optional arg)
  15942. "Act on current element according to context.
  15943. This does one of the following:
  15944. - switch a timestamp at point one day into the past
  15945. - on a headline, switch to the previous TODO keyword.
  15946. - on an item, switch entire list to the previous bullet type
  15947. - on a property line, switch to the previous allowed value
  15948. - on a clocktable definition line, move time block into the past
  15949. - in a table, move a single cell left"
  15950. (interactive "P")
  15951. (cond
  15952. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15953. ((and org-support-shift-select (org-region-active-p))
  15954. (org-call-for-shift-select 'backward-char))
  15955. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15956. ((and (not (eq org-support-shift-select 'always))
  15957. (org-at-heading-p))
  15958. (let ((org-inhibit-logging
  15959. (not org-treat-S-cursor-todo-selection-as-state-change))
  15960. (org-inhibit-blocking
  15961. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15962. (org-call-with-arg 'org-todo 'left)))
  15963. ((or (and org-support-shift-select
  15964. (not (eq org-support-shift-select 'always))
  15965. (org-at-item-bullet-p))
  15966. (and (not org-support-shift-select) (org-at-item-p)))
  15967. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15968. ((and (not (eq org-support-shift-select 'always))
  15969. (org-at-property-p))
  15970. (call-interactively 'org-property-previous-allowed-value))
  15971. ((org-clocktable-try-shift 'left arg))
  15972. ((org-at-table-p) (org-table-move-cell-left))
  15973. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15974. (org-support-shift-select
  15975. (org-call-for-shift-select 'backward-char))
  15976. (t (org-shiftselect-error))))
  15977. (defun org-shiftcontrolright ()
  15978. "Switch to next TODO set."
  15979. (interactive)
  15980. (cond
  15981. ((and org-support-shift-select (org-region-active-p))
  15982. (org-call-for-shift-select 'forward-word))
  15983. ((and (not (eq org-support-shift-select 'always))
  15984. (org-at-heading-p))
  15985. (org-call-with-arg 'org-todo 'nextset))
  15986. (org-support-shift-select
  15987. (org-call-for-shift-select 'forward-word))
  15988. (t (org-shiftselect-error))))
  15989. (defun org-shiftcontrolleft ()
  15990. "Switch to previous TODO set."
  15991. (interactive)
  15992. (cond
  15993. ((and org-support-shift-select (org-region-active-p))
  15994. (org-call-for-shift-select 'backward-word))
  15995. ((and (not (eq org-support-shift-select 'always))
  15996. (org-at-heading-p))
  15997. (org-call-with-arg 'org-todo 'previousset))
  15998. (org-support-shift-select
  15999. (org-call-for-shift-select 'backward-word))
  16000. (t (org-shiftselect-error))))
  16001. (defun org-shiftcontrolup (&optional n)
  16002. "Change timestamps synchronously up in CLOCK log lines.
  16003. Optional argument N tells to change by that many units."
  16004. (interactive "P")
  16005. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  16006. (let (org-support-shift-select)
  16007. (org-clock-timestamps-up n))
  16008. (user-error "Not at a clock log")))
  16009. (defun org-shiftcontroldown (&optional n)
  16010. "Change timestamps synchronously down in CLOCK log lines.
  16011. Optional argument N tells to change by that many units."
  16012. (interactive "P")
  16013. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  16014. (let (org-support-shift-select)
  16015. (org-clock-timestamps-down n))
  16016. (user-error "Not at a clock log")))
  16017. (defun org-increase-number-at-point (&optional inc)
  16018. "Increment the number at point.
  16019. With an optional prefix numeric argument INC, increment using
  16020. this numeric value."
  16021. (interactive "p")
  16022. (if (not (number-at-point))
  16023. (user-error "Not on a number")
  16024. (unless inc (setq inc 1))
  16025. (let ((pos (point))
  16026. (beg (skip-chars-backward "-+^/*0-9eE."))
  16027. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  16028. (setq nap (buffer-substring-no-properties
  16029. (+ pos beg) (+ pos beg end)))
  16030. (delete-region (+ pos beg) (+ pos beg end))
  16031. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  16032. (when (org-at-table-p)
  16033. (org-table-align)
  16034. (org-table-end-of-field 1))))
  16035. (defun org-decrease-number-at-point (&optional inc)
  16036. "Decrement the number at point.
  16037. With an optional prefix numeric argument INC, decrement using
  16038. this numeric value."
  16039. (interactive "p")
  16040. (org-increase-number-at-point (- (or inc 1))))
  16041. (defun org-ctrl-c-ret ()
  16042. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  16043. (interactive)
  16044. (cond
  16045. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  16046. (t (call-interactively 'org-insert-heading))))
  16047. (defun org-find-visible ()
  16048. (let ((s (point)))
  16049. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  16050. (get-char-property s 'invisible)))
  16051. s))
  16052. (defun org-find-invisible ()
  16053. (let ((s (point)))
  16054. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  16055. (not (get-char-property s 'invisible))))
  16056. s))
  16057. (defun org-copy-visible (beg end)
  16058. "Copy the visible parts of the region."
  16059. (interactive "r")
  16060. (let ((result ""))
  16061. (while (/= beg end)
  16062. (when (get-char-property beg 'invisible)
  16063. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  16064. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  16065. (setq result (concat result (buffer-substring beg next)))
  16066. (setq beg next)))
  16067. (setq deactivate-mark t)
  16068. (kill-new result)
  16069. (message "Visible strings have been copied to the kill ring.")))
  16070. (defun org-copy-special ()
  16071. "Copy region in table or copy current subtree.
  16072. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  16073. context. See the individual commands for more information."
  16074. (interactive)
  16075. (call-interactively
  16076. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  16077. (defun org-cut-special ()
  16078. "Cut region in table or cut current subtree.
  16079. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  16080. context. See the individual commands for more information."
  16081. (interactive)
  16082. (call-interactively
  16083. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  16084. (defun org-paste-special (arg)
  16085. "Paste rectangular region into table, or past subtree relative to level.
  16086. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  16087. See the individual commands for more information."
  16088. (interactive "P")
  16089. (if (org-at-table-p)
  16090. (org-table-paste-rectangle)
  16091. (org-paste-subtree arg)))
  16092. (defun org-edit-special (&optional arg)
  16093. "Call a special editor for the element at point.
  16094. When at a table, call the formula editor with `org-table-edit-formulas'.
  16095. When in a source code block, call `org-edit-src-code'.
  16096. When in a fixed-width region, call `org-edit-fixed-width-region'.
  16097. When in an export block, call `org-edit-export-block'.
  16098. When in a LaTeX environment, call `org-edit-latex-environment'.
  16099. When at an #+INCLUDE keyword, visit the included file.
  16100. When at a footnote reference, call `org-edit-footnote-reference'.
  16101. When at a planning line call, `org-deadline' and/or `org-schedule'.
  16102. When at an active timestamp, call `org-time-stamp'.
  16103. When at an inactive timestamp, call `org-time-stamp-inactive'.
  16104. On a link, call `ffap' to visit the link at point.
  16105. Otherwise, return a user error."
  16106. (interactive "P")
  16107. (let ((element (org-element-at-point)))
  16108. (barf-if-buffer-read-only)
  16109. (pcase (org-element-type element)
  16110. (`src-block
  16111. (if (not arg) (org-edit-src-code)
  16112. (let* ((info (org-babel-get-src-block-info))
  16113. (lang (nth 0 info))
  16114. (params (nth 2 info))
  16115. (session (cdr (assq :session params))))
  16116. (if (not session) (org-edit-src-code)
  16117. ;; At a source block with a session and function called
  16118. ;; with an ARG: switch to the buffer related to the
  16119. ;; inferior process.
  16120. (switch-to-buffer
  16121. (funcall (intern (concat "org-babel-prep-session:" lang))
  16122. session params))))))
  16123. (`keyword
  16124. (unless (member (org-element-property :key element)
  16125. '("INCLUDE" "SETUPFILE"))
  16126. (user-error "No special environment to edit here"))
  16127. (let ((value (org-element-property :value element)))
  16128. (unless (org-string-nw-p value) (user-error "No file to edit"))
  16129. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  16130. (or (match-string 1 value)
  16131. (match-string 0 value)))))
  16132. (when (org-file-url-p file)
  16133. (user-error "Files located with a URL cannot be edited"))
  16134. (org-link-open-from-string
  16135. (format "[[%s]]" (expand-file-name file))))))
  16136. (`table
  16137. (if (eq (org-element-property :type element) 'table.el)
  16138. (org-edit-table.el)
  16139. (call-interactively 'org-table-edit-formulas)))
  16140. ;; Only Org tables contain `table-row' type elements.
  16141. (`table-row (call-interactively 'org-table-edit-formulas))
  16142. (`example-block (org-edit-src-code))
  16143. (`export-block (org-edit-export-block))
  16144. (`fixed-width (org-edit-fixed-width-region))
  16145. (`latex-environment (org-edit-latex-environment))
  16146. (`planning
  16147. (let ((proplist (cadr element)))
  16148. (mapc #'call-interactively
  16149. (remq nil
  16150. (list
  16151. (when (plist-get proplist :deadline) #'org-deadline)
  16152. (when (plist-get proplist :scheduled) #'org-schedule))))))
  16153. (_
  16154. ;; No notable element at point. Though, we may be at a link or
  16155. ;; a footnote reference, which are objects. Thus, scan deeper.
  16156. (let ((context (org-element-context element)))
  16157. (pcase (org-element-type context)
  16158. (`footnote-reference (org-edit-footnote-reference))
  16159. (`inline-src-block (org-edit-inline-src-code))
  16160. (`timestamp (if (eq 'inactive (org-element-property :type context))
  16161. (call-interactively #'org-time-stamp-inactive)
  16162. (call-interactively #'org-time-stamp)))
  16163. (`link (call-interactively #'ffap))
  16164. (_ (user-error "No special environment to edit here"))))))))
  16165. (defun org-ctrl-c-ctrl-c (&optional arg)
  16166. "Set tags in headline, or update according to changed information at point.
  16167. This command does many different things, depending on context:
  16168. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  16169. this is what we do.
  16170. - If the cursor is on a statistics cookie, update it.
  16171. - If the cursor is in a headline, prompt for tags and insert them
  16172. into the current line, aligned to `org-tags-column'. When called
  16173. with prefix arg, realign all tags in the current buffer.
  16174. - If the cursor is in one of the special #+KEYWORD lines, this
  16175. triggers scanning the buffer for these lines and updating the
  16176. information.
  16177. - If the cursor is inside a table, realign the table. This command
  16178. works even if the automatic table editor has been turned off.
  16179. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  16180. the entire table.
  16181. - If the cursor is at a footnote reference or definition, jump to
  16182. the corresponding definition or references, respectively.
  16183. - If the cursor is a the beginning of a dynamic block, update it.
  16184. - If the current buffer is a capture buffer, close note and file it.
  16185. - If the cursor is on a <<<target>>>, update radio targets and
  16186. corresponding links in this buffer.
  16187. - If the cursor is on a numbered item in a plain list, renumber the
  16188. ordered list.
  16189. - If the cursor is on a checkbox, toggle it.
  16190. - If the cursor is on a code block, evaluate it. The variable
  16191. `org-confirm-babel-evaluate' can be used to control prompting
  16192. before code block evaluation, by default every code block
  16193. evaluation requires confirmation. Code block evaluation can be
  16194. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  16195. (interactive "P")
  16196. (cond
  16197. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  16198. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  16199. (org-remove-occur-highlights)
  16200. (message "Temporary highlights/overlays removed from current buffer"))
  16201. ((and (local-variable-p 'org-finish-function)
  16202. (fboundp org-finish-function))
  16203. (funcall org-finish-function))
  16204. ((org-babel-hash-at-point))
  16205. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  16206. (t
  16207. (let* ((context
  16208. (org-element-lineage
  16209. (org-element-context)
  16210. ;; Limit to supported contexts.
  16211. '(babel-call clock dynamic-block footnote-definition
  16212. footnote-reference inline-babel-call inline-src-block
  16213. inlinetask item keyword node-property paragraph
  16214. plain-list planning property-drawer radio-target
  16215. src-block statistics-cookie table table-cell table-row
  16216. timestamp)
  16217. t))
  16218. (type (org-element-type context)))
  16219. ;; For convenience: at the first line of a paragraph on the same
  16220. ;; line as an item, apply function on that item instead.
  16221. (when (eq type 'paragraph)
  16222. (let ((parent (org-element-property :parent context)))
  16223. (when (and (eq (org-element-type parent) 'item)
  16224. (= (line-beginning-position)
  16225. (org-element-property :begin parent)))
  16226. (setq context parent)
  16227. (setq type 'item))))
  16228. ;; Act according to type of element or object at point.
  16229. ;;
  16230. ;; Do nothing on a blank line, except if it is contained in
  16231. ;; a source block. Hence, we first check if point is in such
  16232. ;; a block and then if it is at a blank line.
  16233. (pcase type
  16234. ((or `inline-src-block `src-block)
  16235. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  16236. (org-babel-eval-wipe-error-buffer)
  16237. (org-babel-execute-src-block
  16238. current-prefix-arg (org-babel-get-src-block-info nil context))))
  16239. ((guard (org-match-line "[ \t]*$"))
  16240. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  16241. (user-error
  16242. (substitute-command-keys
  16243. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  16244. ((or `babel-call `inline-babel-call)
  16245. (let ((info (org-babel-lob-get-info context)))
  16246. (when info (org-babel-execute-src-block nil info))))
  16247. (`clock (org-clock-update-time-maybe))
  16248. (`dynamic-block
  16249. (save-excursion
  16250. (goto-char (org-element-property :post-affiliated context))
  16251. (org-update-dblock)))
  16252. (`footnote-definition
  16253. (goto-char (org-element-property :post-affiliated context))
  16254. (call-interactively 'org-footnote-action))
  16255. (`footnote-reference (call-interactively #'org-footnote-action))
  16256. ((or `headline `inlinetask)
  16257. (save-excursion (goto-char (org-element-property :begin context))
  16258. (call-interactively #'org-set-tags-command)))
  16259. (`item
  16260. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  16261. ;; unconditionally, whereas `C-u' will toggle its presence.
  16262. ;; Without a universal argument, if the item has a checkbox,
  16263. ;; toggle it. Otherwise repair the list.
  16264. (let* ((box (org-element-property :checkbox context))
  16265. (struct (org-element-property :structure context))
  16266. (old-struct (copy-tree struct))
  16267. (parents (org-list-parents-alist struct))
  16268. (prevs (org-list-prevs-alist struct))
  16269. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  16270. (org-list-set-checkbox
  16271. (org-element-property :begin context) struct
  16272. (cond ((equal arg '(16)) "[-]")
  16273. ((and (not box) (equal arg '(4))) "[ ]")
  16274. ((or (not box) (equal arg '(4))) nil)
  16275. ((eq box 'on) "[ ]")
  16276. (t "[X]")))
  16277. ;; Mimic `org-list-write-struct' but with grabbing a return
  16278. ;; value from `org-list-struct-fix-box'.
  16279. (org-list-struct-fix-ind struct parents 2)
  16280. (org-list-struct-fix-item-end struct)
  16281. (org-list-struct-fix-bul struct prevs)
  16282. (org-list-struct-fix-ind struct parents)
  16283. (let ((block-item
  16284. (org-list-struct-fix-box struct parents prevs orderedp)))
  16285. (if (and box (equal struct old-struct))
  16286. (if (equal arg '(16))
  16287. (message "Checkboxes already reset")
  16288. (user-error "Cannot toggle this checkbox: %s"
  16289. (if (eq box 'on)
  16290. "all subitems checked"
  16291. "unchecked subitems")))
  16292. (org-list-struct-apply-struct struct old-struct)
  16293. (org-update-checkbox-count-maybe))
  16294. (when block-item
  16295. (message "Checkboxes were removed due to empty box at line %d"
  16296. (org-current-line block-item))))))
  16297. (`keyword
  16298. (let ((org-inhibit-startup-visibility-stuff t)
  16299. (org-startup-align-all-tables nil))
  16300. (when (boundp 'org-table-coordinate-overlays)
  16301. (mapc #'delete-overlay org-table-coordinate-overlays)
  16302. (setq org-table-coordinate-overlays nil))
  16303. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  16304. (message "Local setup has been refreshed"))
  16305. (`plain-list
  16306. ;; At a plain list, with a double C-u argument, set
  16307. ;; checkboxes of each item to "[-]", whereas a single one
  16308. ;; will toggle their presence according to the state of the
  16309. ;; first item in the list. Without an argument, repair the
  16310. ;; list.
  16311. (let* ((begin (org-element-property :contents-begin context))
  16312. (struct (org-element-property :structure context))
  16313. (old-struct (copy-tree struct))
  16314. (first-box (save-excursion
  16315. (goto-char begin)
  16316. (looking-at org-list-full-item-re)
  16317. (match-string-no-properties 3)))
  16318. (new-box (cond ((equal arg '(16)) "[-]")
  16319. ((equal arg '(4)) (unless first-box "[ ]"))
  16320. ((equal first-box "[X]") "[ ]")
  16321. (t "[X]"))))
  16322. (cond
  16323. (arg
  16324. (dolist (pos
  16325. (org-list-get-all-items
  16326. begin struct (org-list-prevs-alist struct)))
  16327. (org-list-set-checkbox pos struct new-box)))
  16328. ((and first-box (eq (point) begin))
  16329. ;; For convenience, when point is at bol on the first
  16330. ;; item of the list and no argument is provided, simply
  16331. ;; toggle checkbox of that item, if any.
  16332. (org-list-set-checkbox begin struct new-box)))
  16333. (when (equal
  16334. (org-list-write-struct
  16335. struct (org-list-parents-alist struct) old-struct)
  16336. old-struct)
  16337. (message "Cannot update this checkbox"))
  16338. (org-update-checkbox-count-maybe)))
  16339. ((or `property-drawer `node-property)
  16340. (call-interactively #'org-property-action))
  16341. (`radio-target
  16342. (call-interactively #'org-update-radio-target-regexp))
  16343. (`statistics-cookie
  16344. (call-interactively #'org-update-statistics-cookies))
  16345. ((or `table `table-cell `table-row)
  16346. ;; At a table, recalculate every field and align it. Also
  16347. ;; send the table if necessary. If the table has
  16348. ;; a `table.el' type, just give up. At a table row or cell,
  16349. ;; maybe recalculate line but always align table.
  16350. (if (eq (org-element-property :type context) 'table.el)
  16351. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16352. Use `\\[org-edit-special]' to edit table.el tables"))
  16353. (if (or (eq type 'table)
  16354. ;; Check if point is at a TBLFM line.
  16355. (and (eq type 'table-row)
  16356. (= (point) (org-element-property :end context))))
  16357. (save-excursion
  16358. (if (org-at-TBLFM-p)
  16359. (progn (require 'org-table)
  16360. (org-table-calc-current-TBLFM))
  16361. (goto-char (org-element-property :contents-begin context))
  16362. (org-call-with-arg 'org-table-recalculate (or arg t))
  16363. (orgtbl-send-table 'maybe)))
  16364. (org-table-maybe-eval-formula)
  16365. (cond (arg (call-interactively #'org-table-recalculate))
  16366. ((org-table-maybe-recalculate-line))
  16367. (t (org-table-align))))))
  16368. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16369. (org-timestamp-change 0 'day))
  16370. ((and `nil (guard (org-at-heading-p)))
  16371. ;; When point is on an unsupported object type, we can miss
  16372. ;; the fact that it also is at a heading. Handle it here.
  16373. (call-interactively #'org-set-tags-command))
  16374. ((guard
  16375. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16376. (_
  16377. (user-error
  16378. (substitute-command-keys
  16379. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16380. (defun org-mode-restart ()
  16381. (interactive)
  16382. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16383. (funcall major-mode)
  16384. (hack-local-variables)
  16385. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16386. (org-indent-mode -1))
  16387. (org-reset-file-cache))
  16388. (message "%s restarted" major-mode))
  16389. (defun org-flag-above-first-heading (&optional arg)
  16390. "Hide from bob up to the first heading.
  16391. Move point to the beginning of first heading or end of buffer."
  16392. (goto-char (point-min))
  16393. (unless (org-at-heading-p)
  16394. (outline-next-heading))
  16395. (unless (bobp)
  16396. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16397. (defun org-show-branches-buffer ()
  16398. "Show all branches in the buffer."
  16399. (org-flag-above-first-heading)
  16400. (outline-hide-sublevels 1)
  16401. (unless (eobp)
  16402. (outline-show-branches)
  16403. (while (outline-get-next-sibling)
  16404. (outline-show-branches)))
  16405. (goto-char (point-min)))
  16406. (defun org-kill-note-or-show-branches ()
  16407. "Abort storing current note, or show just branches."
  16408. (interactive)
  16409. (if org-finish-function
  16410. (let ((org-note-abort t))
  16411. (funcall org-finish-function))
  16412. (if (org-before-first-heading-p)
  16413. (org-show-branches-buffer)
  16414. (outline-hide-subtree)
  16415. (outline-show-branches))))
  16416. (defun org-delete-indentation (&optional arg)
  16417. "Join current line to previous and fix whitespace at join.
  16418. If previous line is a headline add to headline title. Otherwise
  16419. the function calls `delete-indentation'.
  16420. With a non-nil optional argument, join it to the following one."
  16421. (interactive "*P")
  16422. (if (save-excursion
  16423. (beginning-of-line (if arg 1 0))
  16424. (let ((case-fold-search nil))
  16425. (looking-at org-complex-heading-regexp)))
  16426. ;; At headline.
  16427. (let ((tags-column (when (match-beginning 5)
  16428. (save-excursion (goto-char (match-beginning 5))
  16429. (current-column))))
  16430. (string (concat " " (progn (when arg (forward-line 1))
  16431. (org-trim (delete-and-extract-region
  16432. (line-beginning-position)
  16433. (line-end-position)))))))
  16434. (unless (bobp) (delete-region (point) (1- (point))))
  16435. (goto-char (or (match-end 4)
  16436. (match-beginning 5)
  16437. (match-end 0)))
  16438. (skip-chars-backward " \t")
  16439. (save-excursion (insert string))
  16440. ;; Adjust alignment of tags.
  16441. (cond
  16442. ((not tags-column)) ;no tags
  16443. (org-auto-align-tags (org-align-tags))
  16444. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16445. (delete-indentation arg)))
  16446. (defun org-open-line (n)
  16447. "Insert a new row in tables, call `open-line' elsewhere.
  16448. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16449. As a special case, when a document starts with a table, allow to
  16450. call `open-line' on the very first character."
  16451. (interactive "*p")
  16452. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16453. (org-table-insert-row)
  16454. (open-line n)))
  16455. (defun org-return (&optional indent)
  16456. "Goto next table row or insert a newline.
  16457. Calls `org-table-next-row' or `newline', depending on context.
  16458. When optional INDENT argument is non-nil, call
  16459. `newline-and-indent' instead of `newline'.
  16460. When `org-return-follows-link' is non-nil and point is on
  16461. a timestamp or a link, call `org-open-at-point'. However, it
  16462. will not happen if point is in a table or on a \"dead\"
  16463. object (e.g., within a comment). In these case, you need to use
  16464. `org-open-at-point' directly."
  16465. (interactive)
  16466. (let ((context (if org-return-follows-link (org-element-context)
  16467. (org-element-at-point))))
  16468. (cond
  16469. ;; In a table, call `org-table-next-row'. However, before first
  16470. ;; column or after last one, split the table.
  16471. ((or (and (eq 'table (org-element-type context))
  16472. (not (eq 'table.el (org-element-property :type context)))
  16473. (>= (point) (org-element-property :contents-begin context))
  16474. (< (point) (org-element-property :contents-end context)))
  16475. (org-element-lineage context '(table-row table-cell) t))
  16476. (if (or (looking-at-p "[ \t]*$")
  16477. (save-excursion (skip-chars-backward " \t") (bolp)))
  16478. (insert "\n")
  16479. (org-table-justify-field-maybe)
  16480. (call-interactively #'org-table-next-row)))
  16481. ;; On a link or a timestamp, call `org-open-at-point' if
  16482. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16483. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16484. ((and org-return-follows-link
  16485. (or (and (eq 'link (org-element-type context))
  16486. ;; Ensure point is not on the white spaces after
  16487. ;; the link.
  16488. (let ((origin (point)))
  16489. (org-with-point-at (org-element-property :end context)
  16490. (skip-chars-backward " \t")
  16491. (> (point) origin))))
  16492. (org-in-regexp org-ts-regexp-both nil t)
  16493. (org-in-regexp org-tsr-regexp-both nil t)
  16494. (org-in-regexp org-link-any-re nil t)))
  16495. (call-interactively #'org-open-at-point))
  16496. ;; Insert newline in heading, but preserve tags.
  16497. ((and (not (bolp))
  16498. (let ((case-fold-search nil))
  16499. (org-match-line org-complex-heading-regexp)))
  16500. ;; At headline. Split line. However, if point is on keyword,
  16501. ;; priority cookie or tags, do not break any of them: add
  16502. ;; a newline after the headline instead.
  16503. (let ((tags-column (and (match-beginning 5)
  16504. (save-excursion (goto-char (match-beginning 5))
  16505. (current-column))))
  16506. (string
  16507. (when (and (match-end 4) (org-point-in-group (point) 4))
  16508. (delete-and-extract-region (point) (match-end 4)))))
  16509. ;; Adjust tag alignment.
  16510. (cond
  16511. ((not (and tags-column string)))
  16512. (org-auto-align-tags (org-align-tags))
  16513. (t (org--align-tags-here tags-column))) ;preserve tags column
  16514. (end-of-line)
  16515. (org-show-entry)
  16516. (if indent (newline-and-indent) (newline))
  16517. (when string (save-excursion (insert (org-trim string))))))
  16518. ;; In a list, make sure indenting keeps trailing text within.
  16519. ((and indent
  16520. (not (eolp))
  16521. (org-element-lineage context '(item)))
  16522. (let ((trailing-data
  16523. (delete-and-extract-region (point) (line-end-position))))
  16524. (newline-and-indent)
  16525. (save-excursion (insert trailing-data))))
  16526. (t
  16527. ;; Do not auto-fill when point is in an Org property drawer.
  16528. (let ((auto-fill-function (and (not (org-at-property-p))
  16529. auto-fill-function)))
  16530. (if indent
  16531. (newline-and-indent)
  16532. (newline)))))))
  16533. (defun org-return-indent ()
  16534. "Goto next table row or insert a newline and indent.
  16535. Calls `org-table-next-row' or `newline-and-indent', depending on
  16536. context. See the individual commands for more information."
  16537. (interactive)
  16538. (org-return t))
  16539. (defun org-ctrl-c-tab (&optional arg)
  16540. "Toggle columns width in a table, or show children.
  16541. Call `org-table-toggle-column-width' if point is in a table.
  16542. Otherwise, call `org-show-children'. ARG is the level to hide."
  16543. (interactive "p")
  16544. (if (org-at-table-p)
  16545. (call-interactively #'org-table-toggle-column-width)
  16546. (if (org-before-first-heading-p)
  16547. (progn
  16548. (org-flag-above-first-heading)
  16549. (outline-hide-sublevels (or arg 1))
  16550. (goto-char (point-min)))
  16551. (outline-hide-subtree)
  16552. (org-show-children arg))))
  16553. (defun org-ctrl-c-star ()
  16554. "Compute table, or change heading status of lines.
  16555. Calls `org-table-recalculate' or `org-toggle-heading',
  16556. depending on context."
  16557. (interactive)
  16558. (cond
  16559. ((org-at-table-p)
  16560. (call-interactively 'org-table-recalculate))
  16561. (t
  16562. ;; Convert all lines in region to list items
  16563. (call-interactively 'org-toggle-heading))))
  16564. (defun org-ctrl-c-minus ()
  16565. "Insert separator line in table or modify bullet status of line.
  16566. Also turns a plain line or a region of lines into list items.
  16567. Calls `org-table-insert-hline', `org-toggle-item', or
  16568. `org-cycle-list-bullet', depending on context."
  16569. (interactive)
  16570. (cond
  16571. ((org-at-table-p)
  16572. (call-interactively 'org-table-insert-hline))
  16573. ((org-region-active-p)
  16574. (call-interactively 'org-toggle-item))
  16575. ((org-in-item-p)
  16576. (call-interactively 'org-cycle-list-bullet))
  16577. (t
  16578. (call-interactively 'org-toggle-item))))
  16579. (defun org-toggle-heading (&optional nstars)
  16580. "Convert headings to normal text, or items or text to headings.
  16581. If there is no active region, only convert the current line.
  16582. With a `\\[universal-argument]' prefix, convert the whole list at
  16583. point into heading.
  16584. In a region:
  16585. - If the first non blank line is a headline, remove the stars
  16586. from all headlines in the region.
  16587. - If it is a normal line, turn each and every normal line (i.e.,
  16588. not an heading or an item) in the region into headings. If you
  16589. want to convert only the first line of this region, use one
  16590. universal prefix argument.
  16591. - If it is a plain list item, turn all plain list items into headings.
  16592. When converting a line into a heading, the number of stars is chosen
  16593. such that the lines become children of the current entry. However,
  16594. when a numeric prefix argument is given, its value determines the
  16595. number of stars to add."
  16596. (interactive "P")
  16597. (let ((skip-blanks
  16598. (function
  16599. ;; Return beginning of first non-blank line, starting from
  16600. ;; line at POS.
  16601. (lambda (pos)
  16602. (save-excursion
  16603. (goto-char pos)
  16604. (while (org-at-comment-p) (forward-line))
  16605. (skip-chars-forward " \r\t\n")
  16606. (point-at-bol)))))
  16607. beg end toggled)
  16608. ;; Determine boundaries of changes. If a universal prefix has
  16609. ;; been given, put the list in a region. If region ends at a bol,
  16610. ;; do not consider the last line to be in the region.
  16611. (when (and current-prefix-arg (org-at-item-p))
  16612. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16613. (org-mark-element))
  16614. (if (org-region-active-p)
  16615. (setq beg (funcall skip-blanks (region-beginning))
  16616. end (copy-marker (save-excursion
  16617. (goto-char (region-end))
  16618. (if (bolp) (point) (point-at-eol)))))
  16619. (setq beg (funcall skip-blanks (point-at-bol))
  16620. end (copy-marker (point-at-eol))))
  16621. ;; Ensure inline tasks don't count as headings.
  16622. (org-with-limited-levels
  16623. (save-excursion
  16624. (goto-char beg)
  16625. (cond
  16626. ;; Case 1. Started at an heading: de-star headings.
  16627. ((org-at-heading-p)
  16628. (while (< (point) end)
  16629. (when (org-at-heading-p t)
  16630. (looking-at org-outline-regexp) (replace-match "")
  16631. (setq toggled t))
  16632. (forward-line)))
  16633. ;; Case 2. Started at an item: change items into headlines.
  16634. ;; One star will be added by `org-list-to-subtree'.
  16635. ((org-at-item-p)
  16636. (while (< (point) end)
  16637. (when (org-at-item-p)
  16638. ;; Pay attention to cases when region ends before list.
  16639. (let* ((struct (org-list-struct))
  16640. (list-end
  16641. (min (org-list-get-bottom-point struct) (1+ end))))
  16642. (save-restriction
  16643. (narrow-to-region (point) list-end)
  16644. (insert (org-list-to-subtree
  16645. (org-list-to-lisp t)
  16646. (pcase (org-current-level)
  16647. (`nil 1)
  16648. (l (1+ (org-reduced-level l)))))
  16649. "\n")))
  16650. (setq toggled t))
  16651. (forward-line)))
  16652. ;; Case 3. Started at normal text: make every line an heading,
  16653. ;; skipping headlines and items.
  16654. (t (let* ((stars
  16655. (make-string
  16656. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16657. (add-stars
  16658. (cond (nstars "") ; stars from prefix only
  16659. ((equal stars "") "*") ; before first heading
  16660. (org-odd-levels-only "**") ; inside heading, odd
  16661. (t "*"))) ; inside heading, oddeven
  16662. (rpl (concat stars add-stars " "))
  16663. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16664. (while (< (point) (if (equal nstars '(4)) lend end))
  16665. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16666. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16667. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16668. (forward-line)))))))
  16669. (unless toggled (message "Cannot toggle heading from here"))))
  16670. (defun org-meta-return (&optional arg)
  16671. "Insert a new heading or wrap a region in a table.
  16672. Calls `org-insert-heading', `org-insert-item' or
  16673. `org-table-wrap-region', depending on context. When called with
  16674. an argument, unconditionally call `org-insert-heading'."
  16675. (interactive "P")
  16676. (org-check-before-invisible-edit 'insert)
  16677. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16678. (call-interactively (cond (arg #'org-insert-heading)
  16679. ((org-at-table-p) #'org-table-wrap-region)
  16680. ((org-in-item-p) #'org-insert-item)
  16681. (t #'org-insert-heading)))))
  16682. ;;; Menu entries
  16683. (defsubst org-in-subtree-not-table-p ()
  16684. "Are we in a subtree and not in a table?"
  16685. (and (not (org-before-first-heading-p))
  16686. (not (org-at-table-p))))
  16687. ;; Define the Org mode menus
  16688. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  16689. '("Tbl"
  16690. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16691. ["Next Field" org-cycle (org-at-table-p)]
  16692. ["Previous Field" org-shifttab (org-at-table-p)]
  16693. ["Next Row" org-return (org-at-table-p)]
  16694. "--"
  16695. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16696. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16697. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16698. "--"
  16699. ("Column"
  16700. ["Move Column Left" org-metaleft (org-at-table-p)]
  16701. ["Move Column Right" org-metaright (org-at-table-p)]
  16702. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16703. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16704. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16705. ("Row"
  16706. ["Move Row Up" org-metaup (org-at-table-p)]
  16707. ["Move Row Down" org-metadown (org-at-table-p)]
  16708. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16709. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16710. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16711. "--"
  16712. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16713. ("Rectangle"
  16714. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16715. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16716. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16717. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16718. "--"
  16719. ("Calculate"
  16720. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16721. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16722. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16723. "--"
  16724. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16725. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16726. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16727. "--"
  16728. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16729. "--"
  16730. ["Sum Column/Rectangle" org-table-sum
  16731. (or (org-at-table-p) (org-region-active-p))]
  16732. ["Which Column?" org-table-current-column (org-at-table-p)])
  16733. ["Debug Formulas"
  16734. org-table-toggle-formula-debugger
  16735. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16736. ["Show Col/Row Numbers"
  16737. org-table-toggle-coordinate-overlays
  16738. :style toggle
  16739. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16740. "--"
  16741. ["Create" org-table-create (not (org-at-table-p))]
  16742. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16743. ["Import from File" org-table-import (not (org-at-table-p))]
  16744. ["Export to File" org-table-export (org-at-table-p)]
  16745. "--"
  16746. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16747. "--"
  16748. ("Plot"
  16749. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16750. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16751. (easy-menu-define org-org-menu org-mode-map "Org menu"
  16752. '("Org"
  16753. ("Show/Hide"
  16754. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16755. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16756. ["Sparse Tree..." org-sparse-tree t]
  16757. ["Reveal Context" org-reveal t]
  16758. ["Show All" org-show-all t]
  16759. "--"
  16760. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16761. "--"
  16762. ["New Heading" org-insert-heading t]
  16763. ("Navigate Headings"
  16764. ["Up" outline-up-heading t]
  16765. ["Next" outline-next-visible-heading t]
  16766. ["Previous" outline-previous-visible-heading t]
  16767. ["Next Same Level" outline-forward-same-level t]
  16768. ["Previous Same Level" outline-backward-same-level t]
  16769. "--"
  16770. ["Jump" org-goto t])
  16771. ("Edit Structure"
  16772. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  16773. "--"
  16774. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16775. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16776. "--"
  16777. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16778. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16779. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16780. "--"
  16781. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16782. "--"
  16783. ["Copy visible text" org-copy-visible t]
  16784. "--"
  16785. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16786. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16787. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16788. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16789. "--"
  16790. ["Sort Region/Children" org-sort t]
  16791. "--"
  16792. ["Convert to odd levels" org-convert-to-odd-levels t]
  16793. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16794. ("Editing"
  16795. ["Emphasis..." org-emphasize t]
  16796. ["Edit Source Example" org-edit-special t]
  16797. "--"
  16798. ["Footnote new/jump" org-footnote-action t]
  16799. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16800. ("Archive"
  16801. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16802. "--"
  16803. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16804. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16805. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  16806. )
  16807. "--"
  16808. ("Hyperlinks"
  16809. ["Store Link (Global)" org-store-link t]
  16810. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16811. ["Insert Link" org-insert-link t]
  16812. ["Follow Link" org-open-at-point t]
  16813. "--"
  16814. ["Next link" org-next-link t]
  16815. ["Previous link" org-previous-link t]
  16816. "--"
  16817. ["Descriptive Links"
  16818. org-toggle-link-display
  16819. :style radio
  16820. :selected org-descriptive-links
  16821. ]
  16822. ["Literal Links"
  16823. org-toggle-link-display
  16824. :style radio
  16825. :selected (not org-descriptive-links)])
  16826. "--"
  16827. ("TODO Lists"
  16828. ["TODO/DONE/-" org-todo t]
  16829. ("Select keyword"
  16830. ["Next keyword" org-shiftright (org-at-heading-p)]
  16831. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16832. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16833. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16834. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16835. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16836. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16837. "--"
  16838. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16839. :selected org-enforce-todo-dependencies :style toggle :active t]
  16840. "Settings for tree at point"
  16841. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16842. :selected (org-entry-get nil "ORDERED")
  16843. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16844. ["Do Children parallel" org-toggle-ordered-property :style radio
  16845. :selected (not (org-entry-get nil "ORDERED"))
  16846. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16847. "--"
  16848. ["Set Priority" org-priority t]
  16849. ["Priority Up" org-shiftup t]
  16850. ["Priority Down" org-shiftdown t]
  16851. "--"
  16852. ["Get news from all feeds" org-feed-update-all t]
  16853. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16854. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16855. ("TAGS and Properties"
  16856. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16857. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16858. "--"
  16859. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16860. ["Column view of properties" org-columns t]
  16861. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16862. ("Dates and Scheduling"
  16863. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16864. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16865. ("Change Date"
  16866. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16867. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16868. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16869. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16870. ["Compute Time Range" org-evaluate-time-range t]
  16871. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16872. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16873. "--"
  16874. ["Custom time format" org-toggle-time-stamp-overlays
  16875. :style radio :selected org-display-custom-times]
  16876. "--"
  16877. ["Goto Calendar" org-goto-calendar t]
  16878. ["Date from Calendar" org-date-from-calendar t]
  16879. "--"
  16880. ["Start/Restart Timer" org-timer-start t]
  16881. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16882. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16883. ["Insert Timer String" org-timer t]
  16884. ["Insert Timer Item" org-timer-item t])
  16885. ("Logging work"
  16886. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16887. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16888. ["Clock out" org-clock-out t]
  16889. ["Clock cancel" org-clock-cancel t]
  16890. "--"
  16891. ["Mark as default task" org-clock-mark-default-task t]
  16892. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16893. ["Goto running clock" org-clock-goto t]
  16894. "--"
  16895. ["Display times" org-clock-display t]
  16896. ["Create clock table" org-clock-report t]
  16897. "--"
  16898. ["Record DONE time"
  16899. (progn (setq org-log-done (not org-log-done))
  16900. (message "Switching to %s will %s record a timestamp"
  16901. (car org-done-keywords)
  16902. (if org-log-done "automatically" "not")))
  16903. :style toggle :selected org-log-done])
  16904. "--"
  16905. ["Agenda Command..." org-agenda t]
  16906. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16907. ("File List for Agenda")
  16908. ("Special views current file"
  16909. ["TODO Tree" org-show-todo-tree t]
  16910. ["Check Deadlines" org-check-deadlines t]
  16911. ["Tags/Property tree" org-match-sparse-tree t])
  16912. "--"
  16913. ["Export/Publish..." org-export-dispatch t]
  16914. ("LaTeX"
  16915. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16916. :style toggle :selected org-cdlatex-mode]
  16917. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16918. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16919. ["Modify math symbol" org-cdlatex-math-modify
  16920. (org-inside-LaTeX-fragment-p)]
  16921. ["Insert citation" org-reftex-citation t])
  16922. "--"
  16923. ("MobileOrg"
  16924. ["Push Files and Views" org-mobile-push t]
  16925. ["Get Captured and Flagged" org-mobile-pull t]
  16926. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  16927. "--"
  16928. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  16929. "--"
  16930. ("Documentation"
  16931. ["Show Version" org-version t]
  16932. ["Info Documentation" org-info t]
  16933. ["Browse Org News" org-browse-news t])
  16934. ("Customize"
  16935. ["Browse Org Group" org-customize t]
  16936. "--"
  16937. ["Expand This Menu" org-create-customize-menu
  16938. (fboundp 'customize-menu-create)])
  16939. ["Send bug report" org-submit-bug-report t]
  16940. "--"
  16941. ("Refresh/Reload"
  16942. ["Refresh setup current buffer" org-mode-restart t]
  16943. ["Reload Org (after update)" org-reload t]
  16944. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16945. (defun org-info (&optional node)
  16946. "Read documentation for Org in the info system.
  16947. With optional NODE, go directly to that node."
  16948. (interactive)
  16949. (info (format "(org)%s" (or node ""))))
  16950. (defun org-browse-news ()
  16951. "Browse the news for the latest major release."
  16952. (interactive)
  16953. (browse-url "https://orgmode.org/Changes.html"))
  16954. ;;;###autoload
  16955. (defun org-submit-bug-report ()
  16956. "Submit a bug report on Org via mail.
  16957. Don't hesitate to report any problems or inaccurate documentation.
  16958. If you don't have setup sending mail from (X)Emacs, please copy the
  16959. output buffer into your mail program, as it gives us important
  16960. information about your Org version and configuration."
  16961. (interactive)
  16962. (require 'reporter)
  16963. (defvar reporter-prompt-for-summary-p)
  16964. (org-load-modules-maybe)
  16965. (org-require-autoloaded-modules)
  16966. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16967. (reporter-submit-bug-report
  16968. "emacs-orgmode@gnu.org"
  16969. (org-version nil 'full)
  16970. (let (list)
  16971. (save-window-excursion
  16972. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16973. (delete-other-windows)
  16974. (erase-buffer)
  16975. (insert "You are about to submit a bug report to the Org mailing list.
  16976. We would like to add your full Org and Outline configuration to the
  16977. bug report. This greatly simplifies the work of the maintainer and
  16978. other experts on the mailing list.
  16979. HOWEVER, some variables you have customized may contain private
  16980. information. The names of customers, colleagues, or friends, might
  16981. appear in the form of file names, tags, todo states, or search strings.
  16982. If you answer yes to the prompt, you might want to check and remove
  16983. such private information before sending the email.")
  16984. (add-text-properties (point-min) (point-max) '(face org-warning))
  16985. (when (yes-or-no-p "Include your Org configuration ")
  16986. (mapatoms
  16987. (lambda (v)
  16988. (and (boundp v)
  16989. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16990. (or (and (symbol-value v)
  16991. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16992. (and
  16993. (get v 'custom-type) (get v 'standard-value)
  16994. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  16995. (push v list)))))
  16996. (kill-buffer (get-buffer "*Warn about privacy*"))
  16997. list))
  16998. nil nil
  16999. "Remember to cover the basics, that is, what you expected to happen and
  17000. what in fact did happen. You don't know how to make a good report? See
  17001. https://orgmode.org/manual/Feedback.html#Feedback
  17002. Your bug report will be posted to the Org mailing list.
  17003. ------------------------------------------------------------------------")
  17004. (save-excursion
  17005. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  17006. (replace-match "\\1Bug: \\3 [\\2]")))))
  17007. (defun org-install-agenda-files-menu ()
  17008. (let ((bl (buffer-list)))
  17009. (save-excursion
  17010. (while bl
  17011. (set-buffer (pop bl))
  17012. (when (derived-mode-p 'org-mode) (setq bl nil)))
  17013. (when (derived-mode-p 'org-mode)
  17014. (easy-menu-change
  17015. '("Org") "File List for Agenda"
  17016. (append
  17017. (list
  17018. ["Edit File List" (org-edit-agenda-file-list) t]
  17019. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  17020. ["Remove Current File from List" org-remove-file t]
  17021. ["Cycle through agenda files" org-cycle-agenda-files t]
  17022. ["Occur in all agenda files" org-occur-in-agenda-files t]
  17023. "--")
  17024. (mapcar 'org-file-menu-entry
  17025. ;; Prevent initialization from failing.
  17026. (ignore-errors (org-agenda-files t)))))))))
  17027. ;;;; Documentation
  17028. (defun org-require-autoloaded-modules ()
  17029. (interactive)
  17030. (mapc #'require
  17031. '(org-agenda org-archive org-attach org-clock org-colview org-id
  17032. org-table org-timer)))
  17033. ;;;###autoload
  17034. (defun org-reload (&optional uncompiled)
  17035. "Reload all Org Lisp files.
  17036. With prefix arg UNCOMPILED, load the uncompiled versions."
  17037. (interactive "P")
  17038. (require 'loadhist)
  17039. (let* ((org-dir (org-find-library-dir "org"))
  17040. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  17041. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  17042. (remove-re (format "\\`%s\\'"
  17043. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  17044. (feats (delete-dups
  17045. (mapcar 'file-name-sans-extension
  17046. (mapcar 'file-name-nondirectory
  17047. (delq nil
  17048. (mapcar 'feature-file
  17049. features))))))
  17050. (lfeat (append
  17051. (sort
  17052. (setq feats
  17053. (delq nil (mapcar
  17054. (lambda (f)
  17055. (if (and (string-match feature-re f)
  17056. (not (string-match remove-re f)))
  17057. f nil))
  17058. feats)))
  17059. 'string-lessp)
  17060. (list "org-version" "org")))
  17061. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  17062. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  17063. load-uncore load-misses)
  17064. (setq load-misses
  17065. (delq 't
  17066. (mapcar (lambda (f)
  17067. (or (org-load-noerror-mustsuffix (concat org-dir f))
  17068. (and (string= org-dir contrib-dir)
  17069. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  17070. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  17071. (add-to-list 'load-uncore f 'append)
  17072. 't)
  17073. f))
  17074. lfeat)))
  17075. (when load-uncore
  17076. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  17077. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  17078. (if load-misses
  17079. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  17080. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  17081. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  17082. ;;;###autoload
  17083. (defun org-customize ()
  17084. "Call the customize function with org as argument."
  17085. (interactive)
  17086. (org-load-modules-maybe)
  17087. (org-require-autoloaded-modules)
  17088. (customize-browse 'org))
  17089. (defun org-create-customize-menu ()
  17090. "Create a full customization menu for Org mode, insert it into the menu."
  17091. (interactive)
  17092. (org-load-modules-maybe)
  17093. (org-require-autoloaded-modules)
  17094. (if (fboundp 'customize-menu-create)
  17095. (progn
  17096. (easy-menu-change
  17097. '("Org") "Customize"
  17098. `(["Browse Org group" org-customize t]
  17099. "--"
  17100. ,(customize-menu-create 'org)
  17101. ["Set" Custom-set t]
  17102. ["Save" Custom-save t]
  17103. ["Reset to Current" Custom-reset-current t]
  17104. ["Reset to Saved" Custom-reset-saved t]
  17105. ["Reset to Standard Settings" Custom-reset-standard t]))
  17106. (message "\"Org\"-menu now contains full customization menu"))
  17107. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  17108. ;;;; Miscellaneous stuff
  17109. ;;; Generally useful functions
  17110. (defun org-in-clocktable-p ()
  17111. "Check if the cursor is in a clocktable."
  17112. (let ((pos (point)) start)
  17113. (save-excursion
  17114. (end-of-line 1)
  17115. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  17116. (setq start (match-beginning 0))
  17117. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  17118. (>= (match-end 0) pos)
  17119. start))))
  17120. (defun org-in-verbatim-emphasis ()
  17121. (save-match-data
  17122. (and (org-in-regexp org-verbatim-re 2)
  17123. (>= (point) (match-beginning 3))
  17124. (<= (point) (match-end 4)))))
  17125. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  17126. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  17127. (if (and marker (marker-buffer marker)
  17128. (buffer-live-p (marker-buffer marker)))
  17129. (progn
  17130. (pop-to-buffer-same-window (marker-buffer marker))
  17131. (when (or (> marker (point-max)) (< marker (point-min)))
  17132. (widen))
  17133. (goto-char marker)
  17134. (org-show-context 'org-goto))
  17135. (if bookmark
  17136. (bookmark-jump bookmark)
  17137. (error "Cannot find location"))))
  17138. (defun org-quote-csv-field (s)
  17139. "Quote field for inclusion in CSV material."
  17140. (if (string-match "[\",]" s)
  17141. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  17142. s))
  17143. (defun org-force-self-insert (N)
  17144. "Needed to enforce self-insert under remapping."
  17145. (interactive "p")
  17146. (self-insert-command N))
  17147. (defun org-quote-vert (s)
  17148. "Replace \"|\" with \"\\vert\"."
  17149. (while (string-match "|" s)
  17150. (setq s (replace-match "\\vert" t t s)))
  17151. s)
  17152. (defun org-uuidgen-p (s)
  17153. "Is S an ID created by UUIDGEN?"
  17154. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  17155. (defun org-in-src-block-p (&optional inside)
  17156. "Whether point is in a code source block.
  17157. When INSIDE is non-nil, don't consider we are within a source
  17158. block when point is at #+BEGIN_SRC or #+END_SRC."
  17159. (let ((case-fold-search t))
  17160. (or (and (eq (get-char-property (point) 'src-block) t))
  17161. (and (not inside)
  17162. (save-match-data
  17163. (save-excursion
  17164. (beginning-of-line)
  17165. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  17166. (defun org-context ()
  17167. "Return a list of contexts of the current cursor position.
  17168. If several contexts apply, all are returned.
  17169. Each context entry is a list with a symbol naming the context, and
  17170. two positions indicating start and end of the context. Possible
  17171. contexts are:
  17172. :headline anywhere in a headline
  17173. :headline-stars on the leading stars in a headline
  17174. :todo-keyword on a TODO keyword (including DONE) in a headline
  17175. :tags on the TAGS in a headline
  17176. :priority on the priority cookie in a headline
  17177. :item on the first line of a plain list item
  17178. :item-bullet on the bullet/number of a plain list item
  17179. :checkbox on the checkbox in a plain list item
  17180. :table in an Org table
  17181. :table-special on a special filed in a table
  17182. :table-table in a table.el table
  17183. :clocktable in a clocktable
  17184. :src-block in a source block
  17185. :link on a hyperlink
  17186. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  17187. :latex-fragment on a LaTeX fragment
  17188. :latex-preview on a LaTeX fragment with overlaid preview image
  17189. This function expects the position to be visible because it uses font-lock
  17190. faces as a help to recognize the following contexts: :table-special, :link,
  17191. and :keyword."
  17192. (let* ((f (get-text-property (point) 'face))
  17193. (faces (if (listp f) f (list f)))
  17194. (case-fold-search t)
  17195. (p (point)) clist o)
  17196. ;; First the large context
  17197. (cond
  17198. ((org-at-heading-p t)
  17199. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  17200. (when (progn
  17201. (beginning-of-line 1)
  17202. (looking-at org-todo-line-tags-regexp))
  17203. (push (org-point-in-group p 1 :headline-stars) clist)
  17204. (push (org-point-in-group p 2 :todo-keyword) clist)
  17205. (push (org-point-in-group p 4 :tags) clist))
  17206. (goto-char p)
  17207. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  17208. (when (looking-at "\\[#[A-Z0-9]\\]")
  17209. (push (org-point-in-group p 0 :priority) clist)))
  17210. ((org-at-item-p)
  17211. (push (org-point-in-group p 2 :item-bullet) clist)
  17212. (push (list :item (point-at-bol)
  17213. (save-excursion (org-end-of-item) (point)))
  17214. clist)
  17215. (and (org-at-item-checkbox-p)
  17216. (push (org-point-in-group p 0 :checkbox) clist)))
  17217. ((org-at-table-p)
  17218. (push (list :table (org-table-begin) (org-table-end)) clist)
  17219. (when (memq 'org-formula faces)
  17220. (push (list :table-special
  17221. (previous-single-property-change p 'face)
  17222. (next-single-property-change p 'face)) clist)))
  17223. ((org-at-table-p 'any)
  17224. (push (list :table-table) clist)))
  17225. (goto-char p)
  17226. (let ((case-fold-search t))
  17227. ;; New the "medium" contexts: clocktables, source blocks
  17228. (cond ((org-in-clocktable-p)
  17229. (push (list :clocktable
  17230. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  17231. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  17232. (match-beginning 1))
  17233. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  17234. (match-end 0))) clist))
  17235. ((org-in-src-block-p)
  17236. (push (list :src-block
  17237. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  17238. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  17239. (match-beginning 1))
  17240. (and (search-forward "#+END_SRC" nil t)
  17241. (match-beginning 0))) clist))))
  17242. (goto-char p)
  17243. ;; Now the small context
  17244. (cond
  17245. ((org-at-timestamp-p)
  17246. (push (org-point-in-group p 0 :timestamp) clist))
  17247. ((memq 'org-link faces)
  17248. (push (list :link
  17249. (previous-single-property-change p 'face)
  17250. (next-single-property-change p 'face)) clist))
  17251. ((memq 'org-special-keyword faces)
  17252. (push (list :keyword
  17253. (previous-single-property-change p 'face)
  17254. (next-single-property-change p 'face)) clist))
  17255. ((setq o (cl-some
  17256. (lambda (o)
  17257. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  17258. o))
  17259. (overlays-at (point))))
  17260. (push (list :latex-fragment
  17261. (overlay-start o) (overlay-end o)) clist)
  17262. (push (list :latex-preview
  17263. (overlay-start o) (overlay-end o)) clist))
  17264. ((org-inside-LaTeX-fragment-p)
  17265. ;; FIXME: positions wrong.
  17266. (push (list :latex-fragment (point) (point)) clist)))
  17267. (setq clist (nreverse (delq nil clist)))
  17268. clist))
  17269. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  17270. "Non-nil when point is between matches of START-RE and END-RE.
  17271. Also return a non-nil value when point is on one of the matches.
  17272. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  17273. buffer positions. Default values are the positions of headlines
  17274. surrounding the point.
  17275. The functions returns a cons cell whose car (resp. cdr) is the
  17276. position before START-RE (resp. after END-RE)."
  17277. (save-match-data
  17278. (let ((pos (point))
  17279. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  17280. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  17281. beg end)
  17282. (save-excursion
  17283. ;; Point is on a block when on START-RE or if START-RE can be
  17284. ;; found before it...
  17285. (and (or (org-in-regexp start-re)
  17286. (re-search-backward start-re limit-up t))
  17287. (setq beg (match-beginning 0))
  17288. ;; ... and END-RE after it...
  17289. (goto-char (match-end 0))
  17290. (re-search-forward end-re limit-down t)
  17291. (> (setq end (match-end 0)) pos)
  17292. ;; ... without another START-RE in-between.
  17293. (goto-char (match-beginning 0))
  17294. (not (re-search-backward start-re (1+ beg) t))
  17295. ;; Return value.
  17296. (cons beg end))))))
  17297. (defun org-in-block-p (names)
  17298. "Non-nil when point belongs to a block whose name belongs to NAMES.
  17299. NAMES is a list of strings containing names of blocks.
  17300. Return first block name matched, or nil. Beware that in case of
  17301. nested blocks, the returned name may not belong to the closest
  17302. block from point."
  17303. (save-match-data
  17304. (catch 'exit
  17305. (let ((case-fold-search t)
  17306. (lim-up (save-excursion (outline-previous-heading)))
  17307. (lim-down (save-excursion (outline-next-heading))))
  17308. (dolist (name names)
  17309. (let ((n (regexp-quote name)))
  17310. (when (org-between-regexps-p
  17311. (concat "^[ \t]*#\\+begin_" n)
  17312. (concat "^[ \t]*#\\+end_" n)
  17313. lim-up lim-down)
  17314. (throw 'exit n)))))
  17315. nil)))
  17316. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  17317. "Call `multi-occur' with buffers for all agenda files."
  17318. (interactive "sOrg-files matching: ")
  17319. (let* ((files (org-agenda-files))
  17320. (tnames (mapcar #'file-truename files))
  17321. (extra org-agenda-text-search-extra-files))
  17322. (when (eq (car extra) 'agenda-archives)
  17323. (setq extra (cdr extra))
  17324. (setq files (org-add-archive-files files)))
  17325. (dolist (f extra)
  17326. (unless (member (file-truename f) tnames)
  17327. (unless (member f files) (setq files (append files (list f))))
  17328. (setq tnames (append tnames (list (file-truename f))))))
  17329. (multi-occur
  17330. (mapcar (lambda (x)
  17331. (with-current-buffer
  17332. ;; FIXME: Why not just (find-file-noselect x)?
  17333. ;; Is it to avoid the "revert buffer" prompt?
  17334. (or (get-file-buffer x) (find-file-noselect x))
  17335. (widen)
  17336. (current-buffer)))
  17337. files)
  17338. regexp)))
  17339. (add-hook 'occur-mode-find-occurrence-hook
  17340. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17341. (defun org-occur-link-in-agenda-files ()
  17342. "Create a link and search for it in the agendas.
  17343. The link is not stored in `org-stored-links', it is just created
  17344. for the search purpose."
  17345. (interactive)
  17346. (let ((link (condition-case nil
  17347. (org-store-link nil)
  17348. (error "Unable to create a link to here"))))
  17349. (org-occur-in-agenda-files (regexp-quote link))))
  17350. (defun org-back-over-empty-lines ()
  17351. "Move backwards over whitespace, to the beginning of the first empty line.
  17352. Returns the number of empty lines passed."
  17353. (let ((pos (point)))
  17354. (if (cdr (assq 'heading org-blank-before-new-entry))
  17355. (skip-chars-backward " \t\n\r")
  17356. (unless (eobp)
  17357. (forward-line -1)))
  17358. (beginning-of-line 2)
  17359. (goto-char (min (point) pos))
  17360. (count-lines (point) pos)))
  17361. ;;; TODO: Only called once, from ox-odt which should probably use
  17362. ;;; org-export-inline-image-p or something.
  17363. (defun org-file-image-p (file)
  17364. "Return non-nil if FILE is an image."
  17365. (save-match-data
  17366. (string-match (image-file-name-regexp) file)))
  17367. (defun org-get-cursor-date (&optional with-time)
  17368. "Return the date at cursor in as a time.
  17369. This works in the calendar and in the agenda, anywhere else it just
  17370. returns the current time.
  17371. If WITH-TIME is non-nil, returns the time of the event at point (in
  17372. the agenda) or the current time of the day; otherwise returns the
  17373. earliest time on the cursor date that Org treats as that date
  17374. (bearing in mind `org-extend-today-until')."
  17375. (let (date day defd tp hod mod)
  17376. (when with-time
  17377. (setq tp (get-text-property (point) 'time))
  17378. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  17379. (setq hod (string-to-number (match-string 1 tp))
  17380. mod (string-to-number (match-string 2 tp))))
  17381. (or tp (let ((now (decode-time)))
  17382. (setq hod (nth 2 now)
  17383. mod (nth 1 now)))))
  17384. (cond
  17385. ((eq major-mode 'calendar-mode)
  17386. (setq date (calendar-cursor-to-date)
  17387. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17388. (nth 1 date) (nth 0 date) (nth 2 date))))
  17389. ((eq major-mode 'org-agenda-mode)
  17390. (setq day (get-text-property (point) 'day))
  17391. (when day
  17392. (setq date (calendar-gregorian-from-absolute day)
  17393. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17394. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17395. (or defd (current-time))))
  17396. (defun org-mark-subtree (&optional up)
  17397. "Mark the current subtree.
  17398. This puts point at the start of the current subtree, and mark at
  17399. the end. If a numeric prefix UP is given, move up into the
  17400. hierarchy of headlines by UP levels before marking the subtree."
  17401. (interactive "P")
  17402. (org-with-limited-levels
  17403. (cond ((org-at-heading-p) (beginning-of-line))
  17404. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17405. (t (outline-previous-visible-heading 1))))
  17406. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17407. (if (called-interactively-p 'any)
  17408. (call-interactively 'org-mark-element)
  17409. (org-mark-element)))
  17410. ;;; Indentation
  17411. (defvar org-element-greater-elements)
  17412. (defun org--get-expected-indentation (element contentsp)
  17413. "Expected indentation column for current line, according to ELEMENT.
  17414. ELEMENT is an element containing point. CONTENTSP is non-nil
  17415. when indentation is to be computed according to contents of
  17416. ELEMENT."
  17417. (let ((type (org-element-type element))
  17418. (start (org-element-property :begin element))
  17419. (post-affiliated (org-element-property :post-affiliated element)))
  17420. (org-with-wide-buffer
  17421. (cond
  17422. (contentsp
  17423. (cl-case type
  17424. ((diary-sexp footnote-definition) 0)
  17425. ((headline inlinetask nil)
  17426. (if (not org-adapt-indentation) 0
  17427. (let ((level (org-current-level)))
  17428. (if level (1+ level) 0))))
  17429. ((item plain-list) (org-list-item-body-column post-affiliated))
  17430. (t
  17431. (goto-char start)
  17432. (current-indentation))))
  17433. ((memq type '(headline inlinetask nil))
  17434. (if (org-match-line "[ \t]*$")
  17435. (org--get-expected-indentation element t)
  17436. 0))
  17437. ((memq type '(diary-sexp footnote-definition)) 0)
  17438. ;; First paragraph of a footnote definition or an item.
  17439. ;; Indent like parent.
  17440. ((< (line-beginning-position) start)
  17441. (org--get-expected-indentation
  17442. (org-element-property :parent element) t))
  17443. ;; At first line: indent according to previous sibling, if any,
  17444. ;; ignoring footnote definitions and inline tasks, or parent's
  17445. ;; contents.
  17446. ((= (line-beginning-position) start)
  17447. (catch 'exit
  17448. (while t
  17449. (if (= (point-min) start) (throw 'exit 0)
  17450. (goto-char (1- start))
  17451. (let* ((previous (org-element-at-point))
  17452. (parent previous))
  17453. (while (and parent (<= (org-element-property :end parent) start))
  17454. (setq previous parent
  17455. parent (org-element-property :parent parent)))
  17456. (cond
  17457. ((not previous) (throw 'exit 0))
  17458. ((> (org-element-property :end previous) start)
  17459. (throw 'exit (org--get-expected-indentation previous t)))
  17460. ((memq (org-element-type previous)
  17461. '(footnote-definition inlinetask))
  17462. (setq start (org-element-property :begin previous)))
  17463. (t (goto-char (org-element-property :begin previous))
  17464. (throw 'exit
  17465. (if (bolp) (current-indentation)
  17466. ;; At first paragraph in an item or
  17467. ;; a footnote definition.
  17468. (org--get-expected-indentation
  17469. (org-element-property :parent previous) t))))))))))
  17470. ;; Otherwise, move to the first non-blank line above.
  17471. (t
  17472. (beginning-of-line)
  17473. (let ((pos (point)))
  17474. (skip-chars-backward " \r\t\n")
  17475. (cond
  17476. ;; Two blank lines end a footnote definition or a plain
  17477. ;; list. When we indent an empty line after them, the
  17478. ;; containing list or footnote definition is over, so it
  17479. ;; qualifies as a previous sibling. Therefore, we indent
  17480. ;; like its first line.
  17481. ((and (memq type '(footnote-definition plain-list))
  17482. (> (count-lines (point) pos) 2))
  17483. (goto-char start)
  17484. (current-indentation))
  17485. ;; Line above is the first one of a paragraph at the
  17486. ;; beginning of an item or a footnote definition. Indent
  17487. ;; like parent.
  17488. ((< (line-beginning-position) start)
  17489. (org--get-expected-indentation
  17490. (org-element-property :parent element) t))
  17491. ;; Line above is the beginning of an element, i.e., point
  17492. ;; was originally on the blank lines between element's start
  17493. ;; and contents.
  17494. ((= (line-beginning-position) post-affiliated)
  17495. (org--get-expected-indentation element t))
  17496. ;; POS is after contents in a greater element. Indent like
  17497. ;; the beginning of the element.
  17498. ((and (memq type org-element-greater-elements)
  17499. (let ((cend (org-element-property :contents-end element)))
  17500. (and cend (<= cend pos))))
  17501. ;; As a special case, if point is at the end of a footnote
  17502. ;; definition or an item, indent like the very last element
  17503. ;; within. If that last element is an item, indent like
  17504. ;; its contents.
  17505. (if (memq type '(footnote-definition item plain-list))
  17506. (let ((last (org-element-at-point)))
  17507. (goto-char pos)
  17508. (org--get-expected-indentation
  17509. last (eq (org-element-type last) 'item)))
  17510. (goto-char start)
  17511. (current-indentation)))
  17512. ;; In any other case, indent like the current line.
  17513. (t (current-indentation)))))))))
  17514. (defun org--align-node-property ()
  17515. "Align node property at point.
  17516. Alignment is done according to `org-property-format', which see."
  17517. (when (save-excursion
  17518. (beginning-of-line)
  17519. (looking-at org-property-re))
  17520. (replace-match
  17521. (concat (match-string 4)
  17522. (org-trim
  17523. (format org-property-format (match-string 1) (match-string 3))))
  17524. t t)))
  17525. (defun org-indent-line ()
  17526. "Indent line depending on context.
  17527. Indentation is done according to the following rules:
  17528. - Footnote definitions, diary sexps, headlines and inline tasks
  17529. have to start at column 0.
  17530. - On the very first line of an element, consider, in order, the
  17531. next rules until one matches:
  17532. 1. If there's a sibling element before, ignoring footnote
  17533. definitions and inline tasks, indent like its first line.
  17534. 2. If element has a parent, indent like its contents. More
  17535. precisely, if parent is an item, indent after the bullet.
  17536. Else, indent like parent's first line.
  17537. 3. Otherwise, indent relatively to current level, if
  17538. `org-adapt-indentation' is non-nil, or to left margin.
  17539. - On a blank line at the end of an element, indent according to
  17540. the type of the element. More precisely
  17541. 1. If element is a plain list, an item, or a footnote
  17542. definition, indent like the very last element within.
  17543. 2. If element is a paragraph, indent like its last non blank
  17544. line.
  17545. 3. Otherwise, indent like its very first line.
  17546. - In the code part of a source block, use language major mode
  17547. to indent current line if `org-src-tab-acts-natively' is
  17548. non-nil. If it is nil, do nothing.
  17549. - Otherwise, indent like the first non-blank line above.
  17550. The function doesn't indent an item as it could break the whole
  17551. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17552. `\\[org-shiftmetaright]'.
  17553. Also align node properties according to `org-property-format'."
  17554. (interactive)
  17555. (cond
  17556. ((org-at-heading-p) 'noindent)
  17557. (t
  17558. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17559. (type (org-element-type element)))
  17560. (cond ((and (memq type '(plain-list item))
  17561. (= (line-beginning-position)
  17562. (org-element-property :post-affiliated element)))
  17563. 'noindent)
  17564. ((and (eq type 'latex-environment)
  17565. (>= (point) (org-element-property :post-affiliated element))
  17566. (< (point) (org-with-wide-buffer
  17567. (goto-char (org-element-property :end element))
  17568. (skip-chars-backward " \r\t\n")
  17569. (line-beginning-position 2))))
  17570. 'noindent)
  17571. ((and (eq type 'src-block)
  17572. org-src-tab-acts-natively
  17573. (> (line-beginning-position)
  17574. (org-element-property :post-affiliated element))
  17575. (< (line-beginning-position)
  17576. (org-with-wide-buffer
  17577. (goto-char (org-element-property :end element))
  17578. (skip-chars-backward " \r\t\n")
  17579. (line-beginning-position))))
  17580. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17581. (t
  17582. (let ((column (org--get-expected-indentation element nil)))
  17583. ;; Preserve current column.
  17584. (if (<= (current-column) (current-indentation))
  17585. (indent-line-to column)
  17586. (save-excursion (indent-line-to column))))
  17587. ;; Align node property. Also preserve current column.
  17588. (when (eq type 'node-property)
  17589. (let ((column (current-column)))
  17590. (org--align-node-property)
  17591. (org-move-to-column column)))))))))
  17592. (defun org-indent-region (start end)
  17593. "Indent each non-blank line in the region.
  17594. Called from a program, START and END specify the region to
  17595. indent. The function will not indent contents of example blocks,
  17596. verse blocks and export blocks as leading white spaces are
  17597. assumed to be significant there."
  17598. (interactive "r")
  17599. (save-excursion
  17600. (goto-char start)
  17601. (skip-chars-forward " \r\t\n")
  17602. (unless (eobp) (beginning-of-line))
  17603. (let ((indent-to
  17604. (lambda (ind pos)
  17605. ;; Set IND as indentation for all lines between point and
  17606. ;; POS. Blank lines are ignored. Leave point after POS
  17607. ;; once done.
  17608. (let ((limit (copy-marker pos)))
  17609. (while (< (point) limit)
  17610. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17611. (forward-line))
  17612. (set-marker limit nil))))
  17613. (end (copy-marker end)))
  17614. (while (< (point) end)
  17615. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17616. (let* ((element (org-element-at-point))
  17617. (type (org-element-type element))
  17618. (element-end (copy-marker (org-element-property :end element)))
  17619. (ind (org--get-expected-indentation element nil)))
  17620. (cond
  17621. ;; Element indented as a single block. Example blocks
  17622. ;; preserving indentation are a special case since the
  17623. ;; "contents" must not be indented whereas the block
  17624. ;; boundaries can.
  17625. ((or (memq type '(export-block latex-environment))
  17626. (and (eq type 'example-block)
  17627. (not
  17628. (or org-src-preserve-indentation
  17629. (org-element-property :preserve-indent element)))))
  17630. (let ((offset (- ind (current-indentation))))
  17631. (unless (zerop offset)
  17632. (indent-rigidly (org-element-property :begin element)
  17633. (org-element-property :end element)
  17634. offset)))
  17635. (goto-char element-end))
  17636. ;; Elements indented line wise. Be sure to exclude
  17637. ;; example blocks (preserving indentation) and source
  17638. ;; blocks from this category as they are treated
  17639. ;; specially later.
  17640. ((or (memq type '(paragraph table table-row))
  17641. (not (or (org-element-property :contents-begin element)
  17642. (memq type '(example-block src-block)))))
  17643. (when (eq type 'node-property)
  17644. (org--align-node-property)
  17645. (beginning-of-line))
  17646. (funcall indent-to ind (min element-end end)))
  17647. ;; Elements consisting of three parts: before the
  17648. ;; contents, the contents, and after the contents. The
  17649. ;; contents are treated specially, according to the
  17650. ;; element type, or not indented at all. Other parts are
  17651. ;; indented as a single block.
  17652. (t
  17653. (let* ((post (copy-marker
  17654. (org-element-property :post-affiliated element)))
  17655. (cbeg
  17656. (copy-marker
  17657. (cond
  17658. ((not (org-element-property :contents-begin element))
  17659. ;; Fake contents for source blocks.
  17660. (org-with-wide-buffer
  17661. (goto-char post)
  17662. (line-beginning-position 2)))
  17663. ((memq type '(footnote-definition item plain-list))
  17664. ;; Contents in these elements could start on
  17665. ;; the same line as the beginning of the
  17666. ;; element. Make sure we start indenting
  17667. ;; from the second line.
  17668. (org-with-wide-buffer
  17669. (goto-char post)
  17670. (end-of-line)
  17671. (skip-chars-forward " \r\t\n")
  17672. (if (eobp) (point) (line-beginning-position))))
  17673. (t (org-element-property :contents-begin element)))))
  17674. (cend (copy-marker
  17675. (or (org-element-property :contents-end element)
  17676. ;; Fake contents for source blocks.
  17677. (org-with-wide-buffer
  17678. (goto-char element-end)
  17679. (skip-chars-backward " \r\t\n")
  17680. (line-beginning-position)))
  17681. t)))
  17682. ;; Do not change items indentation individually as it
  17683. ;; might break the list as a whole. On the other
  17684. ;; hand, when at a plain list, indent it as a whole.
  17685. (cond ((eq type 'plain-list)
  17686. (let ((offset (- ind (current-indentation))))
  17687. (unless (zerop offset)
  17688. (indent-rigidly (org-element-property :begin element)
  17689. (org-element-property :end element)
  17690. offset))
  17691. (goto-char cbeg)))
  17692. ((eq type 'item) (goto-char cbeg))
  17693. (t (funcall indent-to ind (min cbeg end))))
  17694. (when (< (point) end)
  17695. (cl-case type
  17696. ((example-block verse-block))
  17697. (src-block
  17698. ;; In a source block, indent source code
  17699. ;; according to language major mode, but only if
  17700. ;; `org-src-tab-acts-natively' is non-nil.
  17701. (when (and (< (point) end) org-src-tab-acts-natively)
  17702. (ignore-errors
  17703. (org-babel-do-in-edit-buffer
  17704. (indent-region (point-min) (point-max))))))
  17705. (t (org-indent-region (point) (min cend end))))
  17706. (goto-char (min cend end))
  17707. (when (< (point) end)
  17708. (funcall indent-to ind (min element-end end))))
  17709. (set-marker post nil)
  17710. (set-marker cbeg nil)
  17711. (set-marker cend nil))))
  17712. (set-marker element-end nil))))
  17713. (set-marker end nil))))
  17714. (defun org-indent-drawer ()
  17715. "Indent the drawer at point."
  17716. (interactive)
  17717. (unless (save-excursion
  17718. (beginning-of-line)
  17719. (looking-at-p org-drawer-regexp))
  17720. (user-error "Not at a drawer"))
  17721. (let ((element (org-element-at-point)))
  17722. (unless (memq (org-element-type element) '(drawer property-drawer))
  17723. (user-error "Not at a drawer"))
  17724. (org-with-wide-buffer
  17725. (org-indent-region (org-element-property :begin element)
  17726. (org-element-property :end element))))
  17727. (message "Drawer at point indented"))
  17728. (defun org-indent-block ()
  17729. "Indent the block at point."
  17730. (interactive)
  17731. (unless (save-excursion
  17732. (beginning-of-line)
  17733. (let ((case-fold-search t))
  17734. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17735. (user-error "Not at a block"))
  17736. (let ((element (org-element-at-point)))
  17737. (unless (memq (org-element-type element)
  17738. '(comment-block center-block dynamic-block example-block
  17739. export-block quote-block special-block
  17740. src-block verse-block))
  17741. (user-error "Not at a block"))
  17742. (org-with-wide-buffer
  17743. (org-indent-region (org-element-property :begin element)
  17744. (org-element-property :end element))))
  17745. (message "Block at point indented"))
  17746. ;;; Filling
  17747. ;; We use our own fill-paragraph and auto-fill functions.
  17748. ;; `org-fill-paragraph' relies on adaptive filling and context
  17749. ;; checking. Appropriate `fill-prefix' is computed with
  17750. ;; `org-adaptive-fill-function'.
  17751. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17752. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17753. ;; `org-adaptive-fill-function' value. Internally,
  17754. ;; `org-comment-line-break-function' breaks the line.
  17755. ;; `org-setup-filling' installs filling and auto-filling related
  17756. ;; variables during `org-mode' initialization.
  17757. (defun org-setup-filling ()
  17758. (require 'org-element)
  17759. ;; Prevent auto-fill from inserting unwanted new items.
  17760. (when (boundp 'fill-nobreak-predicate)
  17761. (setq-local
  17762. fill-nobreak-predicate
  17763. (org-uniquify
  17764. (append fill-nobreak-predicate
  17765. '(org-fill-line-break-nobreak-p
  17766. org-fill-n-macro-as-item-nobreak-p
  17767. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17768. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17769. (setq-local paragraph-start paragraph-ending)
  17770. (setq-local paragraph-separate paragraph-ending))
  17771. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17772. (setq-local auto-fill-inhibit-regexp nil)
  17773. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17774. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17775. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17776. (defun org-fill-line-break-nobreak-p ()
  17777. "Non-nil when a new line at point would create an Org line break."
  17778. (save-excursion
  17779. (skip-chars-backward " \t")
  17780. (skip-chars-backward "\\\\")
  17781. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17782. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17783. "Non-nil when a new line at point would split a timestamp."
  17784. (and (org-at-timestamp-p 'lax)
  17785. (not (looking-at org-ts-regexp-both))))
  17786. (defun org-fill-n-macro-as-item-nobreak-p ()
  17787. "Non-nil when a new line at point would create a new list."
  17788. ;; During export, a "n" macro followed by a dot or a closing
  17789. ;; parenthesis can end up being parsed as a new list item.
  17790. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17791. (defun org-adaptive-fill-function ()
  17792. "Compute a fill prefix for the current line.
  17793. Return fill prefix, as a string, or nil if current line isn't
  17794. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17795. matches in paragraphs or comments, use it."
  17796. (org-with-wide-buffer
  17797. (unless (org-at-heading-p)
  17798. (let* ((p (line-beginning-position))
  17799. (element (save-excursion
  17800. (beginning-of-line)
  17801. (org-element-at-point)))
  17802. (type (org-element-type element))
  17803. (post-affiliated (org-element-property :post-affiliated element)))
  17804. (unless (< p post-affiliated)
  17805. (cl-case type
  17806. (comment
  17807. (save-excursion
  17808. (beginning-of-line)
  17809. (looking-at "[ \t]*")
  17810. (concat (match-string 0) "# ")))
  17811. (footnote-definition "")
  17812. ((item plain-list)
  17813. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17814. (paragraph
  17815. ;; Fill prefix is usually the same as the current line,
  17816. ;; unless the paragraph is at the beginning of an item.
  17817. (let ((parent (org-element-property :parent element)))
  17818. (save-excursion
  17819. (beginning-of-line)
  17820. (cond ((eq (org-element-type parent) 'item)
  17821. (make-string (org-list-item-body-column
  17822. (org-element-property :begin parent))
  17823. ?\s))
  17824. ((and adaptive-fill-regexp
  17825. ;; Locally disable
  17826. ;; `adaptive-fill-function' to let
  17827. ;; `fill-context-prefix' handle
  17828. ;; `adaptive-fill-regexp' variable.
  17829. (let (adaptive-fill-function)
  17830. (fill-context-prefix
  17831. post-affiliated
  17832. (org-element-property :end element)))))
  17833. ((looking-at "[ \t]+") (match-string 0))
  17834. (t "")))))
  17835. (comment-block
  17836. ;; Only fill contents if P is within block boundaries.
  17837. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17838. (forward-line)
  17839. (point)))
  17840. (cend (save-excursion
  17841. (goto-char (org-element-property :end element))
  17842. (skip-chars-backward " \r\t\n")
  17843. (line-beginning-position))))
  17844. (when (and (>= p cbeg) (< p cend))
  17845. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17846. (match-string 0)
  17847. ""))))))))))
  17848. (defun org-fill-element (&optional justify)
  17849. "Fill element at point, when applicable.
  17850. This function only applies to comment blocks, comments, example
  17851. blocks and paragraphs. Also, as a special case, re-align table
  17852. when point is at one.
  17853. If JUSTIFY is non-nil (interactively, with prefix argument),
  17854. justify as well. If `sentence-end-double-space' is non-nil, then
  17855. period followed by one space does not end a sentence, so don't
  17856. break a line there. The variable `fill-column' controls the
  17857. width for filling.
  17858. For convenience, when point is at a plain list, an item or
  17859. a footnote definition, try to fill the first paragraph within."
  17860. (with-syntax-table org-mode-transpose-word-syntax-table
  17861. ;; Move to end of line in order to get the first paragraph within
  17862. ;; a plain list or a footnote definition.
  17863. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17864. ;; First check if point is in a blank line at the beginning of
  17865. ;; the buffer. In that case, ignore filling.
  17866. (cl-case (org-element-type element)
  17867. ;; Use major mode filling function is source blocks.
  17868. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  17869. ;; Align Org tables, leave table.el tables as-is.
  17870. (table-row (org-table-align) t)
  17871. (table
  17872. (when (eq (org-element-property :type element) 'org)
  17873. (save-excursion
  17874. (goto-char (org-element-property :post-affiliated element))
  17875. (org-table-align)))
  17876. t)
  17877. (paragraph
  17878. ;; Paragraphs may contain `line-break' type objects.
  17879. (let ((beg (max (point-min)
  17880. (org-element-property :contents-begin element)))
  17881. (end (min (point-max)
  17882. (org-element-property :contents-end element))))
  17883. ;; Do nothing if point is at an affiliated keyword.
  17884. (if (< (line-end-position) beg) t
  17885. ;; Fill paragraph, taking line breaks into account.
  17886. (save-excursion
  17887. (goto-char beg)
  17888. (let ((cuts (list beg)))
  17889. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17890. (when (eq 'line-break
  17891. (org-element-type
  17892. (save-excursion (backward-char)
  17893. (org-element-context))))
  17894. (push (point) cuts)))
  17895. (dolist (c (delq end cuts))
  17896. (fill-region-as-paragraph c end justify)
  17897. (setq end c))))
  17898. t)))
  17899. ;; Contents of `comment-block' type elements should be
  17900. ;; filled as plain text, but only if point is within block
  17901. ;; markers.
  17902. (comment-block
  17903. (let* ((case-fold-search t)
  17904. (beg (save-excursion
  17905. (goto-char (org-element-property :begin element))
  17906. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17907. (forward-line)
  17908. (point)))
  17909. (end (save-excursion
  17910. (goto-char (org-element-property :end element))
  17911. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17912. (line-beginning-position))))
  17913. (if (or (< (point) beg) (> (point) end)) t
  17914. (fill-region-as-paragraph
  17915. (save-excursion (end-of-line)
  17916. (re-search-backward "^[ \t]*$" beg 'move)
  17917. (line-beginning-position))
  17918. (save-excursion (beginning-of-line)
  17919. (re-search-forward "^[ \t]*$" end 'move)
  17920. (line-beginning-position))
  17921. justify))))
  17922. ;; Fill comments.
  17923. (comment
  17924. (let ((begin (org-element-property :post-affiliated element))
  17925. (end (org-element-property :end element)))
  17926. (when (and (>= (point) begin) (<= (point) end))
  17927. (let ((begin (save-excursion
  17928. (end-of-line)
  17929. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17930. (progn (forward-line) (point))
  17931. begin)))
  17932. (end (save-excursion
  17933. (end-of-line)
  17934. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17935. (1- (line-beginning-position))
  17936. (skip-chars-backward " \r\t\n")
  17937. (line-end-position)))))
  17938. ;; Do not fill comments when at a blank line.
  17939. (when (> end begin)
  17940. (let ((fill-prefix
  17941. (save-excursion
  17942. (beginning-of-line)
  17943. (looking-at "[ \t]*#")
  17944. (let ((comment-prefix (match-string 0)))
  17945. (goto-char (match-end 0))
  17946. (if (looking-at adaptive-fill-regexp)
  17947. (concat comment-prefix (match-string 0))
  17948. (concat comment-prefix " "))))))
  17949. (save-excursion
  17950. (fill-region-as-paragraph begin end justify))))))
  17951. t))
  17952. ;; Ignore every other element.
  17953. (otherwise t)))))
  17954. (defun org-fill-paragraph (&optional justify region)
  17955. "Fill element at point, when applicable.
  17956. This function only applies to comment blocks, comments, example
  17957. blocks and paragraphs. Also, as a special case, re-align table
  17958. when point is at one.
  17959. For convenience, when point is at a plain list, an item or
  17960. a footnote definition, try to fill the first paragraph within.
  17961. If JUSTIFY is non-nil (interactively, with prefix argument),
  17962. justify as well. If `sentence-end-double-space' is non-nil, then
  17963. period followed by one space does not end a sentence, so don't
  17964. break a line there. The variable `fill-column' controls the
  17965. width for filling.
  17966. The REGION argument is non-nil if called interactively; in that
  17967. case, if Transient Mark mode is enabled and the mark is active,
  17968. fill each of the elements in the active region, instead of just
  17969. filling the current element."
  17970. (interactive (progn
  17971. (barf-if-buffer-read-only)
  17972. (list (when current-prefix-arg 'full) t)))
  17973. (let ((hash (and (not (buffer-modified-p))
  17974. (org-buffer-hash))))
  17975. (cond
  17976. ((and region transient-mark-mode mark-active
  17977. (not (eq (region-beginning) (region-end))))
  17978. (let ((origin (point-marker))
  17979. (start (region-beginning)))
  17980. (unwind-protect
  17981. (progn
  17982. (goto-char (region-end))
  17983. (while (> (point) start)
  17984. (org-backward-paragraph)
  17985. (org-fill-element justify)))
  17986. (goto-char origin)
  17987. (set-marker origin nil))))
  17988. (t (org-fill-element justify)))
  17989. ;; If we didn't change anything in the buffer (and the buffer was
  17990. ;; previously unmodified), then flip the modification status back
  17991. ;; to "unchanged".
  17992. (when (and hash (equal hash (org-buffer-hash)))
  17993. (set-buffer-modified-p nil))))
  17994. (defun org-auto-fill-function ()
  17995. "Auto-fill function."
  17996. ;; Check if auto-filling is meaningful.
  17997. (let ((fc (current-fill-column)))
  17998. (when (and fc (> (current-column) fc))
  17999. (let* ((fill-prefix (org-adaptive-fill-function))
  18000. ;; Enforce empty fill prefix, if required. Otherwise, it
  18001. ;; will be computed again.
  18002. (adaptive-fill-mode (not (equal fill-prefix ""))))
  18003. (when fill-prefix (do-auto-fill))))))
  18004. (defun org-comment-line-break-function (&optional soft)
  18005. "Break line at point and indent, continuing comment if within one.
  18006. The inserted newline is marked hard if variable
  18007. `use-hard-newlines' is true, unless optional argument SOFT is
  18008. non-nil."
  18009. (if soft (insert-and-inherit ?\n) (newline 1))
  18010. (save-excursion (forward-char -1) (delete-horizontal-space))
  18011. (delete-horizontal-space)
  18012. (indent-to-left-margin)
  18013. (insert-before-markers-and-inherit fill-prefix))
  18014. ;;; Fixed Width Areas
  18015. (defun org-toggle-fixed-width ()
  18016. "Toggle fixed-width markup.
  18017. Add or remove fixed-width markup on current line, whenever it
  18018. makes sense. Return an error otherwise.
  18019. If a region is active and if it contains only fixed-width areas
  18020. or blank lines, remove all fixed-width markup in it. If the
  18021. region contains anything else, convert all non-fixed-width lines
  18022. to fixed-width ones.
  18023. Blank lines at the end of the region are ignored unless the
  18024. region only contains such lines."
  18025. (interactive)
  18026. (if (not (org-region-active-p))
  18027. ;; No region:
  18028. ;;
  18029. ;; Remove fixed width marker only in a fixed-with element.
  18030. ;;
  18031. ;; Add fixed width maker in paragraphs, in blank lines after
  18032. ;; elements or at the beginning of a headline or an inlinetask,
  18033. ;; and before any one-line elements (e.g., a clock).
  18034. (progn
  18035. (beginning-of-line)
  18036. (let* ((element (org-element-at-point))
  18037. (type (org-element-type element)))
  18038. (cond
  18039. ((and (eq type 'fixed-width)
  18040. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  18041. (replace-match
  18042. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  18043. ((and (memq type '(babel-call clock comment diary-sexp headline
  18044. horizontal-rule keyword paragraph
  18045. planning))
  18046. (<= (org-element-property :post-affiliated element) (point)))
  18047. (skip-chars-forward " \t")
  18048. (insert ": "))
  18049. ((and (looking-at-p "[ \t]*$")
  18050. (or (eq type 'inlinetask)
  18051. (save-excursion
  18052. (skip-chars-forward " \r\t\n")
  18053. (<= (org-element-property :end element) (point)))))
  18054. (delete-region (point) (line-end-position))
  18055. (org-indent-line)
  18056. (insert ": "))
  18057. (t (user-error "Cannot insert a fixed-width line here")))))
  18058. ;; Region active.
  18059. (let* ((begin (save-excursion
  18060. (goto-char (region-beginning))
  18061. (line-beginning-position)))
  18062. (end (copy-marker
  18063. (save-excursion
  18064. (goto-char (region-end))
  18065. (unless (eolp) (beginning-of-line))
  18066. (if (save-excursion (re-search-backward "\\S-" begin t))
  18067. (progn (skip-chars-backward " \r\t\n") (point))
  18068. (point)))))
  18069. (all-fixed-width-p
  18070. (catch 'not-all-p
  18071. (save-excursion
  18072. (goto-char begin)
  18073. (skip-chars-forward " \r\t\n")
  18074. (when (eobp) (throw 'not-all-p nil))
  18075. (while (< (point) end)
  18076. (let ((element (org-element-at-point)))
  18077. (if (eq (org-element-type element) 'fixed-width)
  18078. (goto-char (org-element-property :end element))
  18079. (throw 'not-all-p nil))))
  18080. t))))
  18081. (if all-fixed-width-p
  18082. (save-excursion
  18083. (goto-char begin)
  18084. (while (< (point) end)
  18085. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  18086. (replace-match
  18087. "" nil nil nil
  18088. (if (= (line-end-position) (match-end 0)) 0 1)))
  18089. (forward-line)))
  18090. (let ((min-ind (point-max)))
  18091. ;; Find minimum indentation across all lines.
  18092. (save-excursion
  18093. (goto-char begin)
  18094. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  18095. (setq min-ind 0)
  18096. (catch 'zerop
  18097. (while (< (point) end)
  18098. (unless (looking-at-p "[ \t]*$")
  18099. (let ((ind (current-indentation)))
  18100. (setq min-ind (min min-ind ind))
  18101. (when (zerop ind) (throw 'zerop t))))
  18102. (forward-line)))))
  18103. ;; Loop over all lines and add fixed-width markup everywhere
  18104. ;; but in fixed-width lines.
  18105. (save-excursion
  18106. (goto-char begin)
  18107. (while (< (point) end)
  18108. (cond
  18109. ((org-at-heading-p)
  18110. (insert ": ")
  18111. (forward-line)
  18112. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  18113. (insert ":")
  18114. (forward-line)))
  18115. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  18116. (let* ((element (org-element-at-point))
  18117. (element-end (org-element-property :end element)))
  18118. (if (eq (org-element-type element) 'fixed-width)
  18119. (progn (goto-char element-end)
  18120. (skip-chars-backward " \r\t\n")
  18121. (forward-line))
  18122. (let ((limit (min end element-end)))
  18123. (while (< (point) limit)
  18124. (org-move-to-column min-ind t)
  18125. (insert ": ")
  18126. (forward-line))))))
  18127. (t
  18128. (org-move-to-column min-ind t)
  18129. (insert ": ")
  18130. (forward-line)))))))
  18131. (set-marker end nil))))
  18132. ;;; Blocks
  18133. (defun org-block-map (function &optional start end)
  18134. "Call FUNCTION at the head of all source blocks in the current buffer.
  18135. Optional arguments START and END can be used to limit the range."
  18136. (let ((start (or start (point-min)))
  18137. (end (or end (point-max))))
  18138. (save-excursion
  18139. (goto-char start)
  18140. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  18141. (save-excursion
  18142. (save-match-data
  18143. (goto-char (match-beginning 0))
  18144. (funcall function)))))))
  18145. (defun org-next-block (arg &optional backward block-regexp)
  18146. "Jump to the next block.
  18147. With a prefix argument ARG, jump forward ARG many blocks.
  18148. When BACKWARD is non-nil, jump to the previous block.
  18149. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  18150. Match data is set according to this regexp when the function
  18151. returns.
  18152. Return point at beginning of the opening line of found block.
  18153. Throw an error if no block is found."
  18154. (interactive "p")
  18155. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  18156. (case-fold-search t)
  18157. (search-fn (if backward #'re-search-backward #'re-search-forward))
  18158. (count (or arg 1))
  18159. (origin (point))
  18160. last-element)
  18161. (if backward (beginning-of-line) (end-of-line))
  18162. (while (and (> count 0) (funcall search-fn re nil t))
  18163. (let ((element (save-excursion
  18164. (goto-char (match-beginning 0))
  18165. (save-match-data (org-element-at-point)))))
  18166. (when (and (memq (org-element-type element)
  18167. '(center-block comment-block dynamic-block
  18168. example-block export-block quote-block
  18169. special-block src-block verse-block))
  18170. (<= (match-beginning 0)
  18171. (org-element-property :post-affiliated element)))
  18172. (setq last-element element)
  18173. (cl-decf count))))
  18174. (if (= count 0)
  18175. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  18176. (save-match-data (org-show-context)))
  18177. (goto-char origin)
  18178. (user-error "No %s code blocks" (if backward "previous" "further")))))
  18179. (defun org-previous-block (arg &optional block-regexp)
  18180. "Jump to the previous block.
  18181. With a prefix argument ARG, jump backward ARG many source blocks.
  18182. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  18183. (interactive "p")
  18184. (org-next-block arg t block-regexp))
  18185. ;;; Comments
  18186. ;; Org comments syntax is quite complex. It requires the entire line
  18187. ;; to be just a comment. Also, even with the right syntax at the
  18188. ;; beginning of line, some elements (e.g., verse-block or
  18189. ;; example-block) don't accept comments. Usual Emacs comment commands
  18190. ;; cannot cope with those requirements. Therefore, Org replaces them.
  18191. ;; Org still relies on `comment-dwim', but cannot trust
  18192. ;; `comment-only-p'. So, `comment-region-function' and
  18193. ;; `uncomment-region-function' both point
  18194. ;; to`org-comment-or-uncomment-region'. Eventually,
  18195. ;; `org-insert-comment' takes care of insertion of comments at the
  18196. ;; beginning of line.
  18197. ;; `org-setup-comments-handling' install comments related variables
  18198. ;; during `org-mode' initialization.
  18199. (defun org-setup-comments-handling ()
  18200. (interactive)
  18201. (setq-local comment-use-syntax nil)
  18202. (setq-local comment-start "# ")
  18203. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  18204. (setq-local comment-insert-comment-function 'org-insert-comment)
  18205. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  18206. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  18207. (defun org-insert-comment ()
  18208. "Insert an empty comment above current line.
  18209. If the line is empty, insert comment at its beginning. When
  18210. point is within a source block, comment according to the related
  18211. major mode."
  18212. (if (let ((element (org-element-at-point)))
  18213. (and (eq (org-element-type element) 'src-block)
  18214. (< (save-excursion
  18215. (goto-char (org-element-property :post-affiliated element))
  18216. (line-end-position))
  18217. (point))
  18218. (> (save-excursion
  18219. (goto-char (org-element-property :end element))
  18220. (skip-chars-backward " \r\t\n")
  18221. (line-beginning-position))
  18222. (point))))
  18223. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  18224. (beginning-of-line)
  18225. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  18226. (open-line 1))
  18227. (org-indent-line)
  18228. (insert "# ")))
  18229. (defvar comment-empty-lines) ; From newcomment.el.
  18230. (defun org-comment-or-uncomment-region (beg end &rest _)
  18231. "Comment or uncomment each non-blank line in the region.
  18232. Uncomment each non-blank line between BEG and END if it only
  18233. contains commented lines. Otherwise, comment them. If region is
  18234. strictly within a source block, use appropriate comment syntax."
  18235. (if (let ((element (org-element-at-point)))
  18236. (and (eq (org-element-type element) 'src-block)
  18237. (< (save-excursion
  18238. (goto-char (org-element-property :post-affiliated element))
  18239. (line-end-position))
  18240. beg)
  18241. (>= (save-excursion
  18242. (goto-char (org-element-property :end element))
  18243. (skip-chars-backward " \r\t\n")
  18244. (line-beginning-position))
  18245. end)))
  18246. ;; Translate region boundaries for the Org buffer to the source
  18247. ;; buffer.
  18248. (let ((offset (- end beg)))
  18249. (save-excursion
  18250. (goto-char beg)
  18251. (org-babel-do-in-edit-buffer
  18252. (comment-or-uncomment-region (point) (+ offset (point))))))
  18253. (save-restriction
  18254. ;; Restrict region
  18255. (narrow-to-region (save-excursion (goto-char beg)
  18256. (skip-chars-forward " \r\t\n" end)
  18257. (line-beginning-position))
  18258. (save-excursion (goto-char end)
  18259. (skip-chars-backward " \r\t\n" beg)
  18260. (line-end-position)))
  18261. (let ((uncommentp
  18262. ;; UNCOMMENTP is non-nil when every non blank line between
  18263. ;; BEG and END is a comment.
  18264. (save-excursion
  18265. (goto-char (point-min))
  18266. (while (and (not (eobp))
  18267. (let ((element (org-element-at-point)))
  18268. (and (eq (org-element-type element) 'comment)
  18269. (goto-char (min (point-max)
  18270. (org-element-property
  18271. :end element)))))))
  18272. (eobp))))
  18273. (if uncommentp
  18274. ;; Only blank lines and comments in region: uncomment it.
  18275. (save-excursion
  18276. (goto-char (point-min))
  18277. (while (not (eobp))
  18278. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  18279. (replace-match "" nil nil nil 1))
  18280. (forward-line)))
  18281. ;; Comment each line in region.
  18282. (let ((min-indent (point-max)))
  18283. ;; First find the minimum indentation across all lines.
  18284. (save-excursion
  18285. (goto-char (point-min))
  18286. (while (and (not (eobp)) (not (zerop min-indent)))
  18287. (unless (looking-at "[ \t]*$")
  18288. (setq min-indent (min min-indent (current-indentation))))
  18289. (forward-line)))
  18290. ;; Then loop over all lines.
  18291. (save-excursion
  18292. (goto-char (point-min))
  18293. (while (not (eobp))
  18294. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18295. ;; Don't get fooled by invisible text (e.g. link path)
  18296. ;; when moving to column MIN-INDENT.
  18297. (let ((buffer-invisibility-spec nil))
  18298. (org-move-to-column min-indent t))
  18299. (insert comment-start))
  18300. (forward-line)))))))))
  18301. (defun org-comment-dwim (_arg)
  18302. "Call the comment command you mean.
  18303. Call `org-toggle-comment' if on a heading, otherwise call
  18304. `comment-dwim', within a source edit buffer if needed."
  18305. (interactive "*P")
  18306. (cond ((org-at-heading-p)
  18307. (call-interactively #'org-toggle-comment))
  18308. ((org-in-src-block-p)
  18309. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18310. (t (call-interactively #'comment-dwim))))
  18311. ;;; Timestamps API
  18312. ;; This section contains tools to operate on, or create, timestamp
  18313. ;; objects, as returned by, e.g. `org-element-context'.
  18314. (defun org-timestamp-from-string (s)
  18315. "Convert Org timestamp S, as a string, into a timestamp object.
  18316. Return nil if S is not a valid timestamp string."
  18317. (when (org-string-nw-p s)
  18318. (with-temp-buffer
  18319. (save-excursion (insert s))
  18320. (org-element-timestamp-parser))))
  18321. (defun org-timestamp-from-time (time &optional with-time inactive)
  18322. "Convert a time value into a timestamp object.
  18323. TIME is an Emacs internal time representation, as returned, e.g.,
  18324. by `current-time'.
  18325. When optional argument WITH-TIME is non-nil, return a timestamp
  18326. object with a time part, i.e., with hours and minutes.
  18327. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18328. return an active timestamp."
  18329. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18330. (org-element-create 'timestamp
  18331. (list :type (if inactive 'inactive 'active)
  18332. :year-start year
  18333. :month-start month
  18334. :day-start day
  18335. :hour-start (and with-time hour)
  18336. :minute-start (and with-time minute)))))
  18337. (defun org-timestamp-to-time (timestamp &optional end)
  18338. "Convert TIMESTAMP object into an Emacs internal time value.
  18339. Use end of date range or time range when END is non-nil.
  18340. Otherwise, use its start."
  18341. (apply #'encode-time
  18342. (cons 0
  18343. (mapcar
  18344. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18345. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18346. '(:minute-start :hour-start :day-start :month-start
  18347. :year-start))))))
  18348. (defun org-timestamp-has-time-p (timestamp)
  18349. "Non-nil when TIMESTAMP has a time specified."
  18350. (org-element-property :hour-start timestamp))
  18351. (defun org-timestamp-format (timestamp format &optional end utc)
  18352. "Format a TIMESTAMP object into a string.
  18353. FORMAT is a format specifier to be passed to
  18354. `format-time-string'.
  18355. When optional argument END is non-nil, use end of date-range or
  18356. time-range, if possible.
  18357. When optional argument UTC is non-nil, time is be expressed as
  18358. Universal Time."
  18359. (format-time-string format (org-timestamp-to-time timestamp end)
  18360. (and utc t)))
  18361. (defun org-timestamp-split-range (timestamp &optional end)
  18362. "Extract a TIMESTAMP object from a date or time range.
  18363. END, when non-nil, means extract the end of the range.
  18364. Otherwise, extract its start.
  18365. Return a new timestamp object."
  18366. (let ((type (org-element-property :type timestamp)))
  18367. (if (memq type '(active inactive diary)) timestamp
  18368. (let ((split-ts (org-element-copy timestamp)))
  18369. ;; Set new type.
  18370. (org-element-put-property
  18371. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18372. ;; Copy start properties over end properties if END is
  18373. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18374. (let ((p-alist '((:minute-start . :minute-end)
  18375. (:hour-start . :hour-end)
  18376. (:day-start . :day-end)
  18377. (:month-start . :month-end)
  18378. (:year-start . :year-end))))
  18379. (dolist (p-cell p-alist)
  18380. (org-element-put-property
  18381. split-ts
  18382. (funcall (if end #'car #'cdr) p-cell)
  18383. (org-element-property
  18384. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18385. ;; Eventually refresh `:raw-value'.
  18386. (org-element-put-property split-ts :raw-value nil)
  18387. (org-element-put-property
  18388. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18389. (defun org-timestamp-translate (timestamp &optional boundary)
  18390. "Translate TIMESTAMP object to custom format.
  18391. Format string is defined in `org-time-stamp-custom-formats',
  18392. which see.
  18393. When optional argument BOUNDARY is non-nil, it is either the
  18394. symbol `start' or `end'. In this case, only translate the
  18395. starting or ending part of TIMESTAMP if it is a date or time
  18396. range. Otherwise, translate both parts.
  18397. Return timestamp as-is if `org-display-custom-times' is nil or if
  18398. it has a `diary' type."
  18399. (let ((type (org-element-property :type timestamp)))
  18400. (if (or (not org-display-custom-times) (eq type 'diary))
  18401. (org-element-interpret-data timestamp)
  18402. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18403. org-time-stamp-custom-formats)))
  18404. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18405. (concat (org-timestamp-format timestamp fmt)
  18406. "--"
  18407. (org-timestamp-format timestamp fmt t))
  18408. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18409. ;;; Other stuff
  18410. (defvar reftex-docstruct-symbol)
  18411. (defvar org--rds)
  18412. (defun org-reftex-citation ()
  18413. "Use reftex-citation to insert a citation into the buffer.
  18414. This looks for a line like
  18415. #+BIBLIOGRAPHY: foo plain option:-d
  18416. and derives from it that foo.bib is the bibliography file relevant
  18417. for this document. It then installs the necessary environment for RefTeX
  18418. to work in this buffer and calls `reftex-citation' to insert a citation
  18419. into the buffer.
  18420. Export of such citations to both LaTeX and HTML is handled by the contributed
  18421. package ox-bibtex by Taru Karttunen."
  18422. (interactive)
  18423. (let ((reftex-docstruct-symbol 'org--rds)
  18424. org--rds bib)
  18425. (org-with-wide-buffer
  18426. (let ((case-fold-search t)
  18427. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18428. (if (not (save-excursion
  18429. (or (re-search-forward re nil t)
  18430. (re-search-backward re nil t))))
  18431. (user-error "No bibliography defined in file")
  18432. (setq bib (concat (match-string 1) ".bib")
  18433. org--rds (list (list 'bib bib))))))
  18434. (call-interactively 'reftex-citation)))
  18435. ;;;; Functions extending outline functionality
  18436. (defun org-beginning-of-line (&optional n)
  18437. "Go to the beginning of the current visible line.
  18438. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18439. symbol `reversed', on the first attempt move to where the
  18440. headline text starts, and only move to beginning of line when the
  18441. cursor is already before the start of the text of the headline.
  18442. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18443. start of the text on the second attempt.
  18444. With argument N not nil or 1, move forward N - 1 lines first."
  18445. (interactive "^p")
  18446. (let ((origin (point))
  18447. (special (pcase org-special-ctrl-a/e
  18448. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18449. deactivate-mark)
  18450. ;; First move to a visible line.
  18451. (if (bound-and-true-p visual-line-mode)
  18452. (beginning-of-visual-line n)
  18453. (move-beginning-of-line n)
  18454. ;; `move-beginning-of-line' may leave point after invisible
  18455. ;; characters if line starts with such of these (e.g., with
  18456. ;; a link at column 0). Really move to the beginning of the
  18457. ;; current visible line.
  18458. (beginning-of-line))
  18459. (cond
  18460. ;; No special behavior. Point is already at the beginning of
  18461. ;; a line, logical or visual.
  18462. ((not special))
  18463. ;; `beginning-of-visual-line' left point before logical beginning
  18464. ;; of line: point is at the beginning of a visual line. Bail
  18465. ;; out.
  18466. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18467. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18468. ;; At a headline, special position is before the title, but
  18469. ;; after any TODO keyword or priority cookie.
  18470. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18471. (line-end-position)))
  18472. (bol (point)))
  18473. (if (eq special 'reversed)
  18474. (when (and (= origin bol) (eq last-command this-command))
  18475. (goto-char refpos))
  18476. (when (or (> origin refpos) (= origin bol))
  18477. (goto-char refpos)))))
  18478. ((and (looking-at org-list-full-item-re)
  18479. (memq (org-element-type (save-match-data (org-element-at-point)))
  18480. '(item plain-list)))
  18481. ;; Set special position at first white space character after
  18482. ;; bullet, and check-box, if any.
  18483. (let ((after-bullet
  18484. (let ((box (match-end 3)))
  18485. (cond ((not box) (match-end 1))
  18486. ((eq (char-after box) ?\s) (1+ box))
  18487. (t box)))))
  18488. (if (eq special 'reversed)
  18489. (when (and (= (point) origin) (eq last-command this-command))
  18490. (goto-char after-bullet))
  18491. (when (or (> origin after-bullet) (= (point) origin))
  18492. (goto-char after-bullet)))))
  18493. ;; No special context. Point is already at beginning of line.
  18494. (t nil))))
  18495. (defun org-end-of-line (&optional n)
  18496. "Go to the end of the line, but before ellipsis, if any.
  18497. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18498. symbol `reversed', ignore tags on the first attempt, and only
  18499. move to after the tags when the cursor is already beyond the end
  18500. of the headline.
  18501. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18502. on the second attempt.
  18503. With argument N not nil or 1, move forward N - 1 lines first."
  18504. (interactive "^p")
  18505. (let ((origin (point))
  18506. (special (pcase org-special-ctrl-a/e
  18507. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18508. deactivate-mark)
  18509. ;; First move to a visible line.
  18510. (if (bound-and-true-p visual-line-mode)
  18511. (beginning-of-visual-line n)
  18512. (move-beginning-of-line n))
  18513. (cond
  18514. ;; At a headline, with tags.
  18515. ((and special
  18516. (save-excursion
  18517. (beginning-of-line)
  18518. (let ((case-fold-search nil))
  18519. (looking-at org-complex-heading-regexp)))
  18520. (match-end 5))
  18521. (let ((tags (save-excursion
  18522. (goto-char (match-beginning 5))
  18523. (skip-chars-backward " \t")
  18524. (point)))
  18525. (visual-end (and (bound-and-true-p visual-line-mode)
  18526. (save-excursion
  18527. (end-of-visual-line)
  18528. (point)))))
  18529. ;; If `end-of-visual-line' brings us before end of line or
  18530. ;; even tags, i.e., the headline spans over multiple visual
  18531. ;; lines, move there.
  18532. (cond ((and visual-end
  18533. (< visual-end tags)
  18534. (<= origin visual-end))
  18535. (goto-char visual-end))
  18536. ((eq special 'reversed)
  18537. (if (and (= origin (line-end-position))
  18538. (eq this-command last-command))
  18539. (goto-char tags)
  18540. (end-of-line)))
  18541. (t
  18542. (if (or (< origin tags) (= origin (line-end-position)))
  18543. (goto-char tags)
  18544. (end-of-line))))))
  18545. ((bound-and-true-p visual-line-mode)
  18546. (let ((bol (line-beginning-position)))
  18547. (end-of-visual-line)
  18548. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18549. ;; end of a line, backtrack and use `end-of-line' instead.
  18550. (when (/= bol (line-beginning-position))
  18551. (goto-char bol)
  18552. (end-of-line))))
  18553. (t (end-of-line)))))
  18554. (defun org-backward-sentence (&optional _arg)
  18555. "Go to beginning of sentence, or beginning of table field.
  18556. This will call `backward-sentence' or `org-table-beginning-of-field',
  18557. depending on context."
  18558. (interactive)
  18559. (let* ((element (org-element-at-point))
  18560. (contents-begin (org-element-property :contents-begin element))
  18561. (table (org-element-lineage element '(table) t)))
  18562. (if (and table
  18563. (> (point) contents-begin)
  18564. (<= (point) (org-element-property :contents-end table)))
  18565. (call-interactively #'org-table-beginning-of-field)
  18566. (save-restriction
  18567. (when (and contents-begin
  18568. (< (point-min) contents-begin)
  18569. (> (point) contents-begin))
  18570. (narrow-to-region contents-begin
  18571. (org-element-property :contents-end element)))
  18572. (call-interactively #'backward-sentence)))))
  18573. (defun org-forward-sentence (&optional _arg)
  18574. "Go to end of sentence, or end of table field.
  18575. This will call `forward-sentence' or `org-table-end-of-field',
  18576. depending on context."
  18577. (interactive)
  18578. (if (and (org-at-heading-p)
  18579. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18580. (save-restriction
  18581. (narrow-to-region (line-beginning-position) (line-end-position))
  18582. (call-interactively #'forward-sentence))
  18583. (let* ((element (org-element-at-point))
  18584. (contents-end (org-element-property :contents-end element))
  18585. (table (org-element-lineage element '(table) t)))
  18586. (if (and table
  18587. (>= (point) (org-element-property :contents-begin table))
  18588. (< (point) contents-end))
  18589. (call-interactively #'org-table-end-of-field)
  18590. (save-restriction
  18591. (when (and contents-end
  18592. (> (point-max) contents-end)
  18593. ;; Skip blank lines between elements.
  18594. (< (org-element-property :end element)
  18595. (save-excursion (goto-char contents-end)
  18596. (skip-chars-forward " \r\t\n"))))
  18597. (narrow-to-region (org-element-property :contents-begin element)
  18598. contents-end))
  18599. ;; End of heading is considered as the end of a sentence.
  18600. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18601. (call-interactively #'forward-sentence)))))))
  18602. (defun org-kill-line (&optional _arg)
  18603. "Kill line, to tags or end of line."
  18604. (interactive)
  18605. (cond
  18606. ((or (not org-special-ctrl-k)
  18607. (bolp)
  18608. (not (org-at-heading-p)))
  18609. (when (and (get-char-property (line-end-position) 'invisible)
  18610. org-ctrl-k-protect-subtree
  18611. (or (eq org-ctrl-k-protect-subtree 'error)
  18612. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18613. (user-error
  18614. (substitute-command-keys
  18615. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18616. (call-interactively
  18617. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18618. ((org-match-line org-tag-line-re)
  18619. (let ((end (save-excursion
  18620. (goto-char (match-beginning 1))
  18621. (skip-chars-backward " \t")
  18622. (point))))
  18623. (if (<= end (point)) ;on tags part
  18624. (kill-region (point) (line-end-position))
  18625. (kill-region (point) end)))
  18626. (org-align-tags))
  18627. (t (kill-region (point) (line-end-position)))))
  18628. (defun org-yank (&optional arg)
  18629. "Yank. If the kill is a subtree, treat it specially.
  18630. This command will look at the current kill and check if is a single
  18631. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18632. cursor is at the beginning of a line or after the stars of a currently
  18633. empty headline, then the yank is handled specially. How exactly depends
  18634. on the value of the following variables.
  18635. `org-yank-folded-subtrees'
  18636. By default, this variable is non-nil, which results in
  18637. subtree(s) being folded after insertion, except if doing so
  18638. would swallow text after the yanked text.
  18639. `org-yank-adjusted-subtrees'
  18640. When non-nil (the default value is nil), the subtree will be
  18641. promoted or demoted in order to fit into the local outline tree
  18642. structure, which means that the level will be adjusted so that it
  18643. becomes the smaller one of the two *visible* surrounding headings.
  18644. Any prefix to this command will cause `yank' to be called directly with
  18645. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18646. will just
  18647. plainly yank the text as it is.
  18648. \[1] The test checks if the first non-white line is a heading
  18649. and if there are no other headings with fewer stars."
  18650. (interactive "P")
  18651. (org-yank-generic 'yank arg))
  18652. (defun org-yank-generic (command arg)
  18653. "Perform some yank-like command.
  18654. This function implements the behavior described in the `org-yank'
  18655. documentation. However, it has been generalized to work for any
  18656. interactive command with similar behavior."
  18657. ;; pretend to be command COMMAND
  18658. (setq this-command command)
  18659. (if arg
  18660. (call-interactively command)
  18661. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18662. (and (org-kill-is-subtree-p)
  18663. (or (bolp)
  18664. (and (looking-at "[ \t]*$")
  18665. (string-match
  18666. "\\`\\*+\\'"
  18667. (buffer-substring (point-at-bol) (point)))))))
  18668. swallowp)
  18669. (cond
  18670. ((and subtreep org-yank-folded-subtrees)
  18671. (let ((beg (point))
  18672. end)
  18673. (if (and subtreep org-yank-adjusted-subtrees)
  18674. (org-paste-subtree nil nil 'for-yank)
  18675. (call-interactively command))
  18676. (setq end (point))
  18677. (goto-char beg)
  18678. (when (and (bolp) subtreep
  18679. (not (setq swallowp
  18680. (org-yank-folding-would-swallow-text beg end))))
  18681. (org-with-limited-levels
  18682. (or (looking-at org-outline-regexp)
  18683. (re-search-forward org-outline-regexp-bol end t))
  18684. (while (and (< (point) end) (looking-at org-outline-regexp))
  18685. (org-flag-subtree t)
  18686. (org-cycle-show-empty-lines 'folded)
  18687. (condition-case nil
  18688. (outline-forward-same-level 1)
  18689. (error (goto-char end))))))
  18690. (when swallowp
  18691. (message
  18692. "Inserted text not folded because that would swallow text"))
  18693. (goto-char end)
  18694. (skip-chars-forward " \t\n\r")
  18695. (beginning-of-line 1)
  18696. (push-mark beg 'nomsg)))
  18697. ((and subtreep org-yank-adjusted-subtrees)
  18698. (let ((beg (point-at-bol)))
  18699. (org-paste-subtree nil nil 'for-yank)
  18700. (push-mark beg 'nomsg)))
  18701. (t
  18702. (call-interactively command))))))
  18703. (defun org-yank-folding-would-swallow-text (beg end)
  18704. "Would hide-subtree at BEG swallow any text after END?"
  18705. (let (level)
  18706. (org-with-limited-levels
  18707. (save-excursion
  18708. (goto-char beg)
  18709. (when (or (looking-at org-outline-regexp)
  18710. (re-search-forward org-outline-regexp-bol end t))
  18711. (setq level (org-outline-level)))
  18712. (goto-char end)
  18713. (skip-chars-forward " \t\r\n\v\f")
  18714. (not (or (eobp)
  18715. (and (bolp) (looking-at-p org-outline-regexp)
  18716. (<= (org-outline-level) level))))))))
  18717. (defun org-back-to-heading (&optional invisible-ok)
  18718. "Call `outline-back-to-heading', but provide a better error message."
  18719. (condition-case nil
  18720. (outline-back-to-heading invisible-ok)
  18721. (error (error "Before first headline at position %d in buffer %s"
  18722. (point) (current-buffer)))))
  18723. (defun org-before-first-heading-p ()
  18724. "Before first heading?"
  18725. (org-with-limited-levels
  18726. (save-excursion
  18727. (end-of-line)
  18728. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18729. (defun org-at-heading-p (&optional _)
  18730. "Non-nil when on a headline."
  18731. (outline-on-heading-p t))
  18732. (defun org-in-commented-heading-p (&optional no-inheritance)
  18733. "Non-nil if point is under a commented heading.
  18734. This function also checks ancestors of the current headline,
  18735. unless optional argument NO-INHERITANCE is non-nil."
  18736. (cond
  18737. ((org-before-first-heading-p) nil)
  18738. ((let ((headline (nth 4 (org-heading-components))))
  18739. (and headline
  18740. (let ((case-fold-search nil))
  18741. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18742. headline)))))
  18743. (no-inheritance nil)
  18744. (t
  18745. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18746. (defun org-at-comment-p nil
  18747. "Is cursor in a commented line?"
  18748. (save-excursion
  18749. (save-match-data
  18750. (beginning-of-line)
  18751. (looking-at "^[ \t]*# "))))
  18752. (defun org-at-drawer-p nil
  18753. "Is cursor at a drawer keyword?"
  18754. (save-excursion
  18755. (move-beginning-of-line 1)
  18756. (looking-at org-drawer-regexp)))
  18757. (defun org-at-block-p nil
  18758. "Is cursor at a block keyword?"
  18759. (save-excursion
  18760. (move-beginning-of-line 1)
  18761. (looking-at org-block-regexp)))
  18762. (defun org-point-at-end-of-empty-headline ()
  18763. "If point is at the end of an empty headline, return t, else nil.
  18764. If the heading only contains a TODO keyword, it is still still considered
  18765. empty."
  18766. (let ((case-fold-search nil))
  18767. (and (looking-at "[ \t]*$")
  18768. org-todo-line-regexp
  18769. (save-excursion
  18770. (beginning-of-line)
  18771. (looking-at org-todo-line-regexp)
  18772. (string= (match-string 3) "")))))
  18773. (defun org-at-heading-or-item-p ()
  18774. (or (org-at-heading-p) (org-at-item-p)))
  18775. (defun org-up-heading-all (arg)
  18776. "Move to the heading line of which the present line is a subheading.
  18777. This function considers both visible and invisible heading lines.
  18778. With argument, move up ARG levels."
  18779. (outline-up-heading arg t))
  18780. (defun org-up-heading-safe ()
  18781. "Move to the heading line of which the present line is a subheading.
  18782. This version will not throw an error. It will return the level of the
  18783. headline found, or nil if no higher level is found.
  18784. Also, this function will be a lot faster than `outline-up-heading',
  18785. because it relies on stars being the outline starters. This can really
  18786. make a significant difference in outlines with very many siblings."
  18787. (when (ignore-errors (org-back-to-heading t))
  18788. (let ((level-up (1- (funcall outline-level))))
  18789. (and (> level-up 0)
  18790. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  18791. (funcall outline-level)))))
  18792. (defun org-first-sibling-p ()
  18793. "Is this heading the first child of its parents?"
  18794. (interactive)
  18795. (let ((re org-outline-regexp-bol)
  18796. level l)
  18797. (unless (org-at-heading-p t)
  18798. (user-error "Not at a heading"))
  18799. (setq level (funcall outline-level))
  18800. (save-excursion
  18801. (if (not (re-search-backward re nil t))
  18802. t
  18803. (setq l (funcall outline-level))
  18804. (< l level)))))
  18805. (defun org-goto-sibling (&optional previous)
  18806. "Goto the next sibling, even if it is invisible.
  18807. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18808. when a sibling was found. When none is found, return nil and don't
  18809. move point."
  18810. (let ((fun (if previous 're-search-backward 're-search-forward))
  18811. (pos (point))
  18812. (re org-outline-regexp-bol)
  18813. level l)
  18814. (when (ignore-errors (org-back-to-heading t))
  18815. (setq level (funcall outline-level))
  18816. (catch 'exit
  18817. (or previous (forward-char 1))
  18818. (while (funcall fun re nil t)
  18819. (setq l (funcall outline-level))
  18820. (when (< l level) (goto-char pos) (throw 'exit nil))
  18821. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18822. (goto-char pos)
  18823. nil))))
  18824. (defun org-show-siblings ()
  18825. "Show all siblings of the current headline."
  18826. (save-excursion
  18827. (while (org-goto-sibling) (org-flag-heading nil)))
  18828. (save-excursion
  18829. (while (org-goto-sibling 'previous)
  18830. (org-flag-heading nil))))
  18831. (defun org-goto-first-child ()
  18832. "Goto the first child, even if it is invisible.
  18833. Return t when a child was found. Otherwise don't move point and
  18834. return nil."
  18835. (let (level (pos (point)) (re org-outline-regexp-bol))
  18836. (when (ignore-errors (org-back-to-heading t))
  18837. (setq level (outline-level))
  18838. (forward-char 1)
  18839. (if (and (re-search-forward re nil t) (> (outline-level) level))
  18840. (progn (goto-char (match-beginning 0)) t)
  18841. (goto-char pos) nil))))
  18842. (defun org-show-hidden-entry ()
  18843. "Show an entry where even the heading is hidden."
  18844. (save-excursion
  18845. (org-show-entry)))
  18846. (defun org-flag-heading (flag &optional entry)
  18847. "Flag the current heading. FLAG non-nil means make invisible.
  18848. When ENTRY is non-nil, show the entire entry."
  18849. (save-excursion
  18850. (org-back-to-heading t)
  18851. ;; Check if we should show the entire entry
  18852. (if (not entry)
  18853. (org-flag-region
  18854. (line-end-position 0) (line-end-position) flag 'outline)
  18855. (org-show-entry)
  18856. (save-excursion
  18857. (and (outline-next-heading)
  18858. (org-flag-heading nil))))))
  18859. (defun org-get-next-sibling ()
  18860. "Move to next heading of the same level, and return point.
  18861. If there is no such heading, return nil.
  18862. This is like outline-next-sibling, but invisible headings are ok."
  18863. (let ((level (funcall outline-level)))
  18864. (outline-next-heading)
  18865. (while (and (not (eobp)) (> (funcall outline-level) level))
  18866. (outline-next-heading))
  18867. (unless (or (eobp) (< (funcall outline-level) level))
  18868. (point))))
  18869. (defun org-get-last-sibling ()
  18870. "Move to previous heading of the same level, and return point.
  18871. If there is no such heading, return nil."
  18872. (let ((opoint (point))
  18873. (level (funcall outline-level)))
  18874. (outline-previous-heading)
  18875. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18876. (while (and (> (funcall outline-level) level)
  18877. (not (bobp)))
  18878. (outline-previous-heading))
  18879. (unless (< (funcall outline-level) level)
  18880. (point)))))
  18881. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18882. "Goto to the end of a subtree."
  18883. ;; This contains an exact copy of the original function, but it uses
  18884. ;; `org-back-to-heading', to make it work also in invisible
  18885. ;; trees. And is uses an invisible-ok argument.
  18886. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18887. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18888. ;; with many children and grandchildren etc, this can be much faster
  18889. ;; than the outline version.
  18890. (org-back-to-heading invisible-ok)
  18891. (let ((first t)
  18892. (level (funcall outline-level)))
  18893. (if (and (derived-mode-p 'org-mode) (< level 1000))
  18894. ;; A true heading (not a plain list item), in Org
  18895. ;; This means we can easily find the end by looking
  18896. ;; only for the right number of stars. Using a regexp to do
  18897. ;; this is so much faster than using a Lisp loop.
  18898. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  18899. (forward-char 1)
  18900. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  18901. ;; something else, do it the slow way
  18902. (while (and (not (eobp))
  18903. (or first (> (funcall outline-level) level)))
  18904. (setq first nil)
  18905. (outline-next-heading)))
  18906. (unless to-heading
  18907. (when (memq (preceding-char) '(?\n ?\^M))
  18908. ;; Go to end of line before heading
  18909. (forward-char -1)
  18910. (when (memq (preceding-char) '(?\n ?\^M))
  18911. ;; leave blank line before heading
  18912. (forward-char -1)))))
  18913. (point))
  18914. (defun org-end-of-meta-data (&optional full)
  18915. "Skip planning line and properties drawer in current entry.
  18916. When optional argument FULL is non-nil, also skip empty lines,
  18917. clocking lines and regular drawers at the beginning of the
  18918. entry."
  18919. (org-back-to-heading t)
  18920. (forward-line)
  18921. (when (looking-at-p org-planning-line-re) (forward-line))
  18922. (when (looking-at org-property-drawer-re)
  18923. (goto-char (match-end 0))
  18924. (forward-line))
  18925. (when (and full (not (org-at-heading-p)))
  18926. (catch 'exit
  18927. (let ((end (save-excursion (outline-next-heading) (point)))
  18928. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18929. (while (not (eobp))
  18930. (cond ((looking-at-p org-drawer-regexp)
  18931. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18932. (forward-line)
  18933. (throw 'exit t)))
  18934. ((looking-at-p re) (forward-line))
  18935. (t (throw 'exit t))))))))
  18936. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18937. "Move forward to the ARG'th subheading at same level as this one.
  18938. Stop at the first and last subheadings of a superior heading.
  18939. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18940. non-nil it will also look at invisible ones."
  18941. (interactive "p")
  18942. (let ((backward? (and arg (< arg 0))))
  18943. (if (org-before-first-heading-p)
  18944. (if backward? (goto-char (point-min)) (outline-next-heading))
  18945. (org-back-to-heading invisible-ok)
  18946. (unless backward? (end-of-line)) ;do not match current headline
  18947. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18948. (f (if backward? #'re-search-backward #'re-search-forward))
  18949. (count (if arg (abs arg) 1))
  18950. (result (point)))
  18951. (while (and (> count 0)
  18952. (funcall f org-outline-regexp-bol nil 'move))
  18953. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18954. (cond ((< l level) (setq count 0))
  18955. ((and (= l level)
  18956. (or invisible-ok
  18957. (not (org-invisible-p
  18958. (line-beginning-position)))))
  18959. (cl-decf count)
  18960. (when (= l level) (setq result (point)))))))
  18961. (goto-char result))
  18962. (beginning-of-line))))
  18963. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18964. "Move backward to the ARG'th subheading at same level as this one.
  18965. Stop at the first and last subheadings of a superior heading."
  18966. (interactive "p")
  18967. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18968. (defun org-next-visible-heading (arg)
  18969. "Move to the next visible heading.
  18970. This function wraps `outline-next-visible-heading' with
  18971. `org-with-limited-levels' in order to skip over inline tasks and
  18972. respect customization of `org-odd-levels-only'."
  18973. (interactive "p")
  18974. (org-with-limited-levels
  18975. (outline-next-visible-heading arg)))
  18976. (defun org-previous-visible-heading (arg)
  18977. "Move to the previous visible heading.
  18978. This function wraps `outline-previous-visible-heading' with
  18979. `org-with-limited-levels' in order to skip over inline tasks and
  18980. respect customization of `org-odd-levels-only'."
  18981. (interactive "p")
  18982. (org-with-limited-levels
  18983. (outline-previous-visible-heading arg)))
  18984. (defun org-forward-paragraph ()
  18985. "Move forward to beginning of next paragraph or equivalent.
  18986. The function moves point to the beginning of the next visible
  18987. structural element, which can be a paragraph, a table, a list
  18988. item, etc. It also provides some special moves for convenience:
  18989. - On an affiliated keyword, jump to the beginning of the
  18990. relative element.
  18991. - On an item or a footnote definition, move to the second
  18992. element inside, if any.
  18993. - On a table or a property drawer, jump after it.
  18994. - On a verse or source block, stop after blank lines."
  18995. (interactive)
  18996. (unless (eobp)
  18997. (let* ((deactivate-mark nil)
  18998. (element (org-element-at-point))
  18999. (type (org-element-type element))
  19000. (post-affiliated (org-element-property :post-affiliated element))
  19001. (contents-begin (org-element-property :contents-begin element))
  19002. (contents-end (org-element-property :contents-end element))
  19003. (end (let ((end (org-element-property :end element)) (parent element))
  19004. (while (and (setq parent (org-element-property :parent parent))
  19005. (= (org-element-property :contents-end parent) end))
  19006. (setq end (org-element-property :end parent)))
  19007. end)))
  19008. (cond ((not element)
  19009. (skip-chars-forward " \r\t\n")
  19010. (or (eobp) (beginning-of-line)))
  19011. ;; On affiliated keywords, move to element's beginning.
  19012. ((< (point) post-affiliated)
  19013. (goto-char post-affiliated))
  19014. ;; At a table row, move to the end of the table. Similarly,
  19015. ;; at a node property, move to the end of the property
  19016. ;; drawer.
  19017. ((memq type '(node-property table-row))
  19018. (goto-char (org-element-property
  19019. :end (org-element-property :parent element))))
  19020. ((memq type '(property-drawer table)) (goto-char end))
  19021. ;; Consider blank lines as separators in verse and source
  19022. ;; blocks to ease editing.
  19023. ((memq type '(src-block verse-block))
  19024. (when (eq type 'src-block)
  19025. (setq contents-end
  19026. (save-excursion (goto-char end)
  19027. (skip-chars-backward " \r\t\n")
  19028. (line-beginning-position))))
  19029. (beginning-of-line)
  19030. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  19031. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  19032. (goto-char end)
  19033. (skip-chars-forward " \r\t\n")
  19034. (if (= (point) contents-end) (goto-char end)
  19035. (beginning-of-line))))
  19036. ;; With no contents, just skip element.
  19037. ((not contents-begin) (goto-char end))
  19038. ;; If contents are invisible, skip the element altogether.
  19039. ((org-invisible-p (line-end-position))
  19040. (cl-case type
  19041. (headline
  19042. (org-with-limited-levels (outline-next-visible-heading 1)))
  19043. ;; At a plain list, make sure we move to the next item
  19044. ;; instead of skipping the whole list.
  19045. (plain-list (forward-char)
  19046. (org-forward-paragraph))
  19047. (otherwise (goto-char end))))
  19048. ((>= (point) contents-end) (goto-char end))
  19049. ((>= (point) contents-begin)
  19050. ;; This can only happen on paragraphs and plain lists.
  19051. (cl-case type
  19052. (paragraph (goto-char end))
  19053. ;; At a plain list, try to move to second element in
  19054. ;; first item, if possible.
  19055. (plain-list (end-of-line)
  19056. (org-forward-paragraph))))
  19057. ;; When contents start on the middle of a line (e.g. in
  19058. ;; items and footnote definitions), try to reach first
  19059. ;; element starting after current line.
  19060. ((> (line-end-position) contents-begin)
  19061. (end-of-line)
  19062. (org-forward-paragraph))
  19063. (t (goto-char contents-begin))))))
  19064. (defun org-backward-paragraph ()
  19065. "Move backward to start of previous paragraph or equivalent.
  19066. The function moves point to the beginning of the current
  19067. structural element, which can be a paragraph, a table, a list
  19068. item, etc., or to the beginning of the previous visible one if
  19069. point is already there. It also provides some special moves for
  19070. convenience:
  19071. - On an affiliated keyword, jump to the first one.
  19072. - On a table or a property drawer, move to its beginning.
  19073. - On comment, example, export, src and verse blocks, stop
  19074. before blank lines."
  19075. (interactive)
  19076. (unless (bobp)
  19077. (let* ((deactivate-mark nil)
  19078. (element (org-element-at-point))
  19079. (type (org-element-type element))
  19080. (contents-end (org-element-property :contents-end element))
  19081. (post-affiliated (org-element-property :post-affiliated element))
  19082. (begin (org-element-property :begin element))
  19083. (special? ;blocks handled specially
  19084. (memq type '(comment-block example-block export-block src-block
  19085. verse-block)))
  19086. (contents-begin
  19087. (if special?
  19088. ;; These types have no proper contents. Fake line
  19089. ;; below the block opening line as contents beginning.
  19090. (save-excursion (goto-char begin) (line-beginning-position 2))
  19091. (org-element-property :contents-begin element))))
  19092. (cond
  19093. ((not element) (goto-char (point-min)))
  19094. ((= (point) begin)
  19095. (backward-char)
  19096. (org-backward-paragraph))
  19097. ((<= (point) post-affiliated) (goto-char begin))
  19098. ;; Special behavior: on a table or a property drawer, move to
  19099. ;; its beginning.
  19100. ((memq type '(node-property table-row))
  19101. (goto-char (org-element-property
  19102. :post-affiliated (org-element-property :parent element))))
  19103. (special?
  19104. (if (<= (point) contents-begin) (goto-char post-affiliated)
  19105. ;; Inside a verse block, see blank lines as paragraph
  19106. ;; separators.
  19107. (let ((origin (point)))
  19108. (skip-chars-backward " \r\t\n" contents-begin)
  19109. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  19110. (skip-chars-forward " \r\t\n" origin)
  19111. (if (= (point) origin) (goto-char contents-begin)
  19112. (beginning-of-line))))))
  19113. ((eq type 'paragraph) (goto-char contents-begin)
  19114. ;; When at first paragraph in an item or a footnote definition,
  19115. ;; move directly to beginning of line.
  19116. (let ((parent-contents
  19117. (org-element-property
  19118. :contents-begin (org-element-property :parent element))))
  19119. (when (and parent-contents (= parent-contents contents-begin))
  19120. (beginning-of-line))))
  19121. ;; At the end of a greater element, move to the beginning of
  19122. ;; the last element within.
  19123. ((and contents-end (>= (point) contents-end))
  19124. (goto-char (1- contents-end))
  19125. (org-backward-paragraph))
  19126. (t (goto-char (or post-affiliated begin))))
  19127. ;; Ensure we never leave point invisible.
  19128. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  19129. (defun org-forward-element ()
  19130. "Move forward by one element.
  19131. Move to the next element at the same level, when possible."
  19132. (interactive)
  19133. (cond ((eobp) (user-error "Cannot move further down"))
  19134. ((org-with-limited-levels (org-at-heading-p))
  19135. (let ((origin (point)))
  19136. (goto-char (org-end-of-subtree nil t))
  19137. (unless (org-with-limited-levels (org-at-heading-p))
  19138. (goto-char origin)
  19139. (user-error "Cannot move further down"))))
  19140. (t
  19141. (let* ((elem (org-element-at-point))
  19142. (end (org-element-property :end elem))
  19143. (parent (org-element-property :parent elem)))
  19144. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19145. (goto-char (org-element-property :end parent)))
  19146. ((integer-or-marker-p end) (goto-char end))
  19147. (t (message "No element at point")))))))
  19148. (defun org-backward-element ()
  19149. "Move backward by one element.
  19150. Move to the previous element at the same level, when possible."
  19151. (interactive)
  19152. (cond ((bobp) (user-error "Cannot move further up"))
  19153. ((org-with-limited-levels (org-at-heading-p))
  19154. ;; At a headline, move to the previous one, if any, or stay
  19155. ;; here.
  19156. (let ((origin (point)))
  19157. (org-with-limited-levels (org-backward-heading-same-level 1))
  19158. ;; When current headline has no sibling above, move to its
  19159. ;; parent.
  19160. (when (= (point) origin)
  19161. (or (org-with-limited-levels (org-up-heading-safe))
  19162. (progn (goto-char origin)
  19163. (user-error "Cannot move further up"))))))
  19164. (t
  19165. (let* ((elem (org-element-at-point))
  19166. (beg (org-element-property :begin elem)))
  19167. (cond
  19168. ;; Move to beginning of current element if point isn't
  19169. ;; there already.
  19170. ((null beg) (message "No element at point"))
  19171. ((/= (point) beg) (goto-char beg))
  19172. (t (goto-char beg)
  19173. (skip-chars-backward " \r\t\n")
  19174. (unless (bobp)
  19175. (let ((prev (org-element-at-point)))
  19176. (goto-char (org-element-property :begin prev))
  19177. (while (and (setq prev (org-element-property :parent prev))
  19178. (<= (org-element-property :end prev) beg))
  19179. (goto-char (org-element-property :begin prev)))))))))))
  19180. (defun org-up-element ()
  19181. "Move to upper element."
  19182. (interactive)
  19183. (if (org-with-limited-levels (org-at-heading-p))
  19184. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19185. (let* ((elem (org-element-at-point))
  19186. (parent (org-element-property :parent elem)))
  19187. (if parent (goto-char (org-element-property :begin parent))
  19188. (if (org-with-limited-levels (org-before-first-heading-p))
  19189. (user-error "No surrounding element")
  19190. (org-with-limited-levels (org-back-to-heading)))))))
  19191. (defun org-down-element ()
  19192. "Move to inner element."
  19193. (interactive)
  19194. (let ((element (org-element-at-point)))
  19195. (cond
  19196. ((memq (org-element-type element) '(plain-list table))
  19197. (goto-char (org-element-property :contents-begin element))
  19198. (forward-char))
  19199. ((memq (org-element-type element) org-element-greater-elements)
  19200. ;; If contents are hidden, first disclose them.
  19201. (when (org-invisible-p (line-end-position)) (org-cycle))
  19202. (goto-char (or (org-element-property :contents-begin element)
  19203. (user-error "No content for this element"))))
  19204. (t (user-error "No inner element")))))
  19205. (defun org-drag-element-backward ()
  19206. "Move backward element at point."
  19207. (interactive)
  19208. (let ((elem (or (org-element-at-point)
  19209. (user-error "No element at point"))))
  19210. (if (eq (org-element-type elem) 'headline)
  19211. ;; Preserve point when moving a whole tree, even if point was
  19212. ;; on blank lines below the headline.
  19213. (let ((offset (skip-chars-backward " \t\n")))
  19214. (unwind-protect (org-move-subtree-up)
  19215. (forward-char (- offset))))
  19216. (let ((prev-elem
  19217. (save-excursion
  19218. (goto-char (org-element-property :begin elem))
  19219. (skip-chars-backward " \r\t\n")
  19220. (unless (bobp)
  19221. (let* ((beg (org-element-property :begin elem))
  19222. (prev (org-element-at-point))
  19223. (up prev))
  19224. (while (and (setq up (org-element-property :parent up))
  19225. (<= (org-element-property :end up) beg))
  19226. (setq prev up))
  19227. prev)))))
  19228. ;; Error out if no previous element or previous element is
  19229. ;; a parent of the current one.
  19230. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19231. (user-error "Cannot drag element backward")
  19232. (let ((pos (point)))
  19233. (org-element-swap-A-B prev-elem elem)
  19234. (goto-char (+ (org-element-property :begin prev-elem)
  19235. (- pos (org-element-property :begin elem))))))))))
  19236. (defun org-drag-element-forward ()
  19237. "Move forward element at point."
  19238. (interactive)
  19239. (let* ((pos (point))
  19240. (elem (or (org-element-at-point)
  19241. (user-error "No element at point"))))
  19242. (when (= (point-max) (org-element-property :end elem))
  19243. (user-error "Cannot drag element forward"))
  19244. (goto-char (org-element-property :end elem))
  19245. (let ((next-elem (org-element-at-point)))
  19246. (when (or (org-element-nested-p elem next-elem)
  19247. (and (eq (org-element-type next-elem) 'headline)
  19248. (not (eq (org-element-type elem) 'headline))))
  19249. (goto-char pos)
  19250. (user-error "Cannot drag element forward"))
  19251. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19252. ;; body's length (without final blanks) and by the length of
  19253. ;; blanks between ELEM and NEXT-ELEM.
  19254. (let ((size-next (- (save-excursion
  19255. (goto-char (org-element-property :end next-elem))
  19256. (skip-chars-backward " \r\t\n")
  19257. (forward-line)
  19258. ;; Small correction if buffer doesn't end
  19259. ;; with a newline character.
  19260. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19261. (org-element-property :begin next-elem)))
  19262. (size-blank (- (org-element-property :end elem)
  19263. (save-excursion
  19264. (goto-char (org-element-property :end elem))
  19265. (skip-chars-backward " \r\t\n")
  19266. (forward-line)
  19267. (point)))))
  19268. (org-element-swap-A-B elem next-elem)
  19269. (goto-char (+ pos size-next size-blank))))))
  19270. (defun org-drag-line-forward (arg)
  19271. "Drag the line at point ARG lines forward."
  19272. (interactive "p")
  19273. (dotimes (_ (abs arg))
  19274. (let ((c (current-column)))
  19275. (if (< 0 arg)
  19276. (progn
  19277. (beginning-of-line 2)
  19278. (transpose-lines 1)
  19279. (beginning-of-line 0))
  19280. (transpose-lines 1)
  19281. (beginning-of-line -1))
  19282. (org-move-to-column c))))
  19283. (defun org-drag-line-backward (arg)
  19284. "Drag the line at point ARG lines backward."
  19285. (interactive "p")
  19286. (org-drag-line-forward (- arg)))
  19287. (defun org-mark-element ()
  19288. "Put point at beginning of this element, mark at end.
  19289. Interactively, if this command is repeated or (in Transient Mark
  19290. mode) if the mark is active, it marks the next element after the
  19291. ones already marked."
  19292. (interactive)
  19293. (let (deactivate-mark)
  19294. (if (and (called-interactively-p 'any)
  19295. (or (and (eq last-command this-command) (mark t))
  19296. (and transient-mark-mode mark-active)))
  19297. (set-mark
  19298. (save-excursion
  19299. (goto-char (mark))
  19300. (goto-char (org-element-property :end (org-element-at-point)))))
  19301. (let ((element (org-element-at-point)))
  19302. (end-of-line)
  19303. (push-mark (org-element-property :end element) t t)
  19304. (goto-char (org-element-property :begin element))))))
  19305. (defun org-narrow-to-element ()
  19306. "Narrow buffer to current element."
  19307. (interactive)
  19308. (let ((elem (org-element-at-point)))
  19309. (cond
  19310. ((eq (car elem) 'headline)
  19311. (narrow-to-region
  19312. (org-element-property :begin elem)
  19313. (org-element-property :end elem)))
  19314. ((memq (car elem) org-element-greater-elements)
  19315. (narrow-to-region
  19316. (org-element-property :contents-begin elem)
  19317. (org-element-property :contents-end elem)))
  19318. (t
  19319. (narrow-to-region
  19320. (org-element-property :begin elem)
  19321. (org-element-property :end elem))))))
  19322. (defun org-transpose-element ()
  19323. "Transpose current and previous elements, keeping blank lines between.
  19324. Point is moved after both elements."
  19325. (interactive)
  19326. (org-skip-whitespace)
  19327. (let ((end (org-element-property :end (org-element-at-point))))
  19328. (org-drag-element-backward)
  19329. (goto-char end)))
  19330. (defun org-unindent-buffer ()
  19331. "Un-indent the visible part of the buffer.
  19332. Relative indentation (between items, inside blocks, etc.) isn't
  19333. modified."
  19334. (interactive)
  19335. (unless (eq major-mode 'org-mode)
  19336. (user-error "Cannot un-indent a buffer not in Org mode"))
  19337. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19338. (unindent-tree
  19339. (lambda (contents)
  19340. (dolist (element (reverse contents))
  19341. (if (memq (org-element-type element) '(headline section))
  19342. (funcall unindent-tree (org-element-contents element))
  19343. (save-excursion
  19344. (save-restriction
  19345. (narrow-to-region
  19346. (org-element-property :begin element)
  19347. (org-element-property :end element))
  19348. (org-do-remove-indentation))))))))
  19349. (funcall unindent-tree (org-element-contents parse-tree))))
  19350. (defun org-make-options-regexp (kwds &optional extra)
  19351. "Make a regular expression for keyword lines.
  19352. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19353. when non-nil, is a regexp matching keywords names."
  19354. (concat "^[ \t]*#\\+\\("
  19355. (regexp-opt kwds)
  19356. (and extra (concat (and kwds "\\|") extra))
  19357. "\\):[ \t]*\\(.*\\)"))
  19358. ;;; Conveniently switch to Info nodes
  19359. (defun org-info-find-node (&optional nodename)
  19360. "Find Info documentation NODENAME or Org documentation according context.
  19361. Started from `gnus-info-find-node'."
  19362. (interactive)
  19363. (Info-goto-node
  19364. (or nodename
  19365. (let ((default-org-info-node "(org) Top"))
  19366. (cond
  19367. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19368. ((eq 'org-mode major-mode)
  19369. (let* ((context (org-element-at-point))
  19370. (element-info-nodes ; compare to `org-element-all-elements'.
  19371. `((babel-call . "(org) Evaluating Code Blocks")
  19372. (center-block . "(org) Paragraphs")
  19373. (clock . ,default-org-info-node)
  19374. (comment . "(org) Comment Lines")
  19375. (comment-block . "(org) Comment Lines")
  19376. (diary-sexp . ,default-org-info-node)
  19377. (drawer . "(org) Drawers")
  19378. (dynamic-block . "(org) Dynamic Blocks")
  19379. (example-block . "(org) Literal Examples")
  19380. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19381. (fixed-width . ,default-org-info-node)
  19382. (footnote-definition . "(org) Creating Footnotes")
  19383. (headline . "(org) Document Structure")
  19384. (horizontal-rule . "(org) Built-in Table Editor")
  19385. (inlinetask . ,default-org-info-node)
  19386. (item . "(org) Plain Lists")
  19387. (keyword . "(org) Per-file keywords")
  19388. (latex-environment . "(org) LaTeX Export")
  19389. (node-property . "(org) Properties and Columns")
  19390. (paragraph . "(org) Paragraphs")
  19391. (plain-list . "(org) Plain Lists")
  19392. (planning . "(org) Deadlines and Scheduling")
  19393. (property-drawer . "(org) Properties and Columns")
  19394. (quote-block . "(org) Paragraphs")
  19395. (section . ,default-org-info-node)
  19396. (special-block . ,default-org-info-node)
  19397. (src-block . "(org) Working with Source Code")
  19398. (table . "(org) Tables")
  19399. (table-row . "(org) Tables")
  19400. (verse-block . "(org) Paragraphs"))))
  19401. (or (cdr (assoc (car context) element-info-nodes))
  19402. default-org-info-node)))
  19403. (t default-org-info-node))))))
  19404. ;;; Finish up
  19405. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19406. (lambda () (add-hook 'change-major-mode-hook
  19407. 'org-show-all 'append 'local)))
  19408. (provide 'org)
  19409. (run-hooks 'org-load-hook)
  19410. ;;; org.el ends here