org.el 813 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2020 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Bastien Guerry <bzg@gnu.org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Version: 9.4-dev
  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-quit "org-colview" ())
  131. (declare-function org-columns-insert-dblock "org-colview" ())
  132. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  133. (declare-function org-element-at-point "org-element" ())
  134. (declare-function org-element-cache-refresh "org-element" (pos))
  135. (declare-function org-element-cache-reset "org-element" (&optional all))
  136. (declare-function org-element-contents "org-element" (element))
  137. (declare-function org-element-context "org-element" (&optional element))
  138. (declare-function org-element-copy "org-element" (datum))
  139. (declare-function org-element-create "org-element" (type &optional props &rest children))
  140. (declare-function org-element-interpret-data "org-element" (data))
  141. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  142. (declare-function org-element-link-parser "org-element" ())
  143. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  144. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  145. (declare-function org-element-property "org-element" (property element))
  146. (declare-function org-element-put-property "org-element" (element property value))
  147. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  148. (declare-function org-element-timestamp-parser "org-element" ())
  149. (declare-function org-element-type "org-element" (element))
  150. (declare-function org-export-dispatch "ox" (&optional arg))
  151. (declare-function org-export-get-backend "ox" (name))
  152. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  153. (declare-function org-feed-goto-inbox "org-feed" (feed))
  154. (declare-function org-feed-update-all "org-feed" ())
  155. (declare-function org-goto "org-goto" (&optional alternative-interface))
  156. (declare-function org-id-find-id-file "org-id" (id))
  157. (declare-function org-id-get-create "org-id" (&optional force))
  158. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  159. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  160. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  161. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  162. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  163. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  164. (declare-function org-timer "org-timer" (&optional restart no-insert))
  165. (declare-function org-timer-item "org-timer" (&optional arg))
  166. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  167. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  168. (declare-function org-timer-start "org-timer" (&optional offset))
  169. (declare-function org-timer-stop "org-timer" ())
  170. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  171. (declare-function org-update-radio-target-regexp "ol" ())
  172. (defvar ffap-url-regexp)
  173. (defvar org-element-paragraph-separate)
  174. (defvar org-indent-indentation-per-level)
  175. (defvar org-radio-target-regexp)
  176. (defvar org-target-link-regexp)
  177. (defvar org-target-regexp)
  178. ;; load languages based on value of `org-babel-load-languages'
  179. (defvar org-babel-load-languages)
  180. ;;;###autoload
  181. (defun org-babel-do-load-languages (sym value)
  182. "Load the languages defined in `org-babel-load-languages'."
  183. (set-default sym value)
  184. (dolist (pair org-babel-load-languages)
  185. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  186. (if active
  187. (require (intern (concat "ob-" lang)))
  188. (fmakunbound
  189. (intern (concat "org-babel-execute:" lang)))
  190. (fmakunbound
  191. (intern (concat "org-babel-expand-body:" lang)))))))
  192. ;;;###autoload
  193. (defun org-babel-load-file (file &optional compile)
  194. "Load Emacs Lisp source code blocks in the Org FILE.
  195. This function exports the source code using `org-babel-tangle'
  196. and then loads the resulting file using `load-file'. With
  197. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  198. byte-compiled before it is loaded."
  199. (interactive "fFile to load: \nP")
  200. (let* ((tangled-file (concat (file-name-sans-extension file) ".el")))
  201. ;; Tangle only if the Org file is newer than the Elisp file.
  202. (unless (org-file-newer-than-p
  203. tangled-file
  204. (file-attribute-modification-time (file-attributes file)))
  205. (org-babel-tangle-file file tangled-file "emacs-lisp"))
  206. (if compile
  207. (progn
  208. (byte-compile-file tangled-file 'load)
  209. (message "Compiled and loaded %s" tangled-file))
  210. (load-file tangled-file)
  211. (message "Loaded %s" tangled-file))))
  212. (defcustom org-babel-load-languages '((emacs-lisp . t))
  213. "Languages which can be evaluated in Org buffers.
  214. \\<org-mode-map>
  215. This list can be used to load support for any of the languages
  216. below. Each language will depend on a different set of system
  217. executables and/or Emacs modes.
  218. When a language is \"loaded\", code blocks in that language can
  219. be evaluated with `org-babel-execute-src-block', which is bound
  220. by default to \\[org-ctrl-c-ctrl-c].
  221. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  222. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  223. default, only Emacs Lisp is loaded, since it has no specific
  224. requirement."
  225. :group 'org-babel
  226. :set 'org-babel-do-load-languages
  227. :version "24.1"
  228. :type '(alist :tag "Babel Languages"
  229. :key-type
  230. (choice
  231. (const :tag "Awk" awk)
  232. (const :tag "C" C)
  233. (const :tag "R" R)
  234. (const :tag "Asymptote" asymptote)
  235. (const :tag "Calc" calc)
  236. (const :tag "Clojure" clojure)
  237. (const :tag "CSS" css)
  238. (const :tag "Ditaa" ditaa)
  239. (const :tag "Dot" dot)
  240. (const :tag "Ebnf2ps" ebnf2ps)
  241. (const :tag "Emacs Lisp" emacs-lisp)
  242. (const :tag "Forth" forth)
  243. (const :tag "Fortran" fortran)
  244. (const :tag "Gnuplot" gnuplot)
  245. (const :tag "Haskell" haskell)
  246. (const :tag "hledger" hledger)
  247. (const :tag "IO" io)
  248. (const :tag "J" J)
  249. (const :tag "Java" java)
  250. (const :tag "Javascript" js)
  251. (const :tag "LaTeX" latex)
  252. (const :tag "Ledger" ledger)
  253. (const :tag "Lilypond" lilypond)
  254. (const :tag "Lisp" lisp)
  255. (const :tag "Makefile" makefile)
  256. (const :tag "Maxima" maxima)
  257. (const :tag "Matlab" matlab)
  258. (const :tag "Mscgen" mscgen)
  259. (const :tag "Ocaml" ocaml)
  260. (const :tag "Octave" octave)
  261. (const :tag "Org" org)
  262. (const :tag "Perl" perl)
  263. (const :tag "Pico Lisp" picolisp)
  264. (const :tag "PlantUML" plantuml)
  265. (const :tag "Python" python)
  266. (const :tag "Ruby" ruby)
  267. (const :tag "Sass" sass)
  268. (const :tag "Scala" scala)
  269. (const :tag "Scheme" scheme)
  270. (const :tag "Screen" screen)
  271. (const :tag "Shell Script" shell)
  272. (const :tag "Shen" shen)
  273. (const :tag "Sql" sql)
  274. (const :tag "Sqlite" sqlite)
  275. (const :tag "Stan" stan)
  276. (const :tag "Vala" vala))
  277. :value-type (boolean :tag "Activate" :value t)))
  278. ;;;; Customization variables
  279. (defcustom org-clone-delete-id nil
  280. "Remove ID property of clones of a subtree.
  281. When non-nil, clones of a subtree don't inherit the ID property.
  282. Otherwise they inherit the ID property with a new unique
  283. identifier."
  284. :type 'boolean
  285. :version "24.1"
  286. :group 'org-id)
  287. ;;; Version
  288. (org-check-version)
  289. ;;;###autoload
  290. (defun org-version (&optional here full message)
  291. "Show the Org version.
  292. Interactively, or when MESSAGE is non-nil, show it in echo area.
  293. With prefix argument, or when HERE is non-nil, insert it at point.
  294. In non-interactive uses, a reduced version string is output unless
  295. FULL is given."
  296. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  297. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  298. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  299. (load-suffixes (list ".el"))
  300. (org-install-dir
  301. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  302. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  303. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  304. (let* ((load-suffixes save-load-suffixes)
  305. (release (org-release))
  306. (git-version (org-git-version))
  307. (version (format "Org mode version %s (%s @ %s)"
  308. release
  309. git-version
  310. (if org-install-dir
  311. (if (string= org-dir org-install-dir)
  312. org-install-dir
  313. (concat "mixed installation! "
  314. org-install-dir
  315. " and "
  316. org-dir))
  317. "org-loaddefs.el can not be found!")))
  318. (version1 (if full version release)))
  319. (when here (insert version1))
  320. (when message (message "%s" version1))
  321. version1)))
  322. (defconst org-version (org-version))
  323. ;;; Syntax Constants
  324. ;;;; Keyword
  325. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  326. "Regular expression for keyword-lines")
  327. ;;;; Block
  328. (defconst org-block-regexp
  329. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  330. "Regular expression for hiding blocks.")
  331. (defconst org-dblock-start-re
  332. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  333. "Matches the start line of a dynamic block, with parameters.")
  334. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  335. "Matches the end of a dynamic block.")
  336. ;;;; Clock and Planning
  337. (defconst org-clock-string "CLOCK:"
  338. "String used as prefix for timestamps clocking work hours on an item.")
  339. (defvar org-closed-string "CLOSED:"
  340. "String used as the prefix for timestamps logging closing a TODO entry.")
  341. (defvar org-deadline-string "DEADLINE:"
  342. "String to mark deadline entries.
  343. \\<org-mode-map>
  344. A deadline is this string, followed by a time stamp. It must be
  345. a word, terminated by a colon. You can insert a schedule keyword
  346. and a timestamp with `\\[org-deadline]'.")
  347. (defvar org-scheduled-string "SCHEDULED:"
  348. "String to mark scheduled TODO entries.
  349. \\<org-mode-map>
  350. A schedule is this string, followed by a time stamp. It must be
  351. a word, terminated by a colon. You can insert a schedule keyword
  352. and a timestamp with `\\[org-schedule]'.")
  353. (defconst org-ds-keyword-length
  354. (+ 2
  355. (apply #'max
  356. (mapcar #'length
  357. (list org-deadline-string org-scheduled-string
  358. org-clock-string org-closed-string))))
  359. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  360. (defconst org-planning-line-re
  361. (concat "^[ \t]*"
  362. (regexp-opt
  363. (list org-closed-string org-deadline-string org-scheduled-string)
  364. t))
  365. "Matches a line with planning info.
  366. Matched keyword is in group 1.")
  367. (defconst org-clock-line-re
  368. (concat "^[ \t]*" org-clock-string)
  369. "Matches a line with clock info.")
  370. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  371. "Matches the DEADLINE keyword.")
  372. (defconst org-deadline-time-regexp
  373. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  374. "Matches the DEADLINE keyword together with a time stamp.")
  375. (defconst org-deadline-time-hour-regexp
  376. (concat "\\<" org-deadline-string
  377. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  378. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  379. (defconst org-deadline-line-regexp
  380. (concat "\\<\\(" org-deadline-string "\\).*")
  381. "Matches the DEADLINE keyword and the rest of the line.")
  382. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  383. "Matches the SCHEDULED keyword.")
  384. (defconst org-scheduled-time-regexp
  385. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  386. "Matches the SCHEDULED keyword together with a time stamp.")
  387. (defconst org-scheduled-time-hour-regexp
  388. (concat "\\<" org-scheduled-string
  389. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  390. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  391. (defconst org-closed-time-regexp
  392. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  393. "Matches the CLOSED keyword together with a time stamp.")
  394. (defconst org-keyword-time-regexp
  395. (concat "\\<"
  396. (regexp-opt
  397. (list org-scheduled-string org-deadline-string org-closed-string
  398. org-clock-string)
  399. t)
  400. " *[[<]\\([^]>]+\\)[]>]")
  401. "Matches any of the 4 keywords, together with the time stamp.")
  402. (defconst org-keyword-time-not-clock-regexp
  403. (concat
  404. "\\<"
  405. (regexp-opt
  406. (list org-scheduled-string org-deadline-string org-closed-string) t)
  407. " *[[<]\\([^]>]+\\)[]>]")
  408. "Matches any of the 3 keywords, together with the time stamp.")
  409. (defconst org-maybe-keyword-time-regexp
  410. (concat "\\(\\<"
  411. (regexp-opt
  412. (list org-scheduled-string org-deadline-string org-closed-string
  413. org-clock-string)
  414. t)
  415. "\\)?"
  416. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  417. "\\|"
  418. "<%%([^\r\n>]*>\\)")
  419. "Matches a timestamp, possibly preceded by a keyword.")
  420. (defconst org-all-time-keywords
  421. (mapcar (lambda (w) (substring w 0 -1))
  422. (list org-scheduled-string org-deadline-string
  423. org-clock-string org-closed-string))
  424. "List of time keywords.")
  425. ;;;; Drawer
  426. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  427. "Matches first or last line of a hidden block.
  428. Group 1 contains drawer's name or \"END\".")
  429. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  430. "Regular expression matching the first line of a property drawer.")
  431. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  432. "Regular expression matching the last line of a property drawer.")
  433. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  434. "Regular expression matching the first line of a clock drawer.")
  435. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  436. "Regular expression matching the last line of a clock drawer.")
  437. (defconst org-property-drawer-re
  438. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  439. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  440. "[ \t]*:END:[ \t]*$")
  441. "Matches an entire property drawer.")
  442. (defconst org-clock-drawer-re
  443. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  444. org-clock-drawer-end-re "\\)\n?")
  445. "Matches an entire clock drawer.")
  446. ;;;; Headline
  447. (defconst org-heading-keyword-regexp-format
  448. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  449. "Printf format for a regexp matching a headline with some keyword.
  450. This regexp will match the headline of any node which has the
  451. exact keyword that is put into the format. The keyword isn't in
  452. any group by default, but the stars and the body are.")
  453. (defconst org-heading-keyword-maybe-regexp-format
  454. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  455. "Printf format for a regexp matching a headline, possibly with some keyword.
  456. This regexp can match any headline with the specified keyword, or
  457. without a keyword. The keyword isn't in any group by default,
  458. but the stars and the body are.")
  459. (defconst org-archive-tag "ARCHIVE"
  460. "The tag that marks a subtree as archived.
  461. An archived subtree does not open during visibility cycling, and does
  462. not contribute to the agenda listings.")
  463. (defconst org-tag-re "[[:alnum:]_@#%]+"
  464. "Regexp matching a single tag.")
  465. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  466. "Regexp matching the tag group at the end of a line, with leading spaces.
  467. Tags are stored in match group 1. Match group 2 stores the tags
  468. without the enclosing colons.")
  469. (defconst org-tag-line-re
  470. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  471. "Regexp matching tags in a headline.
  472. Tags are stored in match group 1. Match group 2 stores the tags
  473. without the enclosing colons.")
  474. (eval-and-compile
  475. (defconst org-comment-string "COMMENT"
  476. "Entries starting with this keyword will never be exported.
  477. \\<org-mode-map>
  478. An entry can be toggled between COMMENT and normal with
  479. `\\[org-toggle-comment]'."))
  480. ;;;; LaTeX Environments and Fragments
  481. (defconst org-latex-regexps
  482. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  483. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  484. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  485. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  486. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  487. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  488. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  489. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  490. "Regular expressions for matching embedded LaTeX.")
  491. ;;;; Node Property
  492. (defconst org-effort-property "Effort"
  493. "The property that is being used to keep track of effort estimates.
  494. Effort estimates given in this property need to be in the format
  495. defined in org-duration.el.")
  496. ;;;; Timestamp
  497. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  498. "Regular expression for fast time stamp matching.")
  499. (defconst org-ts-regexp-inactive
  500. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  501. "Regular expression for fast inactive time stamp matching.")
  502. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  503. "Regular expression for fast time stamp matching.")
  504. (defconst org-ts-regexp0
  505. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  506. "Regular expression matching time strings for analysis.
  507. This one does not require the space after the date, so it can be used
  508. on a string that terminates immediately after the date.")
  509. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  510. "Regular expression matching time strings for analysis.")
  511. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  512. "Regular expression matching time stamps, with groups.")
  513. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  514. "Regular expression matching time stamps (also [..]), with groups.")
  515. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  516. "Regular expression matching a time stamp range.")
  517. (defconst org-tr-regexp-both
  518. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  519. "Regular expression matching a time stamp range.")
  520. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  521. org-ts-regexp "\\)?")
  522. "Regular expression matching a time stamp or time stamp range.")
  523. (defconst org-tsr-regexp-both
  524. (concat org-ts-regexp-both "\\(--?-?"
  525. org-ts-regexp-both "\\)?")
  526. "Regular expression matching a time stamp or time stamp range.
  527. The time stamps may be either active or inactive.")
  528. (defconst org-repeat-re
  529. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  530. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  531. "Regular expression for specifying repeated events.
  532. After a match, group 1 contains the repeat expression.")
  533. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  534. "Formats for `format-time-string' which are used for time stamps.")
  535. ;;; The custom variables
  536. (defgroup org nil
  537. "Outline-based notes management and organizer."
  538. :tag "Org"
  539. :group 'outlines
  540. :group 'calendar)
  541. (defcustom org-mode-hook nil
  542. "Mode hook for Org mode, run after the mode was turned on."
  543. :group 'org
  544. :type 'hook)
  545. (defcustom org-load-hook nil
  546. "Hook that is run after org.el has been loaded."
  547. :group 'org
  548. :type 'hook)
  549. (defcustom org-log-buffer-setup-hook nil
  550. "Hook that is run after an Org log buffer is created."
  551. :group 'org
  552. :version "24.1"
  553. :type 'hook)
  554. (defvar org-modules) ; defined below
  555. (defvar org-modules-loaded nil
  556. "Have the modules been loaded already?")
  557. (defun org-load-modules-maybe (&optional force)
  558. "Load all extensions listed in `org-modules'."
  559. (when (or force (not org-modules-loaded))
  560. (dolist (ext org-modules)
  561. (condition-case nil (require ext)
  562. (error (message "Problems while trying to load feature `%s'" ext))))
  563. (setq org-modules-loaded t)))
  564. (defun org-set-modules (var value)
  565. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  566. (set var value)
  567. (when (featurep 'org)
  568. (org-load-modules-maybe 'force)
  569. (org-element-cache-reset 'all)))
  570. (defcustom org-modules '(ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  571. "Modules that should always be loaded together with org.el.
  572. If a description starts with <C>, the file is not part of Emacs
  573. and loading it will require that you have downloaded and properly
  574. installed the Org mode distribution.
  575. You can also use this system to load external packages (i.e. neither Org
  576. core modules, nor modules from the CONTRIB directory). Just add symbols
  577. to the end of the list. If the package is called org-xyz.el, then you need
  578. to add the symbol `xyz', and the package must have a call to:
  579. (provide \\='org-xyz)
  580. For export specific modules, see also `org-export-backends'."
  581. :group 'org
  582. :set 'org-set-modules
  583. :version "26.1"
  584. :package-version '(Org . "9.2")
  585. :type
  586. '(set :greedy t
  587. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  588. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  589. (const :tag " crypt: Encryption of subtrees" org-crypt)
  590. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  591. (const :tag " docview: Links to Docview buffers" ol-docview)
  592. (const :tag " eww: Store link to URL of Eww" ol-eww)
  593. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  594. (const :tag " habit: Track your consistency with habits" org-habit)
  595. (const :tag " id: Global IDs for identifying entries" org-id)
  596. (const :tag " info: Links to Info nodes" ol-info)
  597. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  598. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  599. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  600. (const :tag " mouse: Additional mouse support" org-mouse)
  601. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  602. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  603. (const :tag " tempo: Fast completion for structures" org-tempo)
  604. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  605. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  606. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  607. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  608. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  609. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  610. (const :tag "C collector: Collect properties into tables" org-collector)
  611. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  612. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  613. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  614. (const :tag "C eval: Include command output as text" org-eval)
  615. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  616. (const :tag "C git-link: Links to specific file version" ol-git-link)
  617. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  618. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  619. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  620. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  621. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  622. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  623. (const :tag "C man: Links to man pages in Org mode" ol-man)
  624. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  625. (const :tag "C notify: Notifications for Org mode" org-notify)
  626. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  627. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  628. (const :tag "C registry: A registry for Org links" org-registry)
  629. (const :tag "C screen: Visit screen sessions through links" org-screen)
  630. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  631. (const :tag "C secretary: Team management with Org" org-secretary)
  632. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  633. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  634. (const :tag "C track: Keep up with Org mode development" org-track)
  635. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  636. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  637. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  638. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  639. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  640. (defvar org-export-registered-backends) ; From ox.el.
  641. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  642. (declare-function org-export-backend-name "ox" (backend) t)
  643. (defcustom org-export-backends '(ascii html icalendar latex odt)
  644. "List of export back-ends that should be always available.
  645. If a description starts with <C>, the file is not part of Emacs
  646. and loading it will require that you have downloaded and properly
  647. installed the Org mode distribution.
  648. Unlike to `org-modules', libraries in this list will not be
  649. loaded along with Org, but only once the export framework is
  650. needed.
  651. This variable needs to be set before org.el is loaded. If you
  652. need to make a change while Emacs is running, use the customize
  653. interface or run the following code, where VAL stands for the new
  654. value of the variable, after updating it:
  655. (progn
  656. (setq org-export-registered-backends
  657. (cl-remove-if-not
  658. (lambda (backend)
  659. (let ((name (org-export-backend-name backend)))
  660. (or (memq name val)
  661. (catch \\='parentp
  662. (dolist (b val)
  663. (and (org-export-derived-backend-p b name)
  664. (throw \\='parentp t)))))))
  665. org-export-registered-backends))
  666. (let ((new-list (mapcar #\\='org-export-backend-name
  667. org-export-registered-backends)))
  668. (dolist (backend val)
  669. (cond
  670. ((not (load (format \"ox-%s\" backend) t t))
  671. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  672. backend))
  673. ((not (memq backend new-list)) (push backend new-list))))
  674. (set-default \\='org-export-backends new-list)))
  675. Adding a back-end to this list will also pull the back-end it
  676. depends on, if any."
  677. :group 'org
  678. :group 'org-export
  679. :version "26.1"
  680. :package-version '(Org . "9.0")
  681. :initialize 'custom-initialize-set
  682. :set (lambda (var val)
  683. (if (not (featurep 'ox)) (set-default var val)
  684. ;; Any back-end not required anymore (not present in VAL and not
  685. ;; a parent of any back-end in the new value) is removed from the
  686. ;; list of registered back-ends.
  687. (setq org-export-registered-backends
  688. (cl-remove-if-not
  689. (lambda (backend)
  690. (let ((name (org-export-backend-name backend)))
  691. (or (memq name val)
  692. (catch 'parentp
  693. (dolist (b val)
  694. (and (org-export-derived-backend-p b name)
  695. (throw 'parentp t)))))))
  696. org-export-registered-backends))
  697. ;; Now build NEW-LIST of both new back-ends and required
  698. ;; parents.
  699. (let ((new-list (mapcar #'org-export-backend-name
  700. org-export-registered-backends)))
  701. (dolist (backend val)
  702. (cond
  703. ((not (load (format "ox-%s" backend) t t))
  704. (message "Problems while trying to load export back-end `%s'"
  705. backend))
  706. ((not (memq backend new-list)) (push backend new-list))))
  707. ;; Set VAR to that list with fixed dependencies.
  708. (set-default var new-list))))
  709. :type '(set :greedy t
  710. (const :tag " ascii Export buffer to ASCII format" ascii)
  711. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  712. (const :tag " html Export buffer to HTML format" html)
  713. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  714. (const :tag " latex Export buffer to LaTeX format" latex)
  715. (const :tag " man Export buffer to MAN format" man)
  716. (const :tag " md Export buffer to Markdown format" md)
  717. (const :tag " odt Export buffer to ODT format" odt)
  718. (const :tag " org Export buffer to Org format" org)
  719. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  720. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  721. (const :tag "C deck Export buffer to deck.js presentations" deck)
  722. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  723. (const :tag "C groff Export buffer to Groff format" groff)
  724. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  725. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  726. (const :tag "C s5 Export buffer to s5 presentations" s5)
  727. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  728. (eval-after-load 'ox
  729. '(dolist (backend org-export-backends)
  730. (condition-case nil (require (intern (format "ox-%s" backend)))
  731. (error (message "Problems while trying to load export back-end `%s'"
  732. backend)))))
  733. (defcustom org-support-shift-select nil
  734. "Non-nil means make shift-cursor commands select text when possible.
  735. \\<org-mode-map>
  736. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  737. start selecting a region, or enlarge regions started in this way.
  738. In Org mode, in special contexts, these same keys are used for
  739. other purposes, important enough to compete with shift selection.
  740. Org tries to balance these needs by supporting `shift-select-mode'
  741. outside these special contexts, under control of this variable.
  742. The default of this variable is nil, to avoid confusing behavior. Shifted
  743. cursor keys will then execute Org commands in the following contexts:
  744. - on a headline, changing TODO state (left/right) and priority (up/down)
  745. - on a time stamp, changing the time
  746. - in a plain list item, changing the bullet type
  747. - in a property definition line, switching between allowed values
  748. - in the BEGIN line of a clock table (changing the time block).
  749. Outside these contexts, the commands will throw an error.
  750. When this variable is t and the cursor is not in a special
  751. context, Org mode will support shift-selection for making and
  752. enlarging regions. To make this more effective, the bullet
  753. cycling will no longer happen anywhere in an item line, but only
  754. if the cursor is exactly on the bullet.
  755. If you set this variable to the symbol `always', then the keys
  756. will not be special in headlines, property lines, and item lines,
  757. to make shift selection work there as well. If this is what you
  758. want, you can use the following alternative commands:
  759. `\\[org-todo]' and `\\[org-priority]' \
  760. to change TODO state and priority,
  761. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  762. can be used to switch TODO sets,
  763. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  764. and properties can be edited by hand or in column view.
  765. However, when the cursor is on a timestamp, shift-cursor commands
  766. will still edit the time stamp - this is just too good to give up."
  767. :group 'org
  768. :type '(choice
  769. (const :tag "Never" nil)
  770. (const :tag "When outside special context" t)
  771. (const :tag "Everywhere except timestamps" always)))
  772. (defcustom org-loop-over-headlines-in-active-region nil
  773. "Shall some commands act upon headlines in the active region?
  774. When set to t, some commands will be performed in all headlines
  775. within the active region.
  776. When set to `start-level', some commands will be performed in all
  777. headlines within the active region, provided that these headlines
  778. are of the same level than the first one.
  779. When set to a string, those commands will be performed on the
  780. matching headlines within the active region. Such string must be
  781. a tags/property/todo match as it is used in the agenda tags view.
  782. The list of commands is: `org-schedule', `org-deadline',
  783. `org-todo', `org-set-tags-command', `org-archive-subtree',
  784. `org-archive-set-tag', `org-toggle-archive-tag' and
  785. `org-archive-to-archive-sibling'. The archiving commands skip
  786. already archived entries."
  787. :type '(choice (const :tag "Don't loop" nil)
  788. (const :tag "All headlines in active region" t)
  789. (const :tag "In active region, headlines at the same level than the first one" start-level)
  790. (string :tag "Tags/Property/Todo matcher"))
  791. :version "24.1"
  792. :group 'org-todo
  793. :group 'org-archive)
  794. (defcustom org-startup-folded t
  795. "Non-nil means entering Org mode will switch to OVERVIEW.
  796. This can also be configured on a per-file basis by adding one of
  797. the following lines anywhere in the buffer:
  798. #+STARTUP: fold (or `overview', this is equivalent)
  799. #+STARTUP: nofold (or `showall', this is equivalent)
  800. #+STARTUP: content
  801. #+STARTUP: showeverything
  802. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  803. to ignore this option when Org opens agenda files for the first
  804. time."
  805. :group 'org-startup
  806. :type '(choice
  807. (const :tag "nofold: show all" nil)
  808. (const :tag "fold: overview" t)
  809. (const :tag "content: all headlines" content)
  810. (const :tag "show everything, even drawers" showeverything)))
  811. (defcustom org-startup-truncated t
  812. "Non-nil means entering Org mode will set `truncate-lines'.
  813. This is useful since some lines containing links can be very long and
  814. uninteresting. Also tables look terrible when wrapped.
  815. The variable `org-startup-truncated' allows to configure
  816. truncation for Org mode different to the other modes that use the
  817. variable `truncate-lines' and as a shortcut instead of putting
  818. the variable `truncate-lines' into the `org-mode-hook'. If one
  819. wants to configure truncation for Org mode not statically but
  820. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  821. the variable `truncate-lines' has to be used because in such a
  822. case it is too late to set the variable `org-startup-truncated'."
  823. :group 'org-startup
  824. :type 'boolean)
  825. (defcustom org-startup-indented nil
  826. "Non-nil means turn on `org-indent-mode' on startup.
  827. This can also be configured on a per-file basis by adding one of
  828. the following lines anywhere in the buffer:
  829. #+STARTUP: indent
  830. #+STARTUP: noindent"
  831. :group 'org-structure
  832. :type '(choice
  833. (const :tag "Not" nil)
  834. (const :tag "Globally (slow on startup in large files)" t)))
  835. (defcustom org-use-sub-superscripts t
  836. "Non-nil means interpret \"_\" and \"^\" for display.
  837. If you want to control how Org exports those characters, see
  838. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  839. used to be an alias for `org-export-with-sub-superscripts' in
  840. Org <8.0, it is not anymore.
  841. When this option is turned on, you can use TeX-like syntax for
  842. sub- and superscripts within the buffer. Several characters after
  843. \"_\" or \"^\" will be considered as a single item - so grouping
  844. with {} is normally not needed. For example, the following things
  845. will be parsed as single sub- or superscripts:
  846. 10^24 or 10^tau several digits will be considered 1 item.
  847. 10^-12 or 10^-tau a leading sign with digits or a word
  848. x^2-y^3 will be read as x^2 - y^3, because items are
  849. terminated by almost any nonword/nondigit char.
  850. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  851. Still, ambiguity is possible. So when in doubt, use {} to enclose
  852. the sub/superscript. If you set this variable to the symbol `{}',
  853. the braces are *required* in order to trigger interpretations as
  854. sub/superscript. This can be helpful in documents that need \"_\"
  855. frequently in plain text."
  856. :group 'org-startup
  857. :version "24.4"
  858. :package-version '(Org . "8.0")
  859. :type '(choice
  860. (const :tag "Always interpret" t)
  861. (const :tag "Only with braces" {})
  862. (const :tag "Never interpret" nil)))
  863. (defcustom org-startup-with-beamer-mode nil
  864. "Non-nil means turn on `org-beamer-mode' on startup.
  865. This can also be configured on a per-file basis by adding one of
  866. the following lines anywhere in the buffer:
  867. #+STARTUP: beamer"
  868. :group 'org-startup
  869. :version "24.1"
  870. :type 'boolean)
  871. (defcustom org-startup-align-all-tables nil
  872. "Non-nil means align all tables when visiting a file.
  873. This can also be configured on a per-file basis by adding one of
  874. the following lines anywhere in the buffer:
  875. #+STARTUP: align
  876. #+STARTUP: noalign"
  877. :group 'org-startup
  878. :type 'boolean)
  879. (defcustom org-startup-shrink-all-tables nil
  880. "Non-nil means shrink all table columns with a width cookie.
  881. This can also be configured on a per-file basis by adding one of
  882. the following lines anywhere in the buffer:
  883. #+STARTUP: shrink"
  884. :group 'org-startup
  885. :type 'boolean
  886. :version "27.1"
  887. :package-version '(Org . "9.2")
  888. :safe #'booleanp)
  889. (defcustom org-startup-with-inline-images nil
  890. "Non-nil means show inline images when loading a new Org file.
  891. This can also be configured on a per-file basis by adding one of
  892. the following lines anywhere in the buffer:
  893. #+STARTUP: inlineimages
  894. #+STARTUP: noinlineimages"
  895. :group 'org-startup
  896. :version "24.1"
  897. :type 'boolean)
  898. (defcustom org-startup-with-latex-preview nil
  899. "Non-nil means preview LaTeX fragments when loading a new Org file.
  900. This can also be configured on a per-file basis by adding one of
  901. the following lines anywhere in the buffer:
  902. #+STARTUP: latexpreview
  903. #+STARTUP: nolatexpreview"
  904. :group 'org-startup
  905. :version "24.4"
  906. :package-version '(Org . "8.0")
  907. :type 'boolean)
  908. (defcustom org-insert-mode-line-in-empty-file nil
  909. "Non-nil means insert the first line setting Org mode in empty files.
  910. When the function `org-mode' is called interactively in an empty file, this
  911. normally means that the file name does not automatically trigger Org mode.
  912. To ensure that the file will always be in Org mode in the future, a
  913. line enforcing Org mode will be inserted into the buffer, if this option
  914. has been set."
  915. :group 'org-startup
  916. :type 'boolean)
  917. (defcustom org-ellipsis nil
  918. "The ellipsis to use in the Org mode outline.
  919. When nil, just use the standard three dots. When a non-empty string,
  920. use that string instead.
  921. The change affects only Org mode (which will then use its own display table).
  922. Changing this requires executing `\\[org-mode]' in a buffer to become
  923. effective."
  924. :group 'org-startup
  925. :type '(choice (const :tag "Default" nil)
  926. (string :tag "String" :value "...#"))
  927. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  928. (defvar org-display-table nil
  929. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  930. (defgroup org-keywords nil
  931. "Keywords in Org mode."
  932. :tag "Org Keywords"
  933. :group 'org)
  934. (defcustom org-closed-keep-when-no-todo nil
  935. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  936. :group 'org-todo
  937. :group 'org-keywords
  938. :version "24.4"
  939. :package-version '(Org . "8.0")
  940. :type 'boolean)
  941. (defgroup org-structure nil
  942. "Options concerning the general structure of Org files."
  943. :tag "Org Structure"
  944. :group 'org)
  945. (defgroup org-reveal-location nil
  946. "Options about how to make context of a location visible."
  947. :tag "Org Reveal Location"
  948. :group 'org-structure)
  949. (defcustom org-show-context-detail '((agenda . local)
  950. (bookmark-jump . lineage)
  951. (isearch . lineage)
  952. (default . ancestors))
  953. "Alist between context and visibility span when revealing a location.
  954. \\<org-mode-map>Some actions may move point into invisible
  955. locations. As a consequence, Org always expose a neighborhood
  956. around point. How much is shown depends on the initial action,
  957. or context. Valid contexts are
  958. agenda when exposing an entry from the agenda
  959. org-goto when using the command `org-goto' (`\\[org-goto]')
  960. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  961. tags-tree when constructing a sparse tree based on tags matches
  962. link-search when exposing search matches associated with a link
  963. mark-goto when exposing the jump goal of a mark
  964. bookmark-jump when exposing a bookmark location
  965. isearch when exiting from an incremental search
  966. default default for all contexts not set explicitly
  967. Allowed visibility spans are
  968. minimal show current headline; if point is not on headline,
  969. also show entry
  970. local show current headline, entry and next headline
  971. ancestors show current headline and its direct ancestors; if
  972. point is not on headline, also show entry
  973. lineage show current headline, its direct ancestors and all
  974. their children; if point is not on headline, also show
  975. entry and first child
  976. tree show current headline, its direct ancestors and all
  977. their children; if point is not on headline, also show
  978. entry and all children
  979. canonical show current headline, its direct ancestors along with
  980. their entries and children; if point is not located on
  981. the headline, also show current entry and all children
  982. As special cases, a nil or t value means show all contexts in
  983. `minimal' or `canonical' view, respectively.
  984. Some views can make displayed information very compact, but also
  985. make it harder to edit the location of the match. In such
  986. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  987. more context."
  988. :group 'org-reveal-location
  989. :version "26.1"
  990. :package-version '(Org . "9.0")
  991. :type '(choice
  992. (const :tag "Canonical" t)
  993. (const :tag "Minimal" nil)
  994. (repeat :greedy t :tag "Individual contexts"
  995. (cons
  996. (choice :tag "Context"
  997. (const agenda)
  998. (const org-goto)
  999. (const occur-tree)
  1000. (const tags-tree)
  1001. (const link-search)
  1002. (const mark-goto)
  1003. (const bookmark-jump)
  1004. (const isearch)
  1005. (const default))
  1006. (choice :tag "Detail level"
  1007. (const minimal)
  1008. (const local)
  1009. (const ancestors)
  1010. (const lineage)
  1011. (const tree)
  1012. (const canonical))))))
  1013. (defcustom org-indirect-buffer-display 'other-window
  1014. "How should indirect tree buffers be displayed?
  1015. This applies to indirect buffers created with the commands
  1016. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1017. Valid values are:
  1018. current-window Display in the current window
  1019. other-window Just display in another window.
  1020. dedicated-frame Create one new frame, and re-use it each time.
  1021. new-frame Make a new frame each time. Note that in this case
  1022. previously-made indirect buffers are kept, and you need to
  1023. kill these buffers yourself."
  1024. :group 'org-structure
  1025. :group 'org-agenda-windows
  1026. :type '(choice
  1027. (const :tag "In current window" current-window)
  1028. (const :tag "In current frame, other window" other-window)
  1029. (const :tag "Each time a new frame" new-frame)
  1030. (const :tag "One dedicated frame" dedicated-frame)))
  1031. (defconst org-file-apps-gnu
  1032. '((remote . emacs)
  1033. (system . mailcap)
  1034. (t . mailcap))
  1035. "Default file applications on a UNIX or GNU/Linux system.
  1036. See `org-file-apps'.")
  1037. (defconst org-file-apps-macos
  1038. '((remote . emacs)
  1039. (system . "open %s")
  1040. ("ps.gz" . "gv %s")
  1041. ("eps.gz" . "gv %s")
  1042. ("dvi" . "xdvi %s")
  1043. ("fig" . "xfig %s")
  1044. (t . "open %s"))
  1045. "Default file applications on a macOS system.
  1046. The system \"open\" is known as a default, but we use X11 applications
  1047. for some files for which the OS does not have a good default.
  1048. See `org-file-apps'.")
  1049. (defconst org-file-apps-windowsnt
  1050. (list '(remote . emacs)
  1051. (cons 'system (lambda (file _path)
  1052. (with-no-warnings (w32-shell-execute "open" file))))
  1053. (cons t (lambda (file _path)
  1054. (with-no-warnings (w32-shell-execute "open" file)))))
  1055. "Default file applications on a Windows NT system.
  1056. The system \"open\" is used for most files.
  1057. See `org-file-apps'.")
  1058. (defcustom org-file-apps
  1059. '((auto-mode . emacs)
  1060. (directory . emacs)
  1061. ("\\.mm\\'" . default)
  1062. ("\\.x?html?\\'" . default)
  1063. ("\\.pdf\\'" . default))
  1064. "Applications for opening `file:path' items in a document.
  1065. \\<org-mode-map>
  1066. Org mode uses system defaults for different file types, but you
  1067. can use this variable to set the application for a given file
  1068. extension. The entries in this list are cons cells where the car
  1069. identifies files and the cdr the corresponding command.
  1070. Possible values for the file identifier are:
  1071. \"string\" A string as a file identifier can be interpreted in different
  1072. ways, depending on its contents:
  1073. - Alphanumeric characters only:
  1074. Match links with this file extension.
  1075. Example: (\"pdf\" . \"evince %s\")
  1076. to open PDFs with evince.
  1077. - Regular expression: Match links where the
  1078. filename matches the regexp. If you want to
  1079. use groups here, use shy groups.
  1080. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1081. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1082. to open *.html and *.xhtml with firefox.
  1083. - Regular expression which contains (non-shy) groups:
  1084. Match links where the whole link, including \"::\", and
  1085. anything after that, matches the regexp.
  1086. In a custom command string, %1, %2, etc. are replaced with
  1087. the parts of the link that were matched by the groups.
  1088. For backwards compatibility, if a command string is given
  1089. that does not use any of the group matches, this case is
  1090. handled identically to the second one (i.e. match against
  1091. file name only).
  1092. In a custom function, you can access the group matches with
  1093. (match-string n link).
  1094. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1095. \"evince -p %1 %s\")
  1096. to open [[file:document.pdf::5]] with evince at page 5.
  1097. `directory' Matches a directory
  1098. `remote' Matches a remote file, accessible through tramp or efs.
  1099. Remote files most likely should be visited through Emacs
  1100. because external applications cannot handle such paths.
  1101. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1102. so all files Emacs knows how to handle. Using this with
  1103. command `emacs' will open most files in Emacs. Beware that this
  1104. will also open html files inside Emacs, unless you add
  1105. (\"html\" . default) to the list as well.
  1106. `system' The system command to open files, like `open' on Windows
  1107. and macOS, and mailcap under GNU/Linux. This is the command
  1108. that will be selected if you call `org-open-at-point' with a
  1109. double prefix argument (`\\[universal-argument] \
  1110. \\[universal-argument] \\[org-open-at-point]').
  1111. t Default for files not matched by any of the other options.
  1112. Possible values for the command are:
  1113. `emacs' The file will be visited by the current Emacs process.
  1114. `default' Use the default application for this file type, which is the
  1115. association for t in the list, most likely in the system-specific
  1116. part. This can be used to overrule an unwanted setting in the
  1117. system-specific variable.
  1118. `system' Use the system command for opening files, like \"open\".
  1119. This command is specified by the entry whose car is `system'.
  1120. Most likely, the system-specific version of this variable
  1121. does define this command, but you can overrule/replace it
  1122. here.
  1123. `mailcap' Use command specified in the mailcaps.
  1124. string A command to be executed by a shell; %s will be replaced
  1125. by the path to the file.
  1126. function A Lisp function, which will be called with two arguments:
  1127. the file path and the original link string, without the
  1128. \"file:\" prefix.
  1129. For more examples, see the system specific constants
  1130. `org-file-apps-macos'
  1131. `org-file-apps-windowsnt'
  1132. `org-file-apps-gnu'."
  1133. :group 'org
  1134. :package-version '(Org . "9.4")
  1135. :type '(repeat
  1136. (cons (choice :value ""
  1137. (string :tag "Extension")
  1138. (const :tag "System command to open files" system)
  1139. (const :tag "Default for unrecognized files" t)
  1140. (const :tag "Remote file" remote)
  1141. (const :tag "Links to a directory" directory)
  1142. (const :tag "Any files that have Emacs modes"
  1143. auto-mode))
  1144. (choice :value ""
  1145. (const :tag "Visit with Emacs" emacs)
  1146. (const :tag "Use default" default)
  1147. (const :tag "Use the system command" system)
  1148. (string :tag "Command")
  1149. (function :tag "Function")))))
  1150. (defcustom org-open-non-existing-files nil
  1151. "Non-nil means `org-open-file' opens non-existing files.
  1152. When nil, an error is thrown.
  1153. This variable applies only to external applications because they
  1154. might choke on non-existing files. If the link is to a file that
  1155. will be opened in Emacs, the variable is ignored."
  1156. :group 'org
  1157. :type 'boolean
  1158. :safe #'booleanp)
  1159. (defcustom org-open-directory-means-index-dot-org nil
  1160. "When non-nil a link to a directory really means to \"index.org\".
  1161. When nil, following a directory link runs Dired or opens
  1162. a finder/explorer window on that directory."
  1163. :group 'org
  1164. :type 'boolean
  1165. :safe #'booleanp)
  1166. (defcustom org-bookmark-names-plist
  1167. '(:last-capture "org-capture-last-stored"
  1168. :last-refile "org-refile-last-stored"
  1169. :last-capture-marker "org-capture-last-stored-marker")
  1170. "Names for bookmarks automatically set by some Org commands.
  1171. This can provide strings as names for a number of bookmarks Org sets
  1172. automatically. The following keys are currently implemented:
  1173. :last-capture
  1174. :last-capture-marker
  1175. :last-refile
  1176. When a key does not show up in the property list, the corresponding bookmark
  1177. is not set."
  1178. :group 'org-structure
  1179. :type 'plist)
  1180. (defgroup org-cycle nil
  1181. "Options concerning visibility cycling in Org mode."
  1182. :tag "Org Cycle"
  1183. :group 'org-structure)
  1184. (defcustom org-cycle-skip-children-state-if-no-children t
  1185. "Non-nil means skip CHILDREN state in entries that don't have any."
  1186. :group 'org-cycle
  1187. :type 'boolean)
  1188. (defcustom org-cycle-max-level nil
  1189. "Maximum level which should still be subject to visibility cycling.
  1190. Levels higher than this will, for cycling, be treated as text, not a headline.
  1191. When `org-odd-levels-only' is set, a value of N in this variable actually
  1192. means 2N-1 stars as the limiting headline.
  1193. When nil, cycle all levels.
  1194. Note that the limiting level of cycling is also influenced by
  1195. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1196. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1197. than its value."
  1198. :group 'org-cycle
  1199. :type '(choice
  1200. (const :tag "No limit" nil)
  1201. (integer :tag "Maximum level")))
  1202. (defcustom org-hide-block-startup nil
  1203. "Non-nil means entering Org mode will fold all blocks.
  1204. This can also be set in on a per-file basis with
  1205. #+STARTUP: hideblocks
  1206. #+STARTUP: showblocks"
  1207. :group 'org-startup
  1208. :group 'org-cycle
  1209. :type 'boolean)
  1210. (defcustom org-cycle-global-at-bob nil
  1211. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1212. This makes it possible to do global cycling without having to use `S-TAB'
  1213. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1214. line of the buffer
  1215. must not be a headline -- it may be empty or some other text.
  1216. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1217. sure the cursor stays at the beginning of the buffer.
  1218. When this option is nil, don't do anything special at the beginning of
  1219. the buffer."
  1220. :group 'org-cycle
  1221. :type 'boolean)
  1222. (defcustom org-cycle-level-after-item/entry-creation t
  1223. "Non-nil means cycle entry level or item indentation in new empty entries.
  1224. When the cursor is at the end of an empty headline, i.e., with only stars
  1225. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1226. and then all possible ancestor states, before returning to the original state.
  1227. This makes data entry extremely fast: M-RET to create a new headline,
  1228. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1229. When the cursor is at the end of an empty plain list item, one TAB will
  1230. make it a subitem, two or more tabs will back up to make this an item
  1231. higher up in the item hierarchy."
  1232. :group 'org-cycle
  1233. :type 'boolean)
  1234. (defcustom org-cycle-emulate-tab t
  1235. "Where should `org-cycle' emulate TAB.
  1236. nil Never
  1237. white Only in completely white lines
  1238. whitestart Only at the beginning of lines, before the first non-white char
  1239. t Everywhere except in headlines
  1240. exc-hl-bol Everywhere except at the start of a headline
  1241. If TAB is used in a place where it does not emulate TAB, the current subtree
  1242. visibility is cycled."
  1243. :group 'org-cycle
  1244. :type '(choice (const :tag "Never" nil)
  1245. (const :tag "Only in completely white lines" white)
  1246. (const :tag "Before first char in a line" whitestart)
  1247. (const :tag "Everywhere except in headlines" t)
  1248. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1249. (defcustom org-cycle-separator-lines 2
  1250. "Number of empty lines needed to keep an empty line between collapsed trees.
  1251. If you leave an empty line between the end of a subtree and the following
  1252. headline, this empty line is hidden when the subtree is folded.
  1253. Org mode will leave (exactly) one empty line visible if the number of
  1254. empty lines is equal or larger to the number given in this variable.
  1255. So the default 2 means at least 2 empty lines after the end of a subtree
  1256. are needed to produce free space between a collapsed subtree and the
  1257. following headline.
  1258. If the number is negative, and the number of empty lines is at least -N,
  1259. all empty lines are shown.
  1260. Special case: when 0, never leave empty lines in collapsed view."
  1261. :group 'org-cycle
  1262. :type 'integer)
  1263. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1264. (defcustom org-pre-cycle-hook nil
  1265. "Hook that is run before visibility cycling is happening.
  1266. The function(s) in this hook must accept a single argument which indicates
  1267. the new state that will be set right after running this hook. The
  1268. argument is a symbol. Before a global state change, it can have the values
  1269. `overview', `content', or `all'. Before a local state change, it can have
  1270. the values `folded', `children', or `subtree'."
  1271. :group 'org-cycle
  1272. :type 'hook)
  1273. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1274. org-cycle-show-empty-lines
  1275. org-optimize-window-after-visibility-change)
  1276. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1277. The function(s) in this hook must accept a single argument which indicates
  1278. the new state that was set by the most recent `org-cycle' command. The
  1279. argument is a symbol. After a global state change, it can have the values
  1280. `overview', `contents', or `all'. After a local state change, it can have
  1281. the values `folded', `children', or `subtree'."
  1282. :group 'org-cycle
  1283. :type 'hook
  1284. :version "26.1"
  1285. :package-version '(Org . "8.3"))
  1286. (defgroup org-edit-structure nil
  1287. "Options concerning structure editing in Org mode."
  1288. :tag "Org Edit Structure"
  1289. :group 'org-structure)
  1290. (defcustom org-odd-levels-only nil
  1291. "Non-nil means skip even levels and only use odd levels for the outline.
  1292. This has the effect that two stars are being added/taken away in
  1293. promotion/demotion commands. It also influences how levels are
  1294. handled by the exporters.
  1295. Changing it requires restart of `font-lock-mode' to become effective
  1296. for fontification also in regions already fontified.
  1297. You may also set this on a per-file basis by adding one of the following
  1298. lines to the buffer:
  1299. #+STARTUP: odd
  1300. #+STARTUP: oddeven"
  1301. :group 'org-edit-structure
  1302. :group 'org-appearance
  1303. :type 'boolean)
  1304. (defcustom org-adapt-indentation t
  1305. "Non-nil means adapt indentation to outline node level.
  1306. When this variable is set, Org assumes that you write outlines by
  1307. indenting text in each node to align with the headline (after the
  1308. stars). The following issues are influenced by this variable:
  1309. - The indentation is increased by one space in a demotion
  1310. command, and decreased by one in a promotion command. However,
  1311. in the latter case, if shifting some line in the entry body
  1312. would alter document structure (e.g., insert a new headline),
  1313. indentation is not changed at all.
  1314. - Property drawers and planning information is inserted indented
  1315. when this variable is set. When nil, they will not be indented.
  1316. - TAB indents a line relative to current level. The lines below
  1317. a headline will be indented when this variable is set.
  1318. Note that this is all about true indentation, by adding and
  1319. removing space characters. See also \"org-indent.el\" which does
  1320. level-dependent indentation in a virtual way, i.e. at display
  1321. time in Emacs."
  1322. :group 'org-edit-structure
  1323. :type 'boolean
  1324. :safe #'booleanp)
  1325. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1326. (defcustom org-special-ctrl-a/e nil
  1327. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1328. When t, `C-a' will bring back the cursor to the beginning of the
  1329. headline text, i.e. after the stars and after a possible TODO
  1330. keyword. In an item, this will be the position after bullet and
  1331. check-box, if any. When the cursor is already at that position,
  1332. another `C-a' will bring it to the beginning of the line.
  1333. `C-e' will jump to the end of the headline, ignoring the presence
  1334. of tags in the headline. A second `C-e' will then jump to the
  1335. true end of the line, after any tags. This also means that, when
  1336. this variable is non-nil, `C-e' also will never jump beyond the
  1337. end of the heading of a folded section, i.e. not after the
  1338. ellipses.
  1339. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1340. normally, going to the true line boundary first. Only a directly
  1341. following, identical keypress will bring the cursor to the
  1342. special positions.
  1343. This may also be a cons cell where the behavior for `C-a' and
  1344. `C-e' is set separately."
  1345. :group 'org-edit-structure
  1346. :type '(choice
  1347. (const :tag "off" nil)
  1348. (const :tag "on: after stars/bullet and before tags first" t)
  1349. (const :tag "reversed: true line boundary first" reversed)
  1350. (cons :tag "Set C-a and C-e separately"
  1351. (choice :tag "Special C-a"
  1352. (const :tag "off" nil)
  1353. (const :tag "on: after stars/bullet first" t)
  1354. (const :tag "reversed: before stars/bullet first" reversed))
  1355. (choice :tag "Special C-e"
  1356. (const :tag "off" nil)
  1357. (const :tag "on: before tags first" t)
  1358. (const :tag "reversed: after tags first" reversed)))))
  1359. (defcustom org-special-ctrl-k nil
  1360. "Non-nil means `C-k' will behave specially in headlines.
  1361. When nil, `C-k' will call the default `kill-line' command.
  1362. When t, the following will happen while the cursor is in the headline:
  1363. - When the cursor is at the beginning of a headline, kill the entire
  1364. line and possible the folded subtree below the line.
  1365. - When in the middle of the headline text, kill the headline up to the tags.
  1366. - When after the headline text, kill the tags."
  1367. :group 'org-edit-structure
  1368. :type 'boolean)
  1369. (defcustom org-ctrl-k-protect-subtree nil
  1370. "Non-nil means, do not delete a hidden subtree with C-k.
  1371. When set to the symbol `error', simply throw an error when C-k is
  1372. used to kill (part-of) a headline that has hidden text behind it.
  1373. Any other non-nil value will result in a query to the user, if it is
  1374. OK to kill that hidden subtree. When nil, kill without remorse."
  1375. :group 'org-edit-structure
  1376. :version "24.1"
  1377. :type '(choice
  1378. (const :tag "Do not protect hidden subtrees" nil)
  1379. (const :tag "Protect hidden subtrees with a security query" t)
  1380. (const :tag "Never kill a hidden subtree with C-k" error)))
  1381. (defcustom org-special-ctrl-o t
  1382. "Non-nil means, make `C-o' insert a row in tables."
  1383. :group 'org-edit-structure
  1384. :type 'boolean)
  1385. (defcustom org-catch-invisible-edits nil
  1386. "Check if in invisible region before inserting or deleting a character.
  1387. Valid values are:
  1388. nil Do not check, so just do invisible edits.
  1389. error Throw an error and do nothing.
  1390. show Make point visible, and do the requested edit.
  1391. show-and-error Make point visible, then throw an error and abort the edit.
  1392. smart Make point visible, and do insertion/deletion if it is
  1393. adjacent to visible text and the change feels predictable.
  1394. Never delete a previously invisible character or add in the
  1395. middle or right after an invisible region. Basically, this
  1396. allows insertion and backward-delete right before ellipses.
  1397. FIXME: maybe in this case we should not even show?"
  1398. :group 'org-edit-structure
  1399. :version "24.1"
  1400. :type '(choice
  1401. (const :tag "Do not check" nil)
  1402. (const :tag "Throw error when trying to edit" error)
  1403. (const :tag "Unhide, but do not do the edit" show-and-error)
  1404. (const :tag "Show invisible part and do the edit" show)
  1405. (const :tag "Be smart and do the right thing" smart)))
  1406. (defcustom org-yank-folded-subtrees t
  1407. "Non-nil means when yanking subtrees, fold them.
  1408. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1409. it starts with a heading and all other headings in it are either children
  1410. or siblings, then fold all the subtrees. However, do this only if no
  1411. text after the yank would be swallowed into a folded tree by this action."
  1412. :group 'org-edit-structure
  1413. :type 'boolean)
  1414. (defcustom org-yank-adjusted-subtrees nil
  1415. "Non-nil means when yanking subtrees, adjust the level.
  1416. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1417. this function for details."
  1418. :group 'org-edit-structure
  1419. :type 'boolean)
  1420. (defcustom org-M-RET-may-split-line '((default . t))
  1421. "Non-nil means M-RET will split the line at the cursor position.
  1422. When nil, it will go to the end of the line before making a
  1423. new line.
  1424. You may also set this option in a different way for different
  1425. contexts. Valid contexts are:
  1426. headline when creating a new headline
  1427. item when creating a new item
  1428. table in a table field
  1429. default the value to be used for all contexts not explicitly
  1430. customized"
  1431. :group 'org-structure
  1432. :group 'org-table
  1433. :type '(choice
  1434. (const :tag "Always" t)
  1435. (const :tag "Never" nil)
  1436. (repeat :greedy t :tag "Individual contexts"
  1437. (cons
  1438. (choice :tag "Context"
  1439. (const headline)
  1440. (const item)
  1441. (const table)
  1442. (const default))
  1443. (boolean)))))
  1444. (defcustom org-insert-heading-respect-content nil
  1445. "Non-nil means insert new headings after the current subtree.
  1446. \\<org-mode-map>
  1447. When nil, the new heading is created directly after the current line.
  1448. The commands `\\[org-insert-heading-respect-content]' and \
  1449. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1450. for the duration of the command."
  1451. :group 'org-structure
  1452. :type 'boolean)
  1453. (defcustom org-blank-before-new-entry '((heading . auto)
  1454. (plain-list-item . auto))
  1455. "Should `org-insert-heading' leave a blank line before new heading/item?
  1456. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1457. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1458. which case Org will look at the surrounding headings/items and try to
  1459. make an intelligent decision whether to insert a blank line or not."
  1460. :group 'org-edit-structure
  1461. :type '(list
  1462. (cons (const heading)
  1463. (choice (const :tag "Never" nil)
  1464. (const :tag "Always" t)
  1465. (const :tag "Auto" auto)))
  1466. (cons (const plain-list-item)
  1467. (choice (const :tag "Never" nil)
  1468. (const :tag "Always" t)
  1469. (const :tag "Auto" auto)))))
  1470. (defcustom org-insert-heading-hook nil
  1471. "Hook being run after inserting a new heading."
  1472. :group 'org-edit-structure
  1473. :type 'hook)
  1474. (defgroup org-sparse-trees nil
  1475. "Options concerning sparse trees in Org mode."
  1476. :tag "Org Sparse Trees"
  1477. :group 'org-structure)
  1478. (defcustom org-highlight-sparse-tree-matches t
  1479. "Non-nil means highlight all matches that define a sparse tree.
  1480. The highlights will automatically disappear the next time the buffer is
  1481. changed by an edit command."
  1482. :group 'org-sparse-trees
  1483. :type 'boolean)
  1484. (defcustom org-remove-highlights-with-change t
  1485. "Non-nil means any change to the buffer will remove temporary highlights.
  1486. \\<org-mode-map>\
  1487. Such highlights are created by `org-occur' and `org-clock-display'.
  1488. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1489. to get rid of the highlights.
  1490. The highlights created by `org-latex-preview' always need
  1491. `\\[org-latex-preview]' to be removed."
  1492. :group 'org-sparse-trees
  1493. :group 'org-time
  1494. :type 'boolean)
  1495. (defcustom org-occur-case-fold-search t
  1496. "Non-nil means `org-occur' should be case-insensitive.
  1497. If set to `smart' the search will be case-insensitive only if it
  1498. doesn't specify any upper case character."
  1499. :group 'org-sparse-trees
  1500. :version "26.1"
  1501. :type '(choice
  1502. (const :tag "Case-sensitive" nil)
  1503. (const :tag "Case-insensitive" t)
  1504. (const :tag "Case-insensitive for lower case searches only" smart)))
  1505. (defcustom org-occur-hook '(org-first-headline-recenter)
  1506. "Hook that is run after `org-occur' has constructed a sparse tree.
  1507. This can be used to recenter the window to show as much of the structure
  1508. as possible."
  1509. :group 'org-sparse-trees
  1510. :type 'hook)
  1511. (defcustom org-self-insert-cluster-for-undo nil
  1512. "Non-nil means cluster self-insert commands for undo when possible.
  1513. If this is set, then, like in the Emacs command loop, 20 consecutive
  1514. characters will be undone together.
  1515. This is configurable, because there is some impact on typing performance."
  1516. :group 'org-table
  1517. :type 'boolean)
  1518. (defvaralias 'org-activate-links 'org-highlight-links)
  1519. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1520. "Types of links that should be highlighted in Org files.
  1521. This is a list of symbols, each one of them leading to the
  1522. highlighting of a certain link type.
  1523. You can still open links that are not highlighted.
  1524. In principle, it does not hurt to turn on highlighting for all
  1525. link types. There may be a small gain when turning off unused
  1526. link types. The types are:
  1527. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1528. angle Links in angular brackets that may contain whitespace like
  1529. <bbdb:Carsten Dominik>.
  1530. plain Plain links in normal text, no whitespace, like http://google.com.
  1531. radio Text that is matched by a radio target, see manual for details.
  1532. tag Tag settings in a headline (link to tag search).
  1533. date Time stamps (link to calendar).
  1534. footnote Footnote labels.
  1535. If you set this variable during an Emacs session, use `org-mode-restart'
  1536. in the Org buffer so that the change takes effect."
  1537. :group 'org-appearance
  1538. :type '(set :greedy t
  1539. (const :tag "Double bracket links" bracket)
  1540. (const :tag "Angular bracket links" angle)
  1541. (const :tag "Plain text links" plain)
  1542. (const :tag "Radio target matches" radio)
  1543. (const :tag "Tags" tag)
  1544. (const :tag "Timestamps" date)
  1545. (const :tag "Footnotes" footnote)))
  1546. (defcustom org-mark-ring-length 4
  1547. "Number of different positions to be recorded in the ring.
  1548. Changing this requires a restart of Emacs to work correctly."
  1549. :group 'org-link-follow
  1550. :type 'integer)
  1551. (defgroup org-refile nil
  1552. "Options concerning refiling entries in Org mode."
  1553. :tag "Org Refile"
  1554. :group 'org)
  1555. (defcustom org-directory "~/org"
  1556. "Directory with Org files.
  1557. This is just a default location to look for Org files. There is no need
  1558. at all to put your files into this directory. It is used in the
  1559. following situations:
  1560. 1. When a capture template specifies a target file that is not an
  1561. absolute path. The path will then be interpreted relative to
  1562. `org-directory'
  1563. 2. When the value of variable `org-agenda-files' is a single file, any
  1564. relative paths in this file will be taken as relative to
  1565. `org-directory'."
  1566. :group 'org-refile
  1567. :group 'org-capture
  1568. :type 'directory)
  1569. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  1570. "Default target for storing notes.
  1571. Used as a fall back file for org-capture.el, for templates that
  1572. do not specify a target file."
  1573. :group 'org-refile
  1574. :group 'org-capture
  1575. :type 'file)
  1576. (defcustom org-reverse-note-order nil
  1577. "Non-nil means store new notes at the beginning of a file or entry.
  1578. When nil, new notes will be filed to the end of a file or entry.
  1579. This can also be a list with cons cells of regular expressions that
  1580. are matched against file names, and values."
  1581. :group 'org-capture
  1582. :group 'org-refile
  1583. :type '(choice
  1584. (const :tag "Reverse always" t)
  1585. (const :tag "Reverse never" nil)
  1586. (repeat :tag "By file name regexp"
  1587. (cons regexp boolean))))
  1588. (defcustom org-log-refile nil
  1589. "Information to record when a task is refiled.
  1590. Possible values are:
  1591. nil Don't add anything
  1592. time Add a time stamp to the task
  1593. note Prompt for a note and add it with template `org-log-note-headings'
  1594. This option can also be set with on a per-file-basis with
  1595. #+STARTUP: nologrefile
  1596. #+STARTUP: logrefile
  1597. #+STARTUP: lognoterefile
  1598. You can have local logging settings for a subtree by setting the LOGGING
  1599. property to one or more of these keywords.
  1600. When bulk-refiling, e.g., from the agenda, the value `note' is
  1601. forbidden and will temporarily be changed to `time'."
  1602. :group 'org-refile
  1603. :group 'org-progress
  1604. :version "24.1"
  1605. :type '(choice
  1606. (const :tag "No logging" nil)
  1607. (const :tag "Record timestamp" time)
  1608. (const :tag "Record timestamp with note." note)))
  1609. (defcustom org-refile-targets nil
  1610. "Targets for refiling entries with `\\[org-refile]'.
  1611. This is a list of cons cells. Each cell contains:
  1612. - a specification of the files to be considered, either a list of files,
  1613. or a symbol whose function or variable value will be used to retrieve
  1614. a file name or a list of file names. If you use `org-agenda-files' for
  1615. that, all agenda files will be scanned for targets. Nil means consider
  1616. headings in the current buffer.
  1617. - A specification of how to find candidate refile targets. This may be
  1618. any of:
  1619. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  1620. This tag has to be present in all target headlines, inheritance will
  1621. not be considered.
  1622. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  1623. todo keyword.
  1624. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  1625. headlines that are refiling targets.
  1626. - a cons cell (:level . N). Any headline of level N is considered a target.
  1627. Note that, when `org-odd-levels-only' is set, level corresponds to
  1628. order in hierarchy, not to the number of stars.
  1629. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  1630. Note that, when `org-odd-levels-only' is set, level corresponds to
  1631. order in hierarchy, not to the number of stars.
  1632. Each element of this list generates a set of possible targets.
  1633. The union of these sets is presented (with completion) to
  1634. the user by `org-refile'.
  1635. You can set the variable `org-refile-target-verify-function' to a function
  1636. to verify each headline found by the simple criteria above.
  1637. When this variable is nil, all top-level headlines in the current buffer
  1638. are used, equivalent to the value `((nil . (:level . 1))'."
  1639. :group 'org-refile
  1640. :type '(repeat
  1641. (cons
  1642. (choice :value org-agenda-files
  1643. (const :tag "All agenda files" org-agenda-files)
  1644. (const :tag "Current buffer" nil)
  1645. (function) (variable) (file))
  1646. (choice :tag "Identify target headline by"
  1647. (cons :tag "Specific tag" (const :value :tag) (string))
  1648. (cons :tag "TODO keyword" (const :value :todo) (string))
  1649. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  1650. (cons :tag "Level number" (const :value :level) (integer))
  1651. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  1652. (defcustom org-refile-target-verify-function nil
  1653. "Function to verify if the headline at point should be a refile target.
  1654. The function will be called without arguments, with point at the
  1655. beginning of the headline. It should return t and leave point
  1656. where it is if the headline is a valid target for refiling.
  1657. If the target should not be selected, the function must return nil.
  1658. In addition to this, it may move point to a place from where the search
  1659. should be continued. For example, the function may decide that the entire
  1660. subtree of the current entry should be excluded and move point to the end
  1661. of the subtree."
  1662. :group 'org-refile
  1663. :type '(choice
  1664. (const nil)
  1665. (function)))
  1666. (defcustom org-refile-use-cache nil
  1667. "Non-nil means cache refile targets to speed up the process.
  1668. \\<org-mode-map>\
  1669. The cache for a particular file will be updated automatically when
  1670. the buffer has been killed, or when any of the marker used for flagging
  1671. refile targets no longer points at a live buffer.
  1672. If you have added new entries to a buffer that might themselves be targets,
  1673. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  1674. if you find that easier, \
  1675. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  1676. \\[org-refile]'."
  1677. :group 'org-refile
  1678. :version "24.1"
  1679. :type 'boolean)
  1680. (defcustom org-refile-use-outline-path nil
  1681. "Non-nil means provide refile targets as paths.
  1682. So a level 3 headline will be available as level1/level2/level3.
  1683. When the value is `file', also include the file name (without directory)
  1684. into the path. In this case, you can also stop the completion after
  1685. the file name, to get entries inserted as top level in the file.
  1686. When `full-file-path', include the full file path.
  1687. When `buffer-name', use the buffer name."
  1688. :group 'org-refile
  1689. :type '(choice
  1690. (const :tag "Not" nil)
  1691. (const :tag "Yes" t)
  1692. (const :tag "Start with file name" file)
  1693. (const :tag "Start with full file path" full-file-path)
  1694. (const :tag "Start with buffer name" buffer-name)))
  1695. (defcustom org-outline-path-complete-in-steps t
  1696. "Non-nil means complete the outline path in hierarchical steps.
  1697. When Org uses the refile interface to select an outline path (see
  1698. `org-refile-use-outline-path'), the completion of the path can be
  1699. done in a single go, or it can be done in steps down the headline
  1700. hierarchy. Going in steps is probably the best if you do not use
  1701. a special completion package like `ido' or `icicles'. However,
  1702. when using these packages, going in one step can be very fast,
  1703. while still showing the whole path to the entry."
  1704. :group 'org-refile
  1705. :type 'boolean)
  1706. (defcustom org-refile-allow-creating-parent-nodes nil
  1707. "Non-nil means allow the creation of new nodes as refile targets.
  1708. New nodes are then created by adding \"/new node name\" to the completion
  1709. of an existing node. When the value of this variable is `confirm',
  1710. new node creation must be confirmed by the user (recommended).
  1711. When nil, the completion must match an existing entry.
  1712. Note that, if the new heading is not seen by the criteria
  1713. listed in `org-refile-targets', multiple instances of the same
  1714. heading would be created by trying again to file under the new
  1715. heading."
  1716. :group 'org-refile
  1717. :type '(choice
  1718. (const :tag "Never" nil)
  1719. (const :tag "Always" t)
  1720. (const :tag "Prompt for confirmation" confirm)))
  1721. (defcustom org-refile-active-region-within-subtree nil
  1722. "Non-nil means also refile active region within a subtree.
  1723. By default `org-refile' doesn't allow refiling regions if they
  1724. don't contain a set of subtrees, but it might be convenient to
  1725. do so sometimes: in that case, the first line of the region is
  1726. converted to a headline before refiling."
  1727. :group 'org-refile
  1728. :version "24.1"
  1729. :type 'boolean)
  1730. (defgroup org-todo nil
  1731. "Options concerning TODO items in Org mode."
  1732. :tag "Org TODO"
  1733. :group 'org)
  1734. (defgroup org-progress nil
  1735. "Options concerning Progress logging in Org mode."
  1736. :tag "Org Progress"
  1737. :group 'org-time)
  1738. (defvar org-todo-interpretation-widgets
  1739. '((:tag "Sequence (cycling hits every state)" sequence)
  1740. (:tag "Type (cycling directly to DONE)" type))
  1741. "The available interpretation symbols for customizing `org-todo-keywords'.
  1742. Interested libraries should add to this list.")
  1743. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1744. "List of TODO entry keyword sequences and their interpretation.
  1745. \\<org-mode-map>This is a list of sequences.
  1746. Each sequence starts with a symbol, either `sequence' or `type',
  1747. indicating if the keywords should be interpreted as a sequence of
  1748. action steps, or as different types of TODO items. The first
  1749. keywords are states requiring action - these states will select a headline
  1750. for inclusion into the global TODO list Org produces. If one of the
  1751. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1752. signify that no further action is necessary. If \"|\" is not found,
  1753. the last keyword is treated as the only DONE state of the sequence.
  1754. The command `\\[org-todo]' cycles an entry through these states, and one
  1755. additional state where no keyword is present. For details about this
  1756. cycling, see the manual.
  1757. TODO keywords and interpretation can also be set on a per-file basis with
  1758. the special #+SEQ_TODO and #+TYP_TODO lines.
  1759. Each keyword can optionally specify a character for fast state selection
  1760. \(in combination with the variable `org-use-fast-todo-selection')
  1761. and specifiers for state change logging, using the same syntax that
  1762. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1763. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1764. indicates to record a time stamp each time this state is selected.
  1765. Each keyword may also specify if a timestamp or a note should be
  1766. recorded when entering or leaving the state, by adding additional
  1767. characters in the parenthesis after the keyword. This looks like this:
  1768. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1769. record only the time of the state change. With X and Y being either
  1770. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1771. Y when leaving the state if and only if the *target* state does not
  1772. define X. You may omit any of the fast-selection key or X or /Y,
  1773. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1774. For backward compatibility, this variable may also be just a list
  1775. of keywords. In this case the interpretation (sequence or type) will be
  1776. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1777. :group 'org-todo
  1778. :group 'org-keywords
  1779. :type '(choice
  1780. (repeat :tag "Old syntax, just keywords"
  1781. (string :tag "Keyword"))
  1782. (repeat :tag "New syntax"
  1783. (cons
  1784. (choice
  1785. :tag "Interpretation"
  1786. ;;Quick and dirty way to see
  1787. ;;`org-todo-interpretations'. This takes the
  1788. ;;place of item arguments
  1789. :convert-widget
  1790. (lambda (widget)
  1791. (widget-put widget
  1792. :args (mapcar
  1793. (lambda (x)
  1794. (widget-convert
  1795. (cons 'const x)))
  1796. org-todo-interpretation-widgets))
  1797. widget))
  1798. (repeat
  1799. (string :tag "Keyword"))))))
  1800. (defvar-local org-todo-keywords-1 nil
  1801. "All TODO and DONE keywords active in a buffer.")
  1802. (defvar org-todo-keywords-for-agenda nil)
  1803. (defvar org-done-keywords-for-agenda nil)
  1804. (defvar org-todo-keyword-alist-for-agenda nil)
  1805. (defvar org-tag-alist-for-agenda nil
  1806. "Alist of all tags from all agenda files.")
  1807. (defvar org-tag-groups-alist-for-agenda nil
  1808. "Alist of all groups tags from all current agenda files.")
  1809. (defvar-local org-tag-groups-alist nil)
  1810. (defvar org-agenda-contributing-files nil)
  1811. (defvar-local org-current-tag-alist nil
  1812. "Alist of all tag groups in current buffer.
  1813. This variable takes into consideration `org-tag-alist',
  1814. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1815. (defvar-local org-not-done-keywords nil)
  1816. (defvar-local org-done-keywords nil)
  1817. (defvar-local org-todo-heads nil)
  1818. (defvar-local org-todo-sets nil)
  1819. (defvar-local org-todo-log-states nil)
  1820. (defvar-local org-todo-kwd-alist nil)
  1821. (defvar-local org-todo-key-alist nil)
  1822. (defvar-local org-todo-key-trigger nil)
  1823. (defcustom org-todo-interpretation 'sequence
  1824. "Controls how TODO keywords are interpreted.
  1825. This variable is in principle obsolete and is only used for
  1826. backward compatibility, if the interpretation of todo keywords is
  1827. not given already in `org-todo-keywords'. See that variable for
  1828. more information."
  1829. :group 'org-todo
  1830. :group 'org-keywords
  1831. :type '(choice (const sequence)
  1832. (const type)))
  1833. (defcustom org-use-fast-todo-selection 'auto
  1834. "\\<org-mode-map>\
  1835. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1836. This variable describes if and under what circumstances the cycling
  1837. mechanism for TODO keywords will be replaced by a single-key, direct
  1838. selection scheme, where the choices are displayed in a little window.
  1839. When nil, fast selection is never used. This means that the command
  1840. will always switch to the next state.
  1841. When it is the symbol `auto', fast selection is whenever selection
  1842. keys have been defined.
  1843. `expert' is like `auto', but no special window with the keyword
  1844. will be shown, choices will only be listed in the prompt.
  1845. In all cases, the special interface is only used if access keys have
  1846. actually been assigned by the user, i.e. if keywords in the configuration
  1847. are followed by a letter in parenthesis, like TODO(t)."
  1848. :group 'org-todo
  1849. :set (lambda (var val)
  1850. (cond
  1851. ((eq var t) (set var 'auto))
  1852. ((eq var 'prefix) (set var nil))
  1853. (t (set var val))))
  1854. :type '(choice
  1855. (const :tag "Never" nil)
  1856. (const :tag "Automatically, when key letter have been defined" auto)
  1857. (const :tag "Automatically, but don't show the selection window" expert)))
  1858. (defcustom org-provide-todo-statistics t
  1859. "Non-nil means update todo statistics after insert and toggle.
  1860. ALL-HEADLINES means update todo statistics by including headlines
  1861. with no TODO keyword as well, counting them as not done.
  1862. A list of TODO keywords means the same, but skip keywords that are
  1863. not in this list.
  1864. When set to a list of two lists, the first list contains keywords
  1865. to consider as TODO keywords, the second list contains keywords
  1866. to consider as DONE keywords.
  1867. When this is set, todo statistics is updated in the parent of the
  1868. current entry each time a todo state is changed."
  1869. :group 'org-todo
  1870. :type '(choice
  1871. (const :tag "Yes, only for TODO entries" t)
  1872. (const :tag "Yes, including all entries" all-headlines)
  1873. (repeat :tag "Yes, for TODOs in this list"
  1874. (string :tag "TODO keyword"))
  1875. (list :tag "Yes, for TODOs and DONEs in these lists"
  1876. (repeat (string :tag "TODO keyword"))
  1877. (repeat (string :tag "DONE keyword")))
  1878. (other :tag "No TODO statistics" nil)))
  1879. (defcustom org-hierarchical-todo-statistics t
  1880. "Non-nil means TODO statistics covers just direct children.
  1881. When nil, all entries in the subtree are considered.
  1882. This has only an effect if `org-provide-todo-statistics' is set.
  1883. To set this to nil for only a single subtree, use a COOKIE_DATA
  1884. property and include the word \"recursive\" into the value."
  1885. :group 'org-todo
  1886. :type 'boolean)
  1887. (defcustom org-after-todo-state-change-hook nil
  1888. "Hook which is run after the state of a TODO item was changed.
  1889. The new state (a string with a TODO keyword, or nil) is available in the
  1890. Lisp variable `org-state'."
  1891. :group 'org-todo
  1892. :type 'hook)
  1893. (defvar org-blocker-hook nil
  1894. "Hook for functions that are allowed to block a state change.
  1895. Functions in this hook should not modify the buffer.
  1896. Each function gets as its single argument a property list,
  1897. see `org-trigger-hook' for more information about this list.
  1898. If any of the functions in this hook returns nil, the state change
  1899. is blocked.")
  1900. (defvar org-trigger-hook nil
  1901. "Hook for functions that are triggered by a state change.
  1902. Each function gets as its single argument a property list with at
  1903. least the following elements:
  1904. (:type type-of-change :position pos-at-entry-start
  1905. :from old-state :to new-state)
  1906. Depending on the type, more properties may be present.
  1907. This mechanism is currently implemented for:
  1908. TODO state changes
  1909. ------------------
  1910. :type todo-state-change
  1911. :from previous state (keyword as a string), or nil, or a symbol
  1912. `todo' or `done', to indicate the general type of state.
  1913. :to new state, like in :from")
  1914. (defcustom org-enforce-todo-dependencies nil
  1915. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1916. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1917. be blocked if any prior sibling is not yet done.
  1918. Finally, if the parent is blocked because of ordered siblings of its own,
  1919. the child will also be blocked."
  1920. :set (lambda (var val)
  1921. (set var val)
  1922. (if val
  1923. (add-hook 'org-blocker-hook
  1924. 'org-block-todo-from-children-or-siblings-or-parent)
  1925. (remove-hook 'org-blocker-hook
  1926. 'org-block-todo-from-children-or-siblings-or-parent)))
  1927. :group 'org-todo
  1928. :type 'boolean)
  1929. (defcustom org-enforce-todo-checkbox-dependencies nil
  1930. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1931. When this is nil, checkboxes have no influence on switching TODO states.
  1932. When non-nil, you first need to check off all check boxes before the TODO
  1933. entry can be switched to DONE.
  1934. This variable needs to be set before org.el is loaded, and you need to
  1935. restart Emacs after a change to make the change effective. The only way
  1936. to change it while Emacs is running is through the customize interface."
  1937. :set (lambda (var val)
  1938. (set var val)
  1939. (if val
  1940. (add-hook 'org-blocker-hook
  1941. 'org-block-todo-from-checkboxes)
  1942. (remove-hook 'org-blocker-hook
  1943. 'org-block-todo-from-checkboxes)))
  1944. :group 'org-todo
  1945. :type 'boolean)
  1946. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1947. "Non-nil means inserting a TODO heading is treated as state change.
  1948. So when the command `\\[org-insert-todo-heading]' is used, state change
  1949. logging will apply if appropriate. When nil, the new TODO item will
  1950. be inserted directly, and no logging will take place."
  1951. :group 'org-todo
  1952. :type 'boolean)
  1953. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1954. "Non-nil means switching TODO states with S-cursor counts as state change.
  1955. This is the default behavior. However, setting this to nil allows a
  1956. convenient way to select a TODO state and bypass any logging associated
  1957. with that."
  1958. :group 'org-todo
  1959. :type 'boolean)
  1960. (defcustom org-todo-state-tags-triggers nil
  1961. "Tag changes that should be triggered by TODO state changes.
  1962. This is a list. Each entry is
  1963. (state-change (tag . flag) .......)
  1964. State-change can be a string with a state, and empty string to indicate the
  1965. state that has no TODO keyword, or it can be one of the symbols `todo'
  1966. or `done', meaning any not-done or done state, respectively."
  1967. :group 'org-todo
  1968. :group 'org-tags
  1969. :type '(repeat
  1970. (cons (choice :tag "When changing to"
  1971. (const :tag "Not-done state" todo)
  1972. (const :tag "Done state" done)
  1973. (string :tag "State"))
  1974. (repeat
  1975. (cons :tag "Tag action"
  1976. (string :tag "Tag")
  1977. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1978. (defcustom org-log-done nil
  1979. "Information to record when a task moves to the DONE state.
  1980. Possible values are:
  1981. nil Don't add anything, just change the keyword
  1982. time Add a time stamp to the task
  1983. note Prompt for a note and add it with template `org-log-note-headings'
  1984. This option can also be set with on a per-file-basis with
  1985. #+STARTUP: nologdone
  1986. #+STARTUP: logdone
  1987. #+STARTUP: lognotedone
  1988. You can have local logging settings for a subtree by setting the LOGGING
  1989. property to one or more of these keywords."
  1990. :group 'org-todo
  1991. :group 'org-progress
  1992. :type '(choice
  1993. (const :tag "No logging" nil)
  1994. (const :tag "Record CLOSED timestamp" time)
  1995. (const :tag "Record CLOSED timestamp with note." note)))
  1996. ;; Normalize old uses of org-log-done.
  1997. (cond
  1998. ((eq org-log-done t) (setq org-log-done 'time))
  1999. ((and (listp org-log-done) (memq 'done org-log-done))
  2000. (setq org-log-done 'note)))
  2001. (defcustom org-log-reschedule nil
  2002. "Information to record when the scheduling date of a task is modified.
  2003. Possible values are:
  2004. nil Don't add anything, just change the date
  2005. time Add a time stamp to the task
  2006. note Prompt for a note and add it with template `org-log-note-headings'
  2007. This option can also be set with on a per-file-basis with
  2008. #+STARTUP: nologreschedule
  2009. #+STARTUP: logreschedule
  2010. #+STARTUP: lognotereschedule
  2011. You can have local logging settings for a subtree by setting the LOGGING
  2012. property to one or more of these keywords.
  2013. This variable has an effect when calling `org-schedule' or
  2014. `org-agenda-schedule' only."
  2015. :group 'org-todo
  2016. :group 'org-progress
  2017. :type '(choice
  2018. (const :tag "No logging" nil)
  2019. (const :tag "Record timestamp" time)
  2020. (const :tag "Record timestamp with note" note)))
  2021. (defcustom org-log-redeadline nil
  2022. "Information to record when the deadline date of a task is modified.
  2023. Possible values are:
  2024. nil Don't add anything, just change the date
  2025. time Add a time stamp to the task
  2026. note Prompt for a note and add it with template `org-log-note-headings'
  2027. This option can also be set with on a per-file-basis with
  2028. #+STARTUP: nologredeadline
  2029. #+STARTUP: logredeadline
  2030. #+STARTUP: lognoteredeadline
  2031. You can have local logging settings for a subtree by setting the LOGGING
  2032. property to one or more of these keywords.
  2033. This variable has an effect when calling `org-deadline' or
  2034. `org-agenda-deadline' only."
  2035. :group 'org-todo
  2036. :group 'org-progress
  2037. :type '(choice
  2038. (const :tag "No logging" nil)
  2039. (const :tag "Record timestamp" time)
  2040. (const :tag "Record timestamp with note." note)))
  2041. (defcustom org-log-note-clock-out nil
  2042. "Non-nil means record a note when clocking out of an item.
  2043. This can also be configured on a per-file basis by adding one of
  2044. the following lines anywhere in the buffer:
  2045. #+STARTUP: lognoteclock-out
  2046. #+STARTUP: nolognoteclock-out"
  2047. :group 'org-todo
  2048. :group 'org-progress
  2049. :type 'boolean)
  2050. (defcustom org-log-done-with-time t
  2051. "Non-nil means the CLOSED time stamp will contain date and time.
  2052. When nil, only the date will be recorded."
  2053. :group 'org-progress
  2054. :type 'boolean)
  2055. (defcustom org-log-note-headings
  2056. '((done . "CLOSING NOTE %t")
  2057. (state . "State %-12s from %-12S %t")
  2058. (note . "Note taken on %t")
  2059. (reschedule . "Rescheduled from %S on %t")
  2060. (delschedule . "Not scheduled, was %S on %t")
  2061. (redeadline . "New deadline from %S on %t")
  2062. (deldeadline . "Removed deadline, was %S on %t")
  2063. (refile . "Refiled on %t")
  2064. (clock-out . ""))
  2065. "Headings for notes added to entries.
  2066. The value is an alist, with the car being a symbol indicating the
  2067. note context, and the cdr is the heading to be used. The heading
  2068. may also be the empty string. The following placeholders can be
  2069. used:
  2070. %t a time stamp.
  2071. %T an active time stamp instead the default inactive one
  2072. %d a short-format time stamp.
  2073. %D an active short-format time stamp.
  2074. %s the new TODO state or time stamp (inactive), in double quotes.
  2075. %S the old TODO state or time stamp (inactive), in double quotes.
  2076. %u the user name.
  2077. %U full user name.
  2078. In fact, it is not a good idea to change the `state' entry,
  2079. because Agenda Log mode depends on the format of these entries."
  2080. :group 'org-todo
  2081. :group 'org-progress
  2082. :type '(list :greedy t
  2083. (cons (const :tag "Heading when closing an item" done) string)
  2084. (cons (const :tag
  2085. "Heading when changing todo state (todo sequence only)"
  2086. state) string)
  2087. (cons (const :tag "Heading when just taking a note" note) string)
  2088. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2089. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2090. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2091. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2092. (cons (const :tag "Heading when refiling" refile) string)
  2093. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2094. (unless (assq 'note org-log-note-headings)
  2095. (push '(note . "%t") org-log-note-headings))
  2096. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2097. (defcustom org-log-into-drawer nil
  2098. "Non-nil means insert state change notes and time stamps into a drawer.
  2099. When nil, state changes notes will be inserted after the headline and
  2100. any scheduling and clock lines, but not inside a drawer.
  2101. The value of this variable should be the name of the drawer to use.
  2102. LOGBOOK is proposed as the default drawer for this purpose, you can
  2103. also set this to a string to define the drawer of your choice.
  2104. A value of t is also allowed, representing \"LOGBOOK\".
  2105. A value of t or nil can also be set with on a per-file-basis with
  2106. #+STARTUP: logdrawer
  2107. #+STARTUP: nologdrawer
  2108. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2109. will be ignored.
  2110. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2111. a subtree.
  2112. Do not check directly this variable in a Lisp program. Call
  2113. function `org-log-into-drawer' instead."
  2114. :group 'org-todo
  2115. :group 'org-progress
  2116. :type '(choice
  2117. (const :tag "Not into a drawer" nil)
  2118. (const :tag "LOGBOOK" t)
  2119. (string :tag "Other")))
  2120. (defun org-log-into-drawer ()
  2121. "Name of the log drawer, as a string, or nil.
  2122. This is the value of `org-log-into-drawer'. However, if the
  2123. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2124. be used instead of the default value."
  2125. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2126. (cond ((equal p "nil") nil)
  2127. ((equal p "t") "LOGBOOK")
  2128. ((stringp p) p)
  2129. (p "LOGBOOK")
  2130. ((stringp org-log-into-drawer) org-log-into-drawer)
  2131. (org-log-into-drawer "LOGBOOK"))))
  2132. (defcustom org-log-state-notes-insert-after-drawers nil
  2133. "Non-nil means insert state change notes after any drawers in entry.
  2134. Only the drawers that *immediately* follow the headline and the
  2135. deadline/scheduled line are skipped.
  2136. When nil, insert notes right after the heading and perhaps the line
  2137. with deadline/scheduling if present.
  2138. This variable will have no effect if `org-log-into-drawer' is
  2139. set."
  2140. :group 'org-todo
  2141. :group 'org-progress
  2142. :type 'boolean)
  2143. (defcustom org-log-states-order-reversed t
  2144. "Non-nil means the latest state note will be directly after heading.
  2145. When nil, the state change notes will be ordered according to time.
  2146. This option can also be set with on a per-file-basis with
  2147. #+STARTUP: logstatesreversed
  2148. #+STARTUP: nologstatesreversed"
  2149. :group 'org-todo
  2150. :group 'org-progress
  2151. :type 'boolean)
  2152. (defcustom org-todo-repeat-to-state nil
  2153. "The TODO state to which a repeater should return the repeating task.
  2154. By default this is the first task of a TODO sequence or the
  2155. previous state of a TYPE_TODO set. But you can specify to use
  2156. the previous state in a TODO sequence or a string.
  2157. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2158. entry, which has precedence over this option."
  2159. :group 'org-todo
  2160. :version "24.1"
  2161. :type '(choice (const :tag "Use the previous TODO state" t)
  2162. (const :tag "Use the head of the TODO sequence" nil)
  2163. (string :tag "Use a specific TODO state")))
  2164. (defcustom org-log-repeat 'time
  2165. "Non-nil means record moving through the DONE state when triggering repeat.
  2166. An auto-repeating task is immediately switched back to TODO when
  2167. marked DONE. If you are not logging state changes (by adding \"@\"
  2168. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2169. record a closing note, there will be no record of the task moving
  2170. through DONE. This variable forces taking a note anyway.
  2171. nil Don't force a record
  2172. time Record a time stamp
  2173. note Prompt for a note and add it with template `org-log-note-headings'
  2174. This option can also be set with on a per-file-basis with
  2175. #+STARTUP: nologrepeat
  2176. #+STARTUP: logrepeat
  2177. #+STARTUP: lognoterepeat
  2178. You can have local logging settings for a subtree by setting the LOGGING
  2179. property to one or more of these keywords."
  2180. :group 'org-todo
  2181. :group 'org-progress
  2182. :type '(choice
  2183. (const :tag "Don't force a record" nil)
  2184. (const :tag "Force recording the DONE state" time)
  2185. (const :tag "Force recording a note with the DONE state" note)))
  2186. (defcustom org-todo-repeat-hook nil
  2187. "Hook that is run after a task has been repeated."
  2188. :package-version '(Org . "9.2")
  2189. :group 'org-todo
  2190. :type 'hook)
  2191. (defgroup org-priorities nil
  2192. "Priorities in Org mode."
  2193. :tag "Org Priorities"
  2194. :group 'org-todo)
  2195. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  2196. (defcustom org-priority-enable-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. (defvaralias 'org-highest-priority 'org-priority-highest)
  2203. (defcustom org-priority-highest ?A
  2204. "The highest priority of TODO items.
  2205. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2206. Must be smaller than `org-priority-lowest'."
  2207. :group 'org-priorities
  2208. :type '(choice
  2209. (character :tag "Character")
  2210. (integer :tag "Integer (< 65)")))
  2211. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  2212. (defcustom org-priority-lowest ?C
  2213. "The lowest priority of TODO items.
  2214. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2215. Must be higher than `org-priority-highest'."
  2216. :group 'org-priorities
  2217. :type '(choice
  2218. (character :tag "Character")
  2219. (integer :tag "Integer (< 65)")))
  2220. (defvaralias 'org-default-priority 'org-priority-default)
  2221. (defcustom org-priority-default ?B
  2222. "The default priority of TODO items.
  2223. This is the priority an item gets if no explicit priority is given.
  2224. When starting to cycle on an empty priority the first step in the cycle
  2225. depends on `org-priority-start-cycle-with-default'. The resulting first
  2226. step priority must not exceed the range from `org-priority-highest' to
  2227. `org-priority-lowest' which means that `org-priority-default' has to be
  2228. in this range exclusive or inclusive to the range boundaries. Else the
  2229. first step refuses to set the default and the second will fall back on
  2230. (depending on the command used) the highest or lowest priority."
  2231. :group 'org-priorities
  2232. :type '(choice
  2233. (character :tag "Character")
  2234. (integer :tag "Integer (< 65)")))
  2235. (defcustom org-priority-start-cycle-with-default t
  2236. "Non-nil means start with default priority when starting to cycle.
  2237. When this is nil, the first step in the cycle will be (depending on the
  2238. command used) one higher or lower than the default priority.
  2239. See also `org-priority-default'."
  2240. :group 'org-priorities
  2241. :type 'boolean)
  2242. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2243. (defcustom org-priority-get-priority-function nil
  2244. "Function to extract the priority from a string.
  2245. The string is normally the headline. If this is nil, Org
  2246. computes the priority from the priority cookie like [#A] in the
  2247. headline. It returns an integer, increasing by 1000 for each
  2248. priority level.
  2249. The user can set a different function here, which should take a
  2250. string as an argument and return the numeric priority."
  2251. :group 'org-priorities
  2252. :version "24.1"
  2253. :type '(choice
  2254. (const nil)
  2255. (function)))
  2256. (defgroup org-time nil
  2257. "Options concerning time stamps and deadlines in Org mode."
  2258. :tag "Org Time"
  2259. :group 'org)
  2260. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2261. "Number of minutes to round time stamps to.
  2262. \\<org-mode-map>\
  2263. These are two values, the first applies when first creating a time stamp.
  2264. The second applies when changing it with the commands `S-up' and `S-down'.
  2265. When changing the time stamp, this means that it will change in steps
  2266. of N minutes, as given by the second value.
  2267. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2268. numbers should be factors of 60, so for example 5, 10, 15.
  2269. When this is larger than 1, you can still force an exact time stamp by using
  2270. a double prefix argument to a time stamp command like \
  2271. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2272. and by using a prefix arg to `S-up/down' to specify the exact number
  2273. of minutes to shift."
  2274. :group 'org-time
  2275. :get (lambda (var) ; Make sure both elements are there
  2276. (if (integerp (default-value var))
  2277. (list (default-value var) 5)
  2278. (default-value var)))
  2279. :type '(list
  2280. (integer :tag "when inserting times")
  2281. (integer :tag "when modifying times")))
  2282. ;; Normalize old customizations of this variable.
  2283. (when (integerp org-time-stamp-rounding-minutes)
  2284. (setq org-time-stamp-rounding-minutes
  2285. (list org-time-stamp-rounding-minutes
  2286. org-time-stamp-rounding-minutes)))
  2287. (defcustom org-display-custom-times nil
  2288. "Non-nil means overlay custom formats over all time stamps.
  2289. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2290. To turn this on on a per-file basis, insert anywhere in the file:
  2291. #+STARTUP: customtime"
  2292. :group 'org-time
  2293. :set 'set-default
  2294. :type 'sexp)
  2295. (make-variable-buffer-local 'org-display-custom-times)
  2296. (defcustom org-time-stamp-custom-formats
  2297. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2298. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2299. These are overlaid over the default ISO format if the variable
  2300. `org-display-custom-times' is set. Time like %H:%M should be at the
  2301. end of the second format. The custom formats are also honored by export
  2302. commands, if custom time display is turned on at the time of export."
  2303. :group 'org-time
  2304. :type 'sexp)
  2305. (defun org-time-stamp-format (&optional long inactive)
  2306. "Get the right format for a time string."
  2307. (let ((f (if long (cdr org-time-stamp-formats)
  2308. (car org-time-stamp-formats))))
  2309. (if inactive
  2310. (concat "[" (substring f 1 -1) "]")
  2311. f)))
  2312. (defcustom org-deadline-warning-days 14
  2313. "Number of days before expiration during which a deadline becomes active.
  2314. This variable governs the display in sparse trees and in the agenda.
  2315. When 0 or negative, it means use this number (the absolute value of it)
  2316. even if a deadline has a different individual lead time specified.
  2317. Custom commands can set this variable in the options section."
  2318. :group 'org-time
  2319. :group 'org-agenda-daily/weekly
  2320. :type 'integer)
  2321. (defcustom org-scheduled-delay-days 0
  2322. "Number of days before a scheduled item becomes active.
  2323. This variable governs the display in sparse trees and in the agenda.
  2324. The default value (i.e. 0) means: don't delay scheduled item.
  2325. When negative, it means use this number (the absolute value of it)
  2326. even if a scheduled item has a different individual delay time
  2327. specified.
  2328. Custom commands can set this variable in the options section."
  2329. :group 'org-time
  2330. :group 'org-agenda-daily/weekly
  2331. :version "24.4"
  2332. :package-version '(Org . "8.0")
  2333. :type 'integer)
  2334. (defcustom org-read-date-prefer-future t
  2335. "Non-nil means assume future for incomplete date input from user.
  2336. This affects the following situations:
  2337. 1. The user gives a month but not a year.
  2338. For example, if it is April and you enter \"feb 2\", this will be read
  2339. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2340. 2. The user gives a day, but no month.
  2341. For example, if today is the 15th, and you enter \"3\", Org will read
  2342. this as the third of *next* month. However, if you enter \"17\",
  2343. it will be considered as *this* month.
  2344. If you set this variable to the symbol `time', then also the following
  2345. will work:
  2346. 3. If the user gives a time.
  2347. If the time is before now, it will be interpreted as tomorrow.
  2348. Currently none of this works for ISO week specifications.
  2349. When this option is nil, the current day, month and year will always be
  2350. used as defaults.
  2351. See also `org-agenda-jump-prefer-future'."
  2352. :group 'org-time
  2353. :type '(choice
  2354. (const :tag "Never" nil)
  2355. (const :tag "Check month and day" t)
  2356. (const :tag "Check month, day, and time" time)))
  2357. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2358. "Should the agenda jump command prefer the future for incomplete dates?
  2359. The default is to do the same as configured in `org-read-date-prefer-future'.
  2360. But you can also set a deviating value here.
  2361. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2362. :group 'org-agenda
  2363. :group 'org-time
  2364. :version "24.1"
  2365. :type '(choice
  2366. (const :tag "Use org-read-date-prefer-future"
  2367. org-read-date-prefer-future)
  2368. (const :tag "Never" nil)
  2369. (const :tag "Always" t)))
  2370. (defcustom org-read-date-force-compatible-dates t
  2371. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2372. Depending on the system Emacs is running on, certain dates cannot
  2373. be represented with the type used internally to represent time.
  2374. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2375. correctly. Some systems allow for earlier dates, some for later,
  2376. some for both. One way to find out is to insert any date into an
  2377. Org buffer, putting the cursor on the year and hitting S-up and
  2378. S-down to test the range.
  2379. When this variable is set to t, the date/time prompt will not let
  2380. you specify dates outside the 1970-2037 range, so it is certain that
  2381. these dates will work in whatever version of Emacs you are
  2382. running, and also that you can move a file from one Emacs implementation
  2383. to another. Whenever Org is forcing the year for you, it will display
  2384. a message and beep.
  2385. When this variable is nil, Org will check if the date is
  2386. representable in the specific Emacs implementation you are using.
  2387. If not, it will force a year, usually the current year, and beep
  2388. to remind you. Currently this setting is not recommended because
  2389. the likelihood that you will open your Org files in an Emacs that
  2390. has limited date range is not negligible.
  2391. A workaround for this problem is to use diary sexp dates for time
  2392. stamps outside of this range."
  2393. :group 'org-time
  2394. :version "24.1"
  2395. :type 'boolean)
  2396. (defcustom org-read-date-display-live t
  2397. "Non-nil means display current interpretation of date prompt live.
  2398. This display will be in an overlay, in the minibuffer."
  2399. :group 'org-time
  2400. :type 'boolean)
  2401. (defvaralias 'org-popup-calendar-for-date-prompt
  2402. 'org-read-date-popup-calendar)
  2403. (defcustom org-read-date-popup-calendar t
  2404. "Non-nil means pop up a calendar when prompting for a date.
  2405. In the calendar, the date can be selected with mouse-1. However, the
  2406. minibuffer will also be active, and you can simply enter the date as well.
  2407. When nil, only the minibuffer will be available."
  2408. :group 'org-time
  2409. :type 'boolean)
  2410. (defcustom org-extend-today-until 0
  2411. "The hour when your day really ends. Must be an integer.
  2412. This has influence for the following applications:
  2413. - When switching the agenda to \"today\". If it is still earlier than
  2414. the time given here, the day recognized as TODAY is actually yesterday.
  2415. - When a date is read from the user and it is still before the time given
  2416. here, the current date and time will be assumed to be yesterday, 23:59.
  2417. Also, timestamps inserted in capture templates follow this rule.
  2418. IMPORTANT: This is a feature whose implementation is and likely will
  2419. remain incomplete. Really, it is only here because past midnight seems to
  2420. be the favorite working time of John Wiegley :-)"
  2421. :group 'org-time
  2422. :type 'integer)
  2423. (defcustom org-use-effective-time nil
  2424. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2425. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2426. \"effective time\" of any timestamps between midnight and 8am will be
  2427. 23:59 of the previous day."
  2428. :group 'org-time
  2429. :version "24.1"
  2430. :type 'boolean)
  2431. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2432. "When non-nil, use the last clock out time for `org-todo'.
  2433. Note that this option has precedence over the combined use of
  2434. `org-use-effective-time' and `org-extend-today-until'."
  2435. :group 'org-time
  2436. :version "24.4"
  2437. :package-version '(Org . "8.0")
  2438. :type 'boolean)
  2439. (defcustom org-edit-timestamp-down-means-later nil
  2440. "Non-nil means S-down will increase the time in a time stamp.
  2441. When nil, S-up will increase."
  2442. :group 'org-time
  2443. :type 'boolean)
  2444. (defcustom org-calendar-follow-timestamp-change t
  2445. "Non-nil means make the calendar window follow timestamp changes.
  2446. When a timestamp is modified and the calendar window is visible, it will be
  2447. moved to the new date."
  2448. :group 'org-time
  2449. :type 'boolean)
  2450. (defgroup org-tags nil
  2451. "Options concerning tags in Org mode."
  2452. :tag "Org Tags"
  2453. :group 'org)
  2454. (defcustom org-tag-alist nil
  2455. "Default tags available in Org files.
  2456. The value of this variable is an alist. Associations either:
  2457. (TAG)
  2458. (TAG . SELECT)
  2459. (SPECIAL)
  2460. where TAG is a tag as a string, SELECT is character, used to
  2461. select that tag through the fast tag selection interface, and
  2462. SPECIAL is one of the following keywords: `:startgroup',
  2463. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2464. `:newline'. These keywords are used to define a hierarchy of
  2465. tags. See manual for details.
  2466. When this variable is nil, Org mode bases tag input on what is
  2467. already in the buffer. The value can be overridden locally by
  2468. using a TAGS keyword, e.g.,
  2469. #+TAGS: tag1 tag2
  2470. See also `org-tag-persistent-alist' to sidestep this behavior."
  2471. :group 'org-tags
  2472. :type '(repeat
  2473. (choice
  2474. (cons :tag "Tag with key"
  2475. (string :tag "Tag name")
  2476. (character :tag "Access char"))
  2477. (list :tag "Tag" (string :tag "Tag name"))
  2478. (const :tag "Start radio group" (:startgroup))
  2479. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2480. (const :tag "Group tags delimiter" (:grouptags))
  2481. (const :tag "End radio group" (:endgroup))
  2482. (const :tag "End tag group, non distinct" (:endgrouptag))
  2483. (const :tag "New line" (:newline)))))
  2484. (defcustom org-tag-persistent-alist nil
  2485. "Tags always available in Org files.
  2486. The value of this variable is an alist. Associations either:
  2487. (TAG)
  2488. (TAG . SELECT)
  2489. (SPECIAL)
  2490. where TAG is a tag as a string, SELECT is a character, used to
  2491. select that tag through the fast tag selection interface, and
  2492. SPECIAL is one of the following keywords: `:startgroup',
  2493. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2494. `:newline'. These keywords are used to define a hierarchy of
  2495. tags. See manual for details.
  2496. Unlike to `org-tag-alist', tags defined in this variable do not
  2497. depend on a local TAGS keyword. Instead, to disable these tags
  2498. on a per-file basis, insert anywhere in the file:
  2499. #+STARTUP: noptag"
  2500. :group 'org-tags
  2501. :type '(repeat
  2502. (choice
  2503. (cons :tag "Tag with key"
  2504. (string :tag "Tag name")
  2505. (character :tag "Access char"))
  2506. (list :tag "Tag" (string :tag "Tag name"))
  2507. (const :tag "Start radio group" (:startgroup))
  2508. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2509. (const :tag "Group tags delimiter" (:grouptags))
  2510. (const :tag "End radio group" (:endgroup))
  2511. (const :tag "End tag group, non distinct" (:endgrouptag))
  2512. (const :tag "New line" (:newline)))))
  2513. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2514. "If non-nil, always offer completion for all tags of all agenda files.
  2515. Setting this variable locally allows for dynamic generation of tag
  2516. completions in capture buffers.
  2517. (add-hook \\='org-capture-mode-hook
  2518. (lambda ()
  2519. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2520. :group 'org-tags
  2521. :version "24.1"
  2522. :type 'boolean)
  2523. (defvar org-file-tags nil
  2524. "List of tags that can be inherited by all entries in the file.
  2525. The tags will be inherited if the variable `org-use-tag-inheritance'
  2526. says they should be.
  2527. This variable is populated from #+FILETAGS lines.")
  2528. (defcustom org-use-fast-tag-selection 'auto
  2529. "Non-nil means use fast tag selection scheme.
  2530. This is a special interface to select and deselect tags with single keys.
  2531. When nil, fast selection is never used.
  2532. When the symbol `auto', fast selection is used if and only if selection
  2533. characters for tags have been configured, either through the variable
  2534. `org-tag-alist' or through a #+TAGS line in the buffer.
  2535. When t, fast selection is always used and selection keys are assigned
  2536. automatically if necessary."
  2537. :group 'org-tags
  2538. :type '(choice
  2539. (const :tag "Always" t)
  2540. (const :tag "Never" nil)
  2541. (const :tag "When selection characters are configured" auto)))
  2542. (defcustom org-fast-tag-selection-single-key nil
  2543. "Non-nil means fast tag selection exits after first change.
  2544. When nil, you have to press RET to exit it.
  2545. During fast tag selection, you can toggle this flag with `C-c'.
  2546. This variable can also have the value `expert'. In this case, the window
  2547. displaying the tags menu is not even shown, until you press C-c again."
  2548. :group 'org-tags
  2549. :type '(choice
  2550. (const :tag "No" nil)
  2551. (const :tag "Yes" t)
  2552. (const :tag "Expert" expert)))
  2553. (defvar org-fast-tag-selection-include-todo nil
  2554. "Non-nil means fast tags selection interface will also offer TODO states.
  2555. This is an undocumented feature, you should not rely on it.")
  2556. (defcustom org-tags-column -77
  2557. "The column to which tags should be indented in a headline.
  2558. If this number is positive, it specifies the column. If it is negative,
  2559. it means that the tags should be flushright to that column. For example,
  2560. -80 works well for a normal 80 character screen.
  2561. When 0, place tags directly after headline text, with only one space in
  2562. between."
  2563. :group 'org-tags
  2564. :type 'integer)
  2565. (defcustom org-auto-align-tags t
  2566. "Non-nil keeps tags aligned when modifying headlines.
  2567. Some operations (i.e. demoting) change the length of a headline and
  2568. therefore shift the tags around. With this option turned on, after
  2569. each such operation the tags are again aligned to `org-tags-column'."
  2570. :group 'org-tags
  2571. :type 'boolean)
  2572. (defcustom org-use-tag-inheritance t
  2573. "Non-nil means tags in levels apply also for sublevels.
  2574. When nil, only the tags directly given in a specific line apply there.
  2575. This may also be a list of tags that should be inherited, or a regexp that
  2576. matches tags that should be inherited. Additional control is possible
  2577. with the variable `org-tags-exclude-from-inheritance' which gives an
  2578. explicit list of tags to be excluded from inheritance, even if the value of
  2579. `org-use-tag-inheritance' would select it for inheritance.
  2580. If this option is t, a match early-on in a tree can lead to a large
  2581. number of matches in the subtree when constructing the agenda or creating
  2582. a sparse tree. If you only want to see the first match in a tree during
  2583. a search, check out the variable `org-tags-match-list-sublevels'."
  2584. :group 'org-tags
  2585. :type '(choice
  2586. (const :tag "Not" nil)
  2587. (const :tag "Always" t)
  2588. (repeat :tag "Specific tags" (string :tag "Tag"))
  2589. (regexp :tag "Tags matched by regexp")))
  2590. (defcustom org-tags-exclude-from-inheritance nil
  2591. "List of tags that should never be inherited.
  2592. This is a way to exclude a few tags from inheritance. For way to do
  2593. the opposite, to actively allow inheritance for selected tags,
  2594. see the variable `org-use-tag-inheritance'."
  2595. :group 'org-tags
  2596. :type '(repeat (string :tag "Tag")))
  2597. (defun org-tag-inherit-p (tag)
  2598. "Check if TAG is one that should be inherited."
  2599. (cond
  2600. ((member tag org-tags-exclude-from-inheritance) nil)
  2601. ((eq org-use-tag-inheritance t) t)
  2602. ((not org-use-tag-inheritance) nil)
  2603. ((stringp org-use-tag-inheritance)
  2604. (string-match org-use-tag-inheritance tag))
  2605. ((listp org-use-tag-inheritance)
  2606. (member tag org-use-tag-inheritance))
  2607. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2608. (defcustom org-tags-match-list-sublevels t
  2609. "Non-nil means list also sublevels of headlines matching a search.
  2610. This variable applies to tags/property searches, and also to stuck
  2611. projects because this search is based on a tags match as well.
  2612. When set to the symbol `indented', sublevels are indented with
  2613. leading dots.
  2614. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2615. the sublevels of a headline matching a tag search often also match
  2616. the same search. Listing all of them can create very long lists.
  2617. Setting this variable to nil causes subtrees of a match to be skipped.
  2618. This variable is semi-obsolete and probably should always be true. It
  2619. is better to limit inheritance to certain tags using the variables
  2620. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2621. :group 'org-tags
  2622. :type '(choice
  2623. (const :tag "No, don't list them" nil)
  2624. (const :tag "Yes, do list them" t)
  2625. (const :tag "List them, indented with leading dots" indented)))
  2626. (defcustom org-tags-sort-function nil
  2627. "When set, tags are sorted using this function as a comparator."
  2628. :group 'org-tags
  2629. :type '(choice
  2630. (const :tag "No sorting" nil)
  2631. (const :tag "Alphabetical" org-string-collate-lessp)
  2632. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2633. (function :tag "Custom function" nil)))
  2634. (defvar org-tags-history nil
  2635. "History of minibuffer reads for tags.")
  2636. (defvar org-last-tags-completion-table nil
  2637. "The last used completion table for tags.")
  2638. (defvar org-after-tags-change-hook nil
  2639. "Hook that is run after the tags in a line have changed.")
  2640. (defgroup org-properties nil
  2641. "Options concerning properties in Org mode."
  2642. :tag "Org Properties"
  2643. :group 'org)
  2644. (defcustom org-property-format "%-10s %s"
  2645. "How property key/value pairs should be formatted by `indent-line'.
  2646. When `indent-line' hits a property definition, it will format the line
  2647. according to this format, mainly to make sure that the values are
  2648. lined-up with respect to each other."
  2649. :group 'org-properties
  2650. :type 'string)
  2651. (defcustom org-properties-postprocess-alist nil
  2652. "Alist of properties and functions to adjust inserted values.
  2653. Elements of this alist must be of the form
  2654. ([string] [function])
  2655. where [string] must be a property name and [function] must be a
  2656. lambda expression: this lambda expression must take one argument,
  2657. the value to adjust, and return the new value as a string.
  2658. For example, this element will allow the property \"Remaining\"
  2659. to be updated wrt the relation between the \"Effort\" property
  2660. and the clock summary:
  2661. ((\"Remaining\" (lambda(value)
  2662. (let ((clocksum (org-clock-sum-current-item))
  2663. (effort (org-duration-to-minutes
  2664. (org-entry-get (point) \"Effort\"))))
  2665. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2666. :group 'org-properties
  2667. :version "24.1"
  2668. :type '(alist :key-type (string :tag "Property")
  2669. :value-type (function :tag "Function")))
  2670. (defcustom org-use-property-inheritance nil
  2671. "Non-nil means properties apply also for sublevels.
  2672. This setting is chiefly used during property searches. Turning it on can
  2673. cause significant overhead when doing a search, which is why it is not
  2674. on by default.
  2675. When nil, only the properties directly given in the current entry count.
  2676. When t, every property is inherited. The value may also be a list of
  2677. properties that should have inheritance, or a regular expression matching
  2678. properties that should be inherited.
  2679. However, note that some special properties use inheritance under special
  2680. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2681. and the properties ending in \"_ALL\" when they are used as descriptor
  2682. for valid values of a property.
  2683. Note for programmers:
  2684. When querying an entry with `org-entry-get', you can control if inheritance
  2685. should be used. By default, `org-entry-get' looks only at the local
  2686. properties. You can request inheritance by setting the inherit argument
  2687. to t (to force inheritance) or to `selective' (to respect the setting
  2688. in this variable)."
  2689. :group 'org-properties
  2690. :type '(choice
  2691. (const :tag "Not" nil)
  2692. (const :tag "Always" t)
  2693. (repeat :tag "Specific properties" (string :tag "Property"))
  2694. (regexp :tag "Properties matched by regexp")))
  2695. (defun org-property-inherit-p (property)
  2696. "Return a non-nil value if PROPERTY should be inherited."
  2697. (cond
  2698. ((eq org-use-property-inheritance t) t)
  2699. ((not org-use-property-inheritance) nil)
  2700. ((stringp org-use-property-inheritance)
  2701. (string-match org-use-property-inheritance property))
  2702. ((listp org-use-property-inheritance)
  2703. (member-ignore-case property org-use-property-inheritance))
  2704. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2705. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2706. "The default column format, if no other format has been defined.
  2707. This variable can be set on the per-file basis by inserting a line
  2708. #+COLUMNS: %25ITEM ....."
  2709. :group 'org-properties
  2710. :type 'string)
  2711. (defcustom org-columns-default-format-for-agenda nil
  2712. "The default column format in an agenda buffer.
  2713. This will be used for column view in the agenda unless a format has
  2714. been set by adding `org-overriding-columns-format' to the local
  2715. settings list of a custom agenda view. When nil, the columns format
  2716. for the first item in the agenda list will be used, or as a fall-back,
  2717. `org-columns-default-format'."
  2718. :group 'org-properties
  2719. :type '(choice
  2720. (const :tag "No default" nil)
  2721. (string :tag "Format string")))
  2722. (defcustom org-columns-ellipses ".."
  2723. "The ellipses to be used when a field in column view is truncated.
  2724. When this is the empty string, as many characters as possible are shown,
  2725. but then there will be no visual indication that the field has been truncated.
  2726. When this is a string of length N, the last N characters of a truncated
  2727. field are replaced by this string. If the column is narrower than the
  2728. ellipses string, only part of the ellipses string will be shown."
  2729. :group 'org-properties
  2730. :type 'string)
  2731. (defconst org-global-properties-fixed
  2732. '(("VISIBILITY_ALL" . "folded children content all")
  2733. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2734. "List of property/value pairs that can be inherited by any entry.
  2735. These are fixed values, for the preset properties. The user variable
  2736. that can be used to add to this list is `org-global-properties'.
  2737. The entries in this list are cons cells where the car is a property
  2738. name and cdr is a string with the value. If the value represents
  2739. multiple items like an \"_ALL\" property, separate the items by
  2740. spaces.")
  2741. (defcustom org-global-properties nil
  2742. "List of property/value pairs that can be inherited by any entry.
  2743. This list will be combined with the constant `org-global-properties-fixed'.
  2744. The entries in this list are cons cells where the car is a property
  2745. name and cdr is a string with the value.
  2746. Buffer local properties are added either by a document property drawer
  2747. :PROPERTIES:
  2748. :NAME: VALUE
  2749. :END:
  2750. or by adding lines like
  2751. #+PROPERTY: NAME VALUE"
  2752. :group 'org-properties
  2753. :type '(repeat
  2754. (cons (string :tag "Property")
  2755. (string :tag "Value"))))
  2756. (defvar-local org-keyword-properties nil
  2757. "List of property/value pairs inherited by any entry.
  2758. Valid for the current buffer. This variable is populated from
  2759. PROPERTY keywords.
  2760. Note that properties are defined also in property drawers.
  2761. Properties defined there take precedence over properties defined
  2762. as keywords.")
  2763. (defgroup org-agenda nil
  2764. "Options concerning agenda views in Org mode."
  2765. :tag "Org Agenda"
  2766. :group 'org)
  2767. (defvar-local org-category nil
  2768. "Variable used by Org files to set a category for agenda display.
  2769. There are multiple ways to set the category. One way is to set
  2770. it in the document property drawer. For example:
  2771. :PROPERTIES:
  2772. :CATEGORY: ELisp
  2773. :END:
  2774. Other ways to define it is as an emacs file variable, for example
  2775. # -*- mode: org; org-category: \"ELisp\"
  2776. or for the file to contain a special line:
  2777. #+CATEGORY: ELisp
  2778. If the file does not specify a category, then file's base name
  2779. is used instead.")
  2780. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2781. (defcustom org-agenda-files nil
  2782. "The files to be used for agenda display.
  2783. If an entry is a directory, all files in that directory that are matched
  2784. by `org-agenda-file-regexp' will be part of the file list.
  2785. If the value of the variable is not a list but a single file name, then
  2786. the list of agenda files is actually stored and maintained in that file,
  2787. one agenda file per line. In this file paths can be given relative to
  2788. `org-directory'. Tilde expansion and environment variable substitution
  2789. are also made.
  2790. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2791. and removed with `\\[org-remove-file]'."
  2792. :group 'org-agenda
  2793. :type '(choice
  2794. (repeat :tag "List of files and directories" file)
  2795. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2796. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2797. "Regular expression to match files for `org-agenda-files'.
  2798. If any element in the list in that variable contains a directory instead
  2799. of a normal file, all files in that directory that are matched by this
  2800. regular expression will be included."
  2801. :group 'org-agenda
  2802. :type 'regexp)
  2803. (defvaralias 'org-agenda-multi-occur-extra-files
  2804. 'org-agenda-text-search-extra-files)
  2805. (defcustom org-agenda-text-search-extra-files nil
  2806. "List of extra files to be searched by text search commands.
  2807. These files will be searched in addition to the agenda files by the
  2808. commands `org-search-view' (`\\[org-agenda] s') \
  2809. and `org-occur-in-agenda-files'.
  2810. Note that these files will only be searched for text search commands,
  2811. not for the other agenda views like todo lists, tag searches or the weekly
  2812. agenda. This variable is intended to list notes and possibly archive files
  2813. that should also be searched by these two commands.
  2814. In fact, if the first element in the list is the symbol `agenda-archives',
  2815. then all archive files of all agenda files will be added to the search
  2816. scope."
  2817. :group 'org-agenda
  2818. :type '(set :greedy t
  2819. (const :tag "Agenda Archives" agenda-archives)
  2820. (repeat :inline t (file))))
  2821. (defcustom org-agenda-skip-unavailable-files nil
  2822. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2823. A nil value means to remove them, after a query, from the list."
  2824. :group 'org-agenda
  2825. :type 'boolean)
  2826. (defcustom org-agenda-diary-file 'diary-file
  2827. "File to which to add new entries with the `i' key in agenda and calendar.
  2828. When this is the symbol `diary-file', the functionality in the Emacs
  2829. calendar will be used to add entries to the `diary-file'. But when this
  2830. points to a file, `org-agenda-diary-entry' will be used instead."
  2831. :group 'org-agenda
  2832. :type '(choice
  2833. (const :tag "The standard Emacs diary file" diary-file)
  2834. (file :tag "Special Org file diary entries")))
  2835. (defgroup org-latex nil
  2836. "Options for embedding LaTeX code into Org mode."
  2837. :tag "Org LaTeX"
  2838. :group 'org)
  2839. (defcustom org-format-latex-options
  2840. '(:foreground default :background default :scale 1.0
  2841. :html-foreground "Black" :html-background "Transparent"
  2842. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2843. "Options for creating images from LaTeX fragments.
  2844. This is a property list with the following properties:
  2845. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2846. `default' means use the foreground of the default face.
  2847. `auto' means use the foreground from the text face.
  2848. :background the background color, or \"Transparent\".
  2849. `default' means use the background of the default face.
  2850. `auto' means use the background from the text face.
  2851. :scale a scaling factor for the size of the images, to get more pixels
  2852. :html-foreground, :html-background, :html-scale
  2853. the same numbers for HTML export.
  2854. :matchers a list indicating which matchers should be used to
  2855. find LaTeX fragments. Valid members of this list are:
  2856. \"begin\" find environments
  2857. \"$1\" find single characters surrounded by $.$
  2858. \"$\" find math expressions surrounded by $...$
  2859. \"$$\" find math expressions surrounded by $$....$$
  2860. \"\\(\" find math expressions surrounded by \\(...\\)
  2861. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2862. :group 'org-latex
  2863. :type 'plist)
  2864. (defcustom org-format-latex-signal-error t
  2865. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2866. When nil, just push out a message."
  2867. :group 'org-latex
  2868. :version "24.1"
  2869. :type 'boolean)
  2870. (defcustom org-latex-to-mathml-jar-file nil
  2871. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2872. Use this to specify additional executable file say a jar file.
  2873. When using MathToWeb as the converter, specify the full-path to
  2874. your mathtoweb.jar file."
  2875. :group 'org-latex
  2876. :version "24.1"
  2877. :type '(choice
  2878. (const :tag "None" nil)
  2879. (file :tag "JAR file" :must-match t)))
  2880. (defcustom org-latex-to-mathml-convert-command nil
  2881. "Command to convert LaTeX fragments to MathML.
  2882. Replace format-specifiers in the command as noted below and use
  2883. `shell-command' to convert LaTeX to MathML.
  2884. %j: Executable file in fully expanded form as specified by
  2885. `org-latex-to-mathml-jar-file'.
  2886. %I: Input LaTeX file in fully expanded form.
  2887. %i: The latex fragment to be converted.
  2888. %o: Output MathML file.
  2889. This command is used by `org-create-math-formula'.
  2890. When using MathToWeb as the converter, set this option to
  2891. \"java -jar %j -unicode -force -df %o %I\".
  2892. When using LaTeXML set this option to
  2893. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2894. :group 'org-latex
  2895. :version "24.1"
  2896. :type '(choice
  2897. (const :tag "None" nil)
  2898. (string :tag "\nShell command")))
  2899. (defcustom org-preview-latex-default-process 'dvipng
  2900. "The default process to convert LaTeX fragments to image files.
  2901. All available processes and theirs documents can be found in
  2902. `org-preview-latex-process-alist', which see."
  2903. :group 'org-latex
  2904. :version "26.1"
  2905. :package-version '(Org . "9.0")
  2906. :type 'symbol)
  2907. (defcustom org-preview-latex-process-alist
  2908. '((dvipng
  2909. :programs ("latex" "dvipng")
  2910. :description "dvi > png"
  2911. :message "you need to install the programs: latex and dvipng."
  2912. :image-input-type "dvi"
  2913. :image-output-type "png"
  2914. :image-size-adjust (1.0 . 1.0)
  2915. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2916. :image-converter ("dvipng -D %D -T tight -o %O %f"))
  2917. (dvisvgm
  2918. :programs ("latex" "dvisvgm")
  2919. :description "dvi > svg"
  2920. :message "you need to install the programs: latex and dvisvgm."
  2921. :image-input-type "dvi"
  2922. :image-output-type "svg"
  2923. :image-size-adjust (1.7 . 1.5)
  2924. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2925. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2926. (imagemagick
  2927. :programs ("latex" "convert")
  2928. :description "pdf > png"
  2929. :message "you need to install the programs: latex and imagemagick."
  2930. :image-input-type "pdf"
  2931. :image-output-type "png"
  2932. :image-size-adjust (1.0 . 1.0)
  2933. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2934. :image-converter
  2935. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2936. "Definitions of external processes for LaTeX previewing.
  2937. Org mode can use some external commands to generate TeX snippet's images for
  2938. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2939. `org-create-formula-image' how to call them.
  2940. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2941. PROPERTIES accepts the following attributes:
  2942. :programs list of strings, required programs.
  2943. :description string, describe the process.
  2944. :message string, message it when required programs cannot be found.
  2945. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2946. :image-output-type string, output file type of image converter (e.g., \"png\").
  2947. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2948. image size showed in buffer and the cdr element is for
  2949. HTML file. This option is only useful for process
  2950. developers, users should use variable
  2951. `org-format-latex-options' instead.
  2952. :post-clean list of strings, files matched are to be cleaned up once
  2953. the image is generated. When nil, the files with \".dvi\",
  2954. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2955. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2956. be cleaned up.
  2957. :latex-header list of strings, the LaTeX header of the snippet file.
  2958. When nil, the fallback value is used instead, which is
  2959. controlled by `org-format-latex-header',
  2960. `org-latex-default-packages-alist' and
  2961. `org-latex-packages-alist', which see.
  2962. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2963. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2964. replaced with values defined below.
  2965. :image-converter list of image converter commands strings. Each of them is
  2966. given to the shell and supports any of the following
  2967. place-holders defined below.
  2968. Place-holders used by `:image-converter' and `:latex-compiler':
  2969. %f input file name
  2970. %b base name of input file
  2971. %o base directory of input file
  2972. %O absolute output file name
  2973. Place-holders only used by `:image-converter':
  2974. %D dpi, which is used to adjust image size by some processing commands.
  2975. %S the image size scale ratio, which is used to adjust image size by some
  2976. processing commands."
  2977. :group 'org-latex
  2978. :version "26.1"
  2979. :package-version '(Org . "9.0")
  2980. :type '(alist :tag "LaTeX to image backends"
  2981. :value-type (plist)))
  2982. (defcustom org-preview-latex-image-directory "ltximg/"
  2983. "Path to store latex preview images.
  2984. A relative path here creates many directories relative to the
  2985. processed Org files paths. An absolute path puts all preview
  2986. images at the same place."
  2987. :group 'org-latex
  2988. :version "26.1"
  2989. :package-version '(Org . "9.0")
  2990. :type 'string)
  2991. (defun org-format-latex-mathml-available-p ()
  2992. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2993. (save-match-data
  2994. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2995. org-latex-to-mathml-convert-command)
  2996. (let ((executable (car (split-string
  2997. org-latex-to-mathml-convert-command))))
  2998. (when (executable-find executable)
  2999. (if (string-match
  3000. "%j" org-latex-to-mathml-convert-command)
  3001. (file-readable-p org-latex-to-mathml-jar-file)
  3002. t))))))
  3003. (defcustom org-format-latex-header "\\documentclass{article}
  3004. \\usepackage[usenames]{color}
  3005. \[PACKAGES]
  3006. \[DEFAULT-PACKAGES]
  3007. \\pagestyle{empty} % do not remove
  3008. % The settings below are copied from fullpage.sty
  3009. \\setlength{\\textwidth}{\\paperwidth}
  3010. \\addtolength{\\textwidth}{-3cm}
  3011. \\setlength{\\oddsidemargin}{1.5cm}
  3012. \\addtolength{\\oddsidemargin}{-2.54cm}
  3013. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3014. \\setlength{\\textheight}{\\paperheight}
  3015. \\addtolength{\\textheight}{-\\headheight}
  3016. \\addtolength{\\textheight}{-\\headsep}
  3017. \\addtolength{\\textheight}{-\\footskip}
  3018. \\addtolength{\\textheight}{-3cm}
  3019. \\setlength{\\topmargin}{1.5cm}
  3020. \\addtolength{\\topmargin}{-2.54cm}"
  3021. "The document header used for processing LaTeX fragments.
  3022. It is imperative that this header make sure that no page number
  3023. appears on the page. The package defined in the variables
  3024. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3025. will either replace the placeholder \"[PACKAGES]\" in this
  3026. header, or they will be appended."
  3027. :group 'org-latex
  3028. :type 'string)
  3029. (defun org-set-packages-alist (var val)
  3030. "Set the packages alist and make sure it has 3 elements per entry."
  3031. (set var (mapcar (lambda (x)
  3032. (if (and (consp x) (= (length x) 2))
  3033. (list (car x) (nth 1 x) t)
  3034. x))
  3035. val)))
  3036. (defun org-get-packages-alist (var)
  3037. "Get the packages alist and make sure it has 3 elements per entry."
  3038. (mapcar (lambda (x)
  3039. (if (and (consp x) (= (length x) 2))
  3040. (list (car x) (nth 1 x) t)
  3041. x))
  3042. (default-value var)))
  3043. (defcustom org-latex-default-packages-alist
  3044. '(("AUTO" "inputenc" t ("pdflatex"))
  3045. ("T1" "fontenc" t ("pdflatex"))
  3046. ("" "graphicx" t)
  3047. ("" "grffile" t)
  3048. ("" "longtable" nil)
  3049. ("" "wrapfig" nil)
  3050. ("" "rotating" nil)
  3051. ("normalem" "ulem" t)
  3052. ("" "amsmath" t)
  3053. ("" "textcomp" t)
  3054. ("" "amssymb" t)
  3055. ("" "capt-of" nil)
  3056. ("" "hyperref" nil))
  3057. "Alist of default packages to be inserted in the header.
  3058. Change this only if one of the packages here causes an
  3059. incompatibility with another package you are using.
  3060. The packages in this list are needed by one part or another of
  3061. Org mode to function properly:
  3062. - inputenc, fontenc: for basic font and character selection
  3063. - graphicx: for including images
  3064. - grffile: allow periods and spaces in graphics file names
  3065. - longtable: For multipage tables
  3066. - wrapfig: for figure placement
  3067. - rotating: for sideways figures and tables
  3068. - ulem: for underline and strike-through
  3069. - amsmath: for subscript and superscript and math environments
  3070. - textcomp, amssymb: for various symbols used
  3071. for interpreting the entities in `org-entities'. You can skip
  3072. some of these packages if you don't use any of their symbols.
  3073. - capt-of: for captions outside of floats
  3074. - hyperref: for cross references
  3075. Therefore you should not modify this variable unless you know
  3076. what you are doing. The one reason to change it anyway is that
  3077. you might be loading some other package that conflicts with one
  3078. of the default packages. Each element is either a cell or
  3079. a string.
  3080. A cell is of the format
  3081. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3082. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3083. when compiling LaTeX snippets into images for inclusion into
  3084. non-LaTeX output.
  3085. COMPILERS is a list of compilers that should include the package,
  3086. see `org-latex-compiler'. If the document compiler is not in the
  3087. list, and the list is non-nil, the package will not be inserted
  3088. in the final document.
  3089. A string will be inserted as-is in the header of the document."
  3090. :group 'org-latex
  3091. :group 'org-export-latex
  3092. :set 'org-set-packages-alist
  3093. :get 'org-get-packages-alist
  3094. :version "26.1"
  3095. :package-version '(Org . "8.3")
  3096. :type '(repeat
  3097. (choice
  3098. (list :tag "options/package pair"
  3099. (string :tag "options")
  3100. (string :tag "package")
  3101. (boolean :tag "Snippet")
  3102. (choice
  3103. (const :tag "For all compilers" nil)
  3104. (repeat :tag "Allowed compiler" string)))
  3105. (string :tag "A line of LaTeX"))))
  3106. (defcustom org-latex-packages-alist nil
  3107. "Alist of packages to be inserted in every LaTeX header.
  3108. These will be inserted after `org-latex-default-packages-alist'.
  3109. Each element is either a cell or a string.
  3110. A cell is of the format:
  3111. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3112. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3113. needed when turning LaTeX snippets into images for inclusion into
  3114. non-LaTeX output.
  3115. COMPILERS is a list of compilers that should include the package,
  3116. see `org-latex-compiler'. If the document compiler is not in the
  3117. list, and the list is non-nil, the package will not be inserted
  3118. in the final document.
  3119. A string will be inserted as-is in the header of the document.
  3120. Make sure that you only list packages here which:
  3121. - you want in every file;
  3122. - do not conflict with the setup in `org-format-latex-header';
  3123. - do not conflict with the default packages in
  3124. `org-latex-default-packages-alist'."
  3125. :group 'org-latex
  3126. :group 'org-export-latex
  3127. :set 'org-set-packages-alist
  3128. :get 'org-get-packages-alist
  3129. :type '(repeat
  3130. (choice
  3131. (list :tag "options/package pair"
  3132. (string :tag "options")
  3133. (string :tag "package")
  3134. (boolean :tag "Snippet"))
  3135. (string :tag "A line of LaTeX"))))
  3136. (defgroup org-appearance nil
  3137. "Settings for Org mode appearance."
  3138. :tag "Org Appearance"
  3139. :group 'org)
  3140. (defcustom org-level-color-stars-only nil
  3141. "Non-nil means fontify only the stars in each headline.
  3142. When nil, the entire headline is fontified.
  3143. Changing it requires restart of `font-lock-mode' to become effective
  3144. also in regions already fontified."
  3145. :group 'org-appearance
  3146. :type 'boolean)
  3147. (defcustom org-hide-leading-stars nil
  3148. "Non-nil means hide the first N-1 stars in a headline.
  3149. This works by using the face `org-hide' for these stars. This
  3150. face is white for a light background, and black for a dark
  3151. background. You may have to customize the face `org-hide' to
  3152. make this work.
  3153. Changing it requires restart of `font-lock-mode' to become effective
  3154. also in regions already fontified.
  3155. You may also set this on a per-file basis by adding one of the following
  3156. lines to the buffer:
  3157. #+STARTUP: hidestars
  3158. #+STARTUP: showstars"
  3159. :group 'org-appearance
  3160. :type 'boolean)
  3161. (defcustom org-hidden-keywords nil
  3162. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3163. For example, a value \\='(title) for this list makes the document's title
  3164. appear in the buffer without the initial \"#+TITLE:\" part."
  3165. :group 'org-appearance
  3166. :version "24.1"
  3167. :type '(set (const :tag "#+AUTHOR" author)
  3168. (const :tag "#+DATE" date)
  3169. (const :tag "#+EMAIL" email)
  3170. (const :tag "#+TITLE" title)))
  3171. (defcustom org-custom-properties nil
  3172. "List of properties (as strings) with a special meaning.
  3173. The default use of these custom properties is to let the user
  3174. hide them with `org-toggle-custom-properties-visibility'."
  3175. :group 'org-properties
  3176. :group 'org-appearance
  3177. :version "24.3"
  3178. :type '(repeat (string :tag "Property Name")))
  3179. (defcustom org-fontify-todo-headline nil
  3180. "Non-nil means change the face of a headline if it is marked as TODO.
  3181. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3182. When this is non-nil, the headline after the keyword is set to the
  3183. `org-headline-todo' as an additional indication."
  3184. :group 'org-appearance
  3185. :package-version '(Org . "9.4")
  3186. :type 'boolean
  3187. :safe t)
  3188. (defcustom org-fontify-done-headline nil
  3189. "Non-nil means change the face of a headline if it is marked DONE.
  3190. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3191. When this is non-nil, the headline after the keyword is set to the
  3192. `org-headline-done' as an additional indication."
  3193. :group 'org-appearance
  3194. :type 'boolean)
  3195. (defcustom org-fontify-emphasized-text t
  3196. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3197. Changing this variable requires a restart of Emacs to take effect."
  3198. :group 'org-appearance
  3199. :type 'boolean)
  3200. (defcustom org-fontify-whole-heading-line nil
  3201. "Non-nil means fontify the whole line for headings.
  3202. This is useful when setting a background color for the
  3203. org-level-* faces."
  3204. :group 'org-appearance
  3205. :type 'boolean)
  3206. (defcustom org-fontify-whole-block-delimiter-line t
  3207. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3208. This is useful when setting a background color for the
  3209. org-block-begin-line and org-block-end-line faces."
  3210. :group 'org-appearance
  3211. :type 'boolean)
  3212. (defcustom org-highlight-latex-and-related nil
  3213. "Non-nil means highlight LaTeX related syntax in the buffer.
  3214. When non-nil, the value should be a list containing any of the
  3215. following symbols:
  3216. `native' Highlight LaTeX snippets and environments natively.
  3217. `latex' Highlight LaTeX snippets and environments.
  3218. `script' Highlight subscript and superscript.
  3219. `entities' Highlight entities."
  3220. :group 'org-appearance
  3221. :version "24.4"
  3222. :package-version '(Org . "8.0")
  3223. :type '(choice
  3224. (const :tag "No highlighting" nil)
  3225. (set :greedy t :tag "Highlight"
  3226. (const :tag "LaTeX snippets and environments (native)" native)
  3227. (const :tag "LaTeX snippets and environments" latex)
  3228. (const :tag "Subscript and superscript" script)
  3229. (const :tag "Entities" entities))))
  3230. (defcustom org-hide-emphasis-markers nil
  3231. "Non-nil mean font-lock should hide the emphasis marker characters."
  3232. :group 'org-appearance
  3233. :type 'boolean
  3234. :safe #'booleanp)
  3235. (defcustom org-hide-macro-markers nil
  3236. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3237. :group 'org-appearance
  3238. :type 'boolean)
  3239. (defcustom org-pretty-entities nil
  3240. "Non-nil means show entities as UTF8 characters.
  3241. When nil, the \\name form remains in the buffer."
  3242. :group 'org-appearance
  3243. :version "24.1"
  3244. :type 'boolean)
  3245. (defcustom org-pretty-entities-include-sub-superscripts t
  3246. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3247. :group 'org-appearance
  3248. :version "24.1"
  3249. :type 'boolean)
  3250. (defvar org-emph-re nil
  3251. "Regular expression for matching emphasis.
  3252. After a match, the match groups contain these elements:
  3253. 0 The match of the full regular expression, including the characters
  3254. before and after the proper match
  3255. 1 The character before the proper match, or empty at beginning of line
  3256. 2 The proper match, including the leading and trailing markers
  3257. 3 The leading marker like * or /, indicating the type of highlighting
  3258. 4 The text between the emphasis markers, not including the markers
  3259. 5 The character after the match, empty at the end of a line")
  3260. (defvar org-verbatim-re nil
  3261. "Regular expression for matching verbatim text.")
  3262. (defvar org-emphasis-regexp-components) ; defined just below
  3263. (defvar org-emphasis-alist) ; defined just below
  3264. (defun org-set-emph-re (var val)
  3265. "Set variable and compute the emphasis regular expression."
  3266. (set var val)
  3267. (when (and (boundp 'org-emphasis-alist)
  3268. (boundp 'org-emphasis-regexp-components)
  3269. org-emphasis-alist org-emphasis-regexp-components)
  3270. (pcase-let*
  3271. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3272. (body (if (<= nl 0) body
  3273. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3274. (template
  3275. (format (concat "\\([%s]\\|^\\)" ;before markers
  3276. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3277. "\\([%s]\\|$\\)") ;after markers
  3278. pre border border body border post)))
  3279. (setq org-emph-re (format template "*/_+"))
  3280. (setq org-verbatim-re (format template "=~")))))
  3281. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3282. ;; set this option proved cumbersome. See this message/thread:
  3283. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3284. (defvar org-emphasis-regexp-components
  3285. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3286. "Components used to build the regular expression for emphasis.
  3287. This is a list with five entries. Terminology: In an emphasis string
  3288. like \" *strong word* \", we call the initial space PREMATCH, the final
  3289. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3290. and \"trong wor\" is the body. The different components in this variable
  3291. specify what is allowed/forbidden in each part:
  3292. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3293. post Chars allowed as postmatch. End of line will be allowed too.
  3294. border The chars *forbidden* as border characters.
  3295. body-regexp A regexp like \".\" to match a body character. Don't use
  3296. non-shy groups here, and don't allow newline here.
  3297. newline The maximum number of newlines allowed in an emphasis exp.
  3298. You need to reload Org or to restart Emacs after setting this.")
  3299. (defcustom org-emphasis-alist
  3300. '(("*" bold)
  3301. ("/" italic)
  3302. ("_" underline)
  3303. ("=" org-verbatim verbatim)
  3304. ("~" org-code verbatim)
  3305. ("+" (:strike-through t)))
  3306. "Alist of characters and faces to emphasize text.
  3307. Text starting and ending with a special character will be emphasized,
  3308. for example *bold*, _underlined_ and /italic/. This variable sets the
  3309. marker characters and the face to be used by font-lock for highlighting
  3310. in Org buffers.
  3311. You need to reload Org or to restart Emacs after customizing this."
  3312. :group 'org-appearance
  3313. :set 'org-set-emph-re
  3314. :version "24.4"
  3315. :package-version '(Org . "8.0")
  3316. :type '(repeat
  3317. (list
  3318. (string :tag "Marker character")
  3319. (choice
  3320. (face :tag "Font-lock-face")
  3321. (plist :tag "Face property list"))
  3322. (option (const verbatim)))))
  3323. (defvar org-protecting-blocks '("src" "example" "export")
  3324. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3325. This is needed for font-lock setup.")
  3326. ;;; Functions and variables from their packages
  3327. ;; Declared here to avoid compiler warnings
  3328. (defvar mark-active)
  3329. ;; Various packages
  3330. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3331. (declare-function calendar-forward-day "cal-move" (arg))
  3332. (declare-function calendar-goto-date "cal-move" (date))
  3333. (declare-function calendar-goto-today "cal-move" ())
  3334. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3335. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3336. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3337. (declare-function cdlatex-tab "ext:cdlatex" ())
  3338. (declare-function dired-get-filename
  3339. "dired"
  3340. (&optional localp no-error-if-not-filep))
  3341. (declare-function iswitchb-read-buffer
  3342. "iswitchb"
  3343. (prompt &optional
  3344. default require-match _predicate start matches-set))
  3345. (declare-function org-agenda-change-all-lines
  3346. "org-agenda"
  3347. (newhead hdmarker &optional fixface just-this))
  3348. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3349. "org-agenda"
  3350. (&optional end))
  3351. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3352. (declare-function org-agenda-format-item
  3353. "org-agenda"
  3354. (extra txt &optional level category tags dotime
  3355. remove-re habitp))
  3356. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3357. (declare-function org-agenda-save-markers-for-cut-and-paste
  3358. "org-agenda"
  3359. (beg end))
  3360. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3361. (declare-function org-agenda-skip "org-agenda" ())
  3362. (declare-function org-attach-expand "org-attach" (file))
  3363. (declare-function org-attach-reveal "org-attach" ())
  3364. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3365. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3366. (declare-function org-indent-mode "org-indent" (&optional arg))
  3367. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3368. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3369. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3370. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3371. (declare-function parse-time-string "parse-time" (string))
  3372. (defvar align-mode-rules-list)
  3373. (defvar calc-embedded-close-formula)
  3374. (defvar calc-embedded-open-formula)
  3375. (defvar calc-embedded-open-mode)
  3376. (defvar font-lock-unfontify-region-function)
  3377. (defvar iswitchb-temp-buflist)
  3378. (defvar org-agenda-tags-todo-honor-ignore-options)
  3379. (defvar remember-data-file)
  3380. (defvar texmathp-why)
  3381. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3382. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3383. (declare-function org-resolve-clocks "org-clock"
  3384. (&optional also-non-dangling-p prompt last-valid))
  3385. (defvar org-clock-start-time)
  3386. (defvar org-clock-marker (make-marker)
  3387. "Marker recording the last clock-in.")
  3388. (defvar org-clock-hd-marker (make-marker)
  3389. "Marker recording the last clock-in, but the headline position.")
  3390. (defvar org-clock-heading ""
  3391. "The heading of the current clock entry.")
  3392. (defun org-clock-is-active ()
  3393. "Return the buffer where the clock is currently running.
  3394. Return nil if no clock is running."
  3395. (marker-buffer org-clock-marker))
  3396. (defun org-check-running-clock ()
  3397. "Check if the current buffer contains the running clock.
  3398. If yes, offer to stop it and to save the buffer with the changes."
  3399. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3400. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3401. (buffer-name))))
  3402. (org-clock-out)
  3403. (when (y-or-n-p "Save changed buffer?")
  3404. (save-buffer))))
  3405. (defun org-clocktable-try-shift (dir n)
  3406. "Check if this line starts a clock table, if yes, shift the time block."
  3407. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3408. (org-clocktable-shift dir n)))
  3409. ;;;###autoload
  3410. (defun org-clock-persistence-insinuate ()
  3411. "Set up hooks for clock persistence."
  3412. (require 'org-clock)
  3413. (add-hook 'org-mode-hook 'org-clock-load)
  3414. (add-hook 'kill-emacs-hook 'org-clock-save))
  3415. (defgroup org-archive nil
  3416. "Options concerning archiving in Org mode."
  3417. :tag "Org Archive"
  3418. :group 'org-structure)
  3419. (defcustom org-archive-location "%s_archive::"
  3420. "The location where subtrees should be archived.
  3421. The value of this variable is a string, consisting of two parts,
  3422. separated by a double-colon. The first part is a filename and
  3423. the second part is a headline.
  3424. When the filename is omitted, archiving happens in the same file.
  3425. %s in the filename will be replaced by the current file
  3426. name (without the directory part). Archiving to a different file
  3427. is useful to keep archived entries from contributing to the
  3428. Org Agenda.
  3429. The archived entries will be filed as subtrees of the specified
  3430. headline. When the headline is omitted, the subtrees are simply
  3431. filed away at the end of the file, as top-level entries. Also in
  3432. the heading you can use %s to represent the file name, this can be
  3433. useful when using the same archive for a number of different files.
  3434. Here are a few examples:
  3435. \"%s_archive::\"
  3436. If the current file is Projects.org, archive in file
  3437. Projects.org_archive, as top-level trees. This is the default.
  3438. \"::* Archived Tasks\"
  3439. Archive in the current file, under the top-level headline
  3440. \"* Archived Tasks\".
  3441. \"~/org/archive.org::\"
  3442. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3443. \"~/org/archive.org::* From %s\"
  3444. Archive in file ~/org/archive.org (absolute path), under headlines
  3445. \"From FILENAME\" where file name is the current file name.
  3446. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3447. The \"datetree/\" string is special, signifying to archive
  3448. items to the datetree. Items are placed in either the CLOSED
  3449. date of the item, or the current date if there is no CLOSED date.
  3450. The heading will be a subentry to the current date. There doesn't
  3451. need to be a heading, but there always needs to be a slash after
  3452. datetree. For example, to store archived items directly in the
  3453. datetree, use \"~/org/datetree.org::datetree/\".
  3454. \"basement::** Finished Tasks\"
  3455. Archive in file ./basement (relative path), as level 3 trees
  3456. below the level 2 heading \"** Finished Tasks\".
  3457. You may define it locally by setting an ARCHIVE property. If
  3458. such a property is found in the file or in an entry, and anywhere
  3459. up the hierarchy, it will be used.
  3460. You can also set it for the whole file using the keyword-syntax:
  3461. #+ARCHIVE: basement::** Finished Tasks"
  3462. :group 'org-archive
  3463. :type 'string)
  3464. (defcustom org-agenda-skip-archived-trees t
  3465. "Non-nil means the agenda will skip any items located in archived trees.
  3466. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3467. variable is no longer recommended, you should leave it at the value t.
  3468. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3469. :group 'org-archive
  3470. :group 'org-agenda-skip
  3471. :type 'boolean)
  3472. (defcustom org-columns-skip-archived-trees t
  3473. "Non-nil means ignore archived trees when creating column view."
  3474. :group 'org-archive
  3475. :group 'org-properties
  3476. :type 'boolean)
  3477. (defcustom org-cycle-open-archived-trees nil
  3478. "Non-nil means `org-cycle' will open archived trees.
  3479. An archived tree is a tree marked with the tag ARCHIVE.
  3480. When nil, archived trees will stay folded. You can still open them with
  3481. normal outline commands like `show-all', but not with the cycling commands."
  3482. :group 'org-archive
  3483. :group 'org-cycle
  3484. :type 'boolean)
  3485. (defcustom org-sparse-tree-open-archived-trees nil
  3486. "Non-nil means sparse tree construction shows matches in archived trees.
  3487. When nil, matches in these trees are highlighted, but the trees are kept in
  3488. collapsed state."
  3489. :group 'org-archive
  3490. :group 'org-sparse-trees
  3491. :type 'boolean)
  3492. (defcustom org-sparse-tree-default-date-type nil
  3493. "The default date type when building a sparse tree.
  3494. When this is nil, a date is a scheduled or a deadline timestamp.
  3495. Otherwise, these types are allowed:
  3496. all: all timestamps
  3497. active: only active timestamps (<...>)
  3498. inactive: only inactive timestamps ([...])
  3499. scheduled: only scheduled timestamps
  3500. deadline: only deadline timestamps"
  3501. :type '(choice (const :tag "Scheduled or deadline" nil)
  3502. (const :tag "All timestamps" all)
  3503. (const :tag "Only active timestamps" active)
  3504. (const :tag "Only inactive timestamps" inactive)
  3505. (const :tag "Only scheduled timestamps" scheduled)
  3506. (const :tag "Only deadline timestamps" deadline)
  3507. (const :tag "Only closed timestamps" closed))
  3508. :version "26.1"
  3509. :package-version '(Org . "8.3")
  3510. :group 'org-sparse-trees)
  3511. (defun org-cycle-hide-archived-subtrees (state)
  3512. "Re-hide all archived subtrees after a visibility state change.
  3513. STATE should be one of the symbols listed in the docstring of
  3514. `org-cycle-hook'."
  3515. (when (and (not org-cycle-open-archived-trees)
  3516. (not (memq state '(overview folded))))
  3517. (save-excursion
  3518. (let* ((globalp (memq state '(contents all)))
  3519. (beg (if globalp (point-min) (point)))
  3520. (end (if globalp (point-max) (org-end-of-subtree t))))
  3521. (org-hide-archived-subtrees beg end)
  3522. (goto-char beg)
  3523. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3524. (message "%s" (substitute-command-keys
  3525. "Subtree is archived and stays closed. Use \
  3526. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3527. (defun org-force-cycle-archived ()
  3528. "Cycle subtree even if it is archived."
  3529. (interactive)
  3530. (setq this-command 'org-cycle)
  3531. (let ((org-cycle-open-archived-trees t))
  3532. (call-interactively 'org-cycle)))
  3533. (defun org-hide-archived-subtrees (beg end)
  3534. "Re-hide all archived subtrees after a visibility state change."
  3535. (org-with-wide-buffer
  3536. (let ((case-fold-search nil)
  3537. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3538. (goto-char beg)
  3539. ;; Include headline point is currently on.
  3540. (beginning-of-line)
  3541. (while (and (< (point) end) (re-search-forward re end t))
  3542. (when (member org-archive-tag (org-get-tags nil t))
  3543. (org-flag-subtree t)
  3544. (org-end-of-subtree t))))))
  3545. (defun org-flag-subtree (flag)
  3546. (save-excursion
  3547. (org-back-to-heading t)
  3548. (org-flag-region (line-end-position)
  3549. (progn (org-end-of-subtree t) (point))
  3550. flag
  3551. 'outline)))
  3552. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3553. ;; Declare Column View Code
  3554. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3555. (declare-function org-columns-compute "org-colview" (property))
  3556. ;; Declare ID code
  3557. (declare-function org-id-store-link "org-id")
  3558. (declare-function org-id-locations-load "org-id")
  3559. (declare-function org-id-locations-save "org-id")
  3560. (defvar org-id-track-globally)
  3561. ;;; Variables for pre-computed regular expressions, all buffer local
  3562. (defvar-local org-todo-regexp nil
  3563. "Matches any of the TODO state keywords.
  3564. Since TODO keywords are case-sensitive, `case-fold-search' is
  3565. expected to be bound to nil when matching against this regexp.")
  3566. (defvar-local org-not-done-regexp nil
  3567. "Matches any of the TODO state keywords except the last one.
  3568. Since TODO keywords are case-sensitive, `case-fold-search' is
  3569. expected to be bound to nil when matching against this regexp.")
  3570. (defvar-local org-not-done-heading-regexp nil
  3571. "Matches a TODO headline that is not done.
  3572. Since TODO keywords are case-sensitive, `case-fold-search' is
  3573. expected to be bound to nil when matching against this regexp.")
  3574. (defvar-local org-todo-line-regexp nil
  3575. "Matches a headline and puts TODO state into group 2 if present.
  3576. Since TODO keywords are case-sensitive, `case-fold-search' is
  3577. expected to be bound to nil when matching against this regexp.")
  3578. (defvar-local org-complex-heading-regexp nil
  3579. "Matches a headline and puts everything into groups:
  3580. group 1: Stars
  3581. group 2: The TODO keyword, maybe
  3582. group 3: Priority cookie
  3583. group 4: True headline
  3584. group 5: Tags
  3585. Since TODO keywords are case-sensitive, `case-fold-search' is
  3586. expected to be bound to nil when matching against this regexp.")
  3587. (defvar-local org-complex-heading-regexp-format nil
  3588. "Printf format to make regexp to match an exact headline.
  3589. This regexp will match the headline of any node which has the
  3590. exact headline text that is put into the format, but may have any
  3591. TODO state, priority and tags.")
  3592. (defvar-local org-todo-line-tags-regexp nil
  3593. "Matches a headline and puts TODO state into group 2 if present.
  3594. Also put tags into group 4 if tags are present.")
  3595. (defconst org-plain-time-of-day-regexp
  3596. (concat
  3597. "\\(\\<[012]?[0-9]"
  3598. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3599. "\\(--?"
  3600. "\\(\\<[012]?[0-9]"
  3601. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3602. "\\)?")
  3603. "Regular expression to match a plain time or time range.
  3604. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3605. groups carry important information:
  3606. 0 the full match
  3607. 1 the first time, range or not
  3608. 8 the second time, if it is a range.")
  3609. (defconst org-plain-time-extension-regexp
  3610. (concat
  3611. "\\(\\<[012]?[0-9]"
  3612. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3613. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3614. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3615. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3616. groups carry important information:
  3617. 0 the full match
  3618. 7 hours of duration
  3619. 9 minutes of duration")
  3620. (defconst org-stamp-time-of-day-regexp
  3621. (concat
  3622. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3623. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  3624. "\\(--?"
  3625. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3626. "Regular expression to match a timestamp time or time range.
  3627. After a match, the following groups carry important information:
  3628. 0 the full match
  3629. 1 date plus weekday, for back referencing to make sure both times are on the same day
  3630. 2 the first time, range or not
  3631. 4 the second time, if it is a range.")
  3632. (defconst org-startup-options
  3633. '(("fold" org-startup-folded t)
  3634. ("overview" org-startup-folded t)
  3635. ("nofold" org-startup-folded nil)
  3636. ("showall" org-startup-folded nil)
  3637. ("showeverything" org-startup-folded showeverything)
  3638. ("content" org-startup-folded content)
  3639. ("indent" org-startup-indented t)
  3640. ("noindent" org-startup-indented nil)
  3641. ("hidestars" org-hide-leading-stars t)
  3642. ("showstars" org-hide-leading-stars nil)
  3643. ("odd" org-odd-levels-only t)
  3644. ("oddeven" org-odd-levels-only nil)
  3645. ("align" org-startup-align-all-tables t)
  3646. ("noalign" org-startup-align-all-tables nil)
  3647. ("shrink" org-startup-shrink-all-tables t)
  3648. ("inlineimages" org-startup-with-inline-images t)
  3649. ("noinlineimages" org-startup-with-inline-images nil)
  3650. ("latexpreview" org-startup-with-latex-preview t)
  3651. ("nolatexpreview" org-startup-with-latex-preview nil)
  3652. ("customtime" org-display-custom-times t)
  3653. ("logdone" org-log-done time)
  3654. ("lognotedone" org-log-done note)
  3655. ("nologdone" org-log-done nil)
  3656. ("lognoteclock-out" org-log-note-clock-out t)
  3657. ("nolognoteclock-out" org-log-note-clock-out nil)
  3658. ("logrepeat" org-log-repeat state)
  3659. ("lognoterepeat" org-log-repeat note)
  3660. ("logdrawer" org-log-into-drawer t)
  3661. ("nologdrawer" org-log-into-drawer nil)
  3662. ("logstatesreversed" org-log-states-order-reversed t)
  3663. ("nologstatesreversed" org-log-states-order-reversed nil)
  3664. ("nologrepeat" org-log-repeat nil)
  3665. ("logreschedule" org-log-reschedule time)
  3666. ("lognotereschedule" org-log-reschedule note)
  3667. ("nologreschedule" org-log-reschedule nil)
  3668. ("logredeadline" org-log-redeadline time)
  3669. ("lognoteredeadline" org-log-redeadline note)
  3670. ("nologredeadline" org-log-redeadline nil)
  3671. ("logrefile" org-log-refile time)
  3672. ("lognoterefile" org-log-refile note)
  3673. ("nologrefile" org-log-refile nil)
  3674. ("fninline" org-footnote-define-inline t)
  3675. ("nofninline" org-footnote-define-inline nil)
  3676. ("fnlocal" org-footnote-section nil)
  3677. ("fnauto" org-footnote-auto-label t)
  3678. ("fnprompt" org-footnote-auto-label nil)
  3679. ("fnconfirm" org-footnote-auto-label confirm)
  3680. ("fnplain" org-footnote-auto-label plain)
  3681. ("fnadjust" org-footnote-auto-adjust t)
  3682. ("nofnadjust" org-footnote-auto-adjust nil)
  3683. ("constcgs" constants-unit-system cgs)
  3684. ("constSI" constants-unit-system SI)
  3685. ("noptag" org-tag-persistent-alist nil)
  3686. ("hideblocks" org-hide-block-startup t)
  3687. ("nohideblocks" org-hide-block-startup nil)
  3688. ("beamer" org-startup-with-beamer-mode t)
  3689. ("entitiespretty" org-pretty-entities t)
  3690. ("entitiesplain" org-pretty-entities nil))
  3691. "Variable associated with STARTUP options for Org.
  3692. Each element is a list of three items: the startup options (as written
  3693. in the #+STARTUP line), the corresponding variable, and the value to set
  3694. this variable to if the option is found. An optional forth element PUSH
  3695. means to push this value onto the list in the variable.")
  3696. (defcustom org-group-tags t
  3697. "When non-nil (the default), use group tags.
  3698. This can be turned on/off through `org-toggle-tags-groups'."
  3699. :group 'org-tags
  3700. :group 'org-startup
  3701. :type 'boolean)
  3702. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3703. (defun org-toggle-tags-groups ()
  3704. "Toggle support for group tags.
  3705. Support for group tags is controlled by the option
  3706. `org-group-tags', which is non-nil by default."
  3707. (interactive)
  3708. (setq org-group-tags (not org-group-tags))
  3709. (cond ((and (derived-mode-p 'org-agenda-mode)
  3710. org-group-tags)
  3711. (org-agenda-redo))
  3712. ((derived-mode-p 'org-mode)
  3713. (let ((org-inhibit-startup t)) (org-mode))))
  3714. (message "Groups tags support has been turned %s"
  3715. (if org-group-tags "on" "off")))
  3716. (defun org--tag-add-to-alist (alist1 alist2)
  3717. "Merge tags from ALIST1 into ALIST2.
  3718. Duplicates tags outside a group are removed. Keywords and order
  3719. are preserved.
  3720. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3721. See `org-tag-alist' for their structure."
  3722. (cond
  3723. ((null alist2) alist1)
  3724. ((null alist1) alist2)
  3725. (t
  3726. (let ((to-add nil)
  3727. (group-flag nil))
  3728. (dolist (tag-pair alist1)
  3729. (pcase tag-pair
  3730. (`(,(or :startgrouptag :startgroup))
  3731. (setq group-flag t)
  3732. (push tag-pair to-add))
  3733. (`(,(or :endgrouptag :endgroup))
  3734. (setq group-flag nil)
  3735. (push tag-pair to-add))
  3736. (`(,(or :grouptags :newline))
  3737. (push tag-pair to-add))
  3738. (`(,tag . ,_)
  3739. ;; Remove duplicates from ALIST1, unless they are in
  3740. ;; a group. Indeed, it makes sense to have a tag appear in
  3741. ;; multiple groups.
  3742. (when (or group-flag (not (assoc tag alist2)))
  3743. (push tag-pair to-add)))
  3744. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3745. ;; Preserve order of ALIST1.
  3746. (append (nreverse to-add) alist2)))))
  3747. (defun org-set-regexps-and-options (&optional tags-only)
  3748. "Precompute regular expressions used in the current buffer.
  3749. When optional argument TAGS-ONLY is non-nil, only compute tags
  3750. related expressions."
  3751. (when (derived-mode-p 'org-mode)
  3752. (let ((alist (org--setup-collect-keywords
  3753. (org-make-options-regexp
  3754. (append '("FILETAGS" "TAGS" "SETUPFILE")
  3755. (and (not tags-only)
  3756. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3757. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3758. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  3759. ;; Startup options. Get this early since it does change
  3760. ;; behavior for other options (e.g., tags).
  3761. (let ((startup (cdr (assq 'startup alist))))
  3762. (dolist (option startup)
  3763. (let ((entry (assoc-string option org-startup-options t)))
  3764. (when entry
  3765. (let ((var (nth 1 entry))
  3766. (val (nth 2 entry)))
  3767. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  3768. (unless (listp (symbol-value var))
  3769. (set (make-local-variable var) nil))
  3770. (add-to-list var val)))))))
  3771. (setq-local org-file-tags
  3772. (mapcar #'org-add-prop-inherited
  3773. (cdr (assq 'filetags alist))))
  3774. (setq org-current-tag-alist
  3775. (org--tag-add-to-alist
  3776. org-tag-persistent-alist
  3777. (let ((tags (cdr (assq 'tags alist))))
  3778. (if tags (org-tag-string-to-alist tags)
  3779. org-tag-alist))))
  3780. (setq org-tag-groups-alist
  3781. (org-tag-alist-to-groups org-current-tag-alist))
  3782. (unless tags-only
  3783. ;; Properties.
  3784. (setq-local org-keyword-properties (cdr (assq 'property alist)))
  3785. ;; Archive location.
  3786. (let ((archive (cdr (assq 'archive alist))))
  3787. (when archive (setq-local org-archive-location archive)))
  3788. ;; Category.
  3789. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  3790. (when cat
  3791. (setq-local org-category (intern cat))
  3792. (setq-local org-keyword-properties
  3793. (org--update-property-plist
  3794. "CATEGORY" cat org-keyword-properties))))
  3795. ;; Columns.
  3796. (let ((column (cdr (assq 'columns alist))))
  3797. (when column (setq-local org-columns-default-format column)))
  3798. ;; Constants.
  3799. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  3800. ;; Link abbreviations.
  3801. (let ((links (cdr (assq 'link alist))))
  3802. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3803. ;; Priorities.
  3804. (let ((priorities (cdr (assq 'priorities alist))))
  3805. (when priorities
  3806. (setq-local org-priority-highest (nth 0 priorities))
  3807. (setq-local org-priority-lowest (nth 1 priorities))
  3808. (setq-local org-priority-default (nth 2 priorities))))
  3809. ;; Scripts.
  3810. (let ((scripts (assq 'scripts alist)))
  3811. (when scripts
  3812. (setq-local org-use-sub-superscripts (cdr scripts))))
  3813. ;; TODO keywords.
  3814. (setq-local org-todo-kwd-alist nil)
  3815. (setq-local org-todo-key-alist nil)
  3816. (setq-local org-todo-key-trigger nil)
  3817. (setq-local org-todo-keywords-1 nil)
  3818. (setq-local org-done-keywords nil)
  3819. (setq-local org-todo-heads nil)
  3820. (setq-local org-todo-sets nil)
  3821. (setq-local org-todo-log-states nil)
  3822. (let ((todo-sequences
  3823. (or (nreverse (cdr (assq 'todo alist)))
  3824. (let ((d (default-value 'org-todo-keywords)))
  3825. (if (not (stringp (car d))) d
  3826. ;; XXX: Backward compatibility code.
  3827. (list (cons org-todo-interpretation d)))))))
  3828. (dolist (sequence todo-sequences)
  3829. (let* ((sequence (or (run-hook-with-args-until-success
  3830. 'org-todo-setup-filter-hook sequence)
  3831. sequence))
  3832. (sequence-type (car sequence))
  3833. (keywords (cdr sequence))
  3834. (sep (member "|" keywords))
  3835. names alist)
  3836. (dolist (k (remove "|" keywords))
  3837. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3838. k)
  3839. (error "Invalid TODO keyword %s" k))
  3840. (let ((name (match-string 1 k))
  3841. (key (match-string 2 k))
  3842. (log (org-extract-log-state-settings k)))
  3843. (push name names)
  3844. (push (cons name (and key (string-to-char key))) alist)
  3845. (when log (push log org-todo-log-states))))
  3846. (let* ((names (nreverse names))
  3847. (done (if sep (org-remove-keyword-keys (cdr sep))
  3848. (last names)))
  3849. (head (car names))
  3850. (tail (list sequence-type head (car done) (org-last done))))
  3851. (add-to-list 'org-todo-heads head 'append)
  3852. (push names org-todo-sets)
  3853. (setq org-done-keywords (append org-done-keywords done nil))
  3854. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3855. (setq org-todo-key-alist
  3856. (append org-todo-key-alist
  3857. (and alist
  3858. (append '((:startgroup))
  3859. (nreverse alist)
  3860. '((:endgroup))))))
  3861. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3862. (setq org-todo-sets (nreverse org-todo-sets)
  3863. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3864. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3865. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3866. ;; Compute the regular expressions and other local variables.
  3867. ;; Using `org-outline-regexp-bol' would complicate them much,
  3868. ;; because of the fixed white space at the end of that string.
  3869. (unless org-done-keywords
  3870. (setq org-done-keywords
  3871. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3872. (setq org-not-done-keywords
  3873. (org-delete-all org-done-keywords
  3874. (copy-sequence org-todo-keywords-1))
  3875. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3876. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3877. org-not-done-heading-regexp
  3878. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3879. org-todo-line-regexp
  3880. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3881. org-complex-heading-regexp
  3882. (concat "^\\(\\*+\\)"
  3883. "\\(?: +" org-todo-regexp "\\)?"
  3884. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3885. "\\(?: +\\(.*?\\)\\)??"
  3886. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3887. "[ \t]*$")
  3888. org-complex-heading-regexp-format
  3889. (concat "^\\(\\*+\\)"
  3890. "\\(?: +" org-todo-regexp "\\)?"
  3891. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3892. "\\(?: +"
  3893. ;; Stats cookies can be stuck to body.
  3894. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3895. "\\(%s\\)"
  3896. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3897. "\\)"
  3898. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3899. "[ \t]*$")
  3900. org-todo-line-tags-regexp
  3901. (concat "^\\(\\*+\\)"
  3902. "\\(?: +" org-todo-regexp "\\)?"
  3903. "\\(?: +\\(.*?\\)\\)??"
  3904. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3905. "[ \t]*$"))
  3906. (org-compute-latex-and-related-regexp)))))
  3907. (defsubst org-priority-to-value (s)
  3908. "Convert priority string S to its numeric value."
  3909. (or (save-match-data
  3910. (and (string-match "\\([0-9]+\\)" s)
  3911. (string-to-number (match-string 1 s))))
  3912. (string-to-char s)))
  3913. (defun org--setup-collect-keywords (regexp &optional files alist)
  3914. "Return setup keywords values as an alist.
  3915. REGEXP matches a subset of setup keywords. FILES is a list of
  3916. file names already visited. It is used to avoid circular setup
  3917. files. ALIST, when non-nil, is the alist computed so far.
  3918. Return value contains the following keys: `archive', `category',
  3919. `columns', `constants', `filetags', `link', `priorities',
  3920. `property', `scripts', `startup', `tags' and `todo'."
  3921. (org-with-wide-buffer
  3922. (goto-char (point-min))
  3923. (let ((case-fold-search t))
  3924. (while (re-search-forward regexp nil t)
  3925. (let ((element (org-element-at-point)))
  3926. (when (eq (org-element-type element) 'keyword)
  3927. (let ((key (org-element-property :key element))
  3928. (value (org-element-property :value element)))
  3929. (cond
  3930. ((equal key "ARCHIVE")
  3931. (when (org-string-nw-p value)
  3932. (push (cons 'archive value) alist)))
  3933. ((equal key "CATEGORY") (push (cons 'category value) alist))
  3934. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  3935. ((equal key "CONSTANTS")
  3936. (let* ((constants (assq 'constants alist))
  3937. (store (cdr constants)))
  3938. (dolist (pair (split-string value))
  3939. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  3940. pair)
  3941. (let* ((name (match-string 1 pair))
  3942. (value (match-string 2 pair))
  3943. (old (assoc name store)))
  3944. (if old (setcdr old value)
  3945. (push (cons name value) store)))))
  3946. (if constants (setcdr constants store)
  3947. (push (cons 'constants store) alist))))
  3948. ((equal key "FILETAGS")
  3949. (when (org-string-nw-p value)
  3950. (let ((old (assq 'filetags alist))
  3951. (new (apply #'nconc
  3952. (mapcar (lambda (x) (org-split-string x ":"))
  3953. (split-string value)))))
  3954. (if old (setcdr old (append new (cdr old)))
  3955. (push (cons 'filetags new) alist)))))
  3956. ((equal key "LINK")
  3957. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3958. (let ((links (assq 'link alist))
  3959. (pair (cons (match-string-no-properties 1 value)
  3960. (match-string-no-properties 2 value))))
  3961. (if links (push pair (cdr links))
  3962. (push (list 'link pair) alist)))))
  3963. ((equal key "OPTIONS")
  3964. (when (and (org-string-nw-p value)
  3965. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  3966. (push (cons 'scripts (read (match-string 1 value))) alist)))
  3967. ((equal key "PRIORITIES")
  3968. (push (cons 'priorities
  3969. (let ((prio (split-string value)))
  3970. (if (< (length prio) 3)
  3971. (list org-priority-highest
  3972. org-priority-lowest
  3973. org-priority-default)
  3974. (mapcar #'org-priority-to-value prio))))
  3975. alist))
  3976. ((equal key "PROPERTY")
  3977. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3978. (let* ((property (assq 'property alist))
  3979. (value (org--update-property-plist
  3980. (match-string-no-properties 1 value)
  3981. (match-string-no-properties 2 value)
  3982. (cdr property))))
  3983. (if property (setcdr property value)
  3984. (push (cons 'property value) alist)))))
  3985. ((equal key "STARTUP")
  3986. (let ((startup (assq 'startup alist)))
  3987. (if startup
  3988. (setcdr startup
  3989. (append (cdr startup) (split-string value)))
  3990. (push (cons 'startup (split-string value)) alist))))
  3991. ((equal key "TAGS")
  3992. (let ((tag-cell (assq 'tags alist)))
  3993. (if tag-cell
  3994. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  3995. (push (cons 'tags value) alist))))
  3996. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  3997. (let ((todo (assq 'todo alist))
  3998. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  3999. (split-string value))))
  4000. (if todo (push value (cdr todo))
  4001. (push (list 'todo value) alist))))
  4002. ((equal key "SETUPFILE")
  4003. (unless buffer-read-only ; Do not check in Gnus messages.
  4004. (let ((f (and (org-string-nw-p value)
  4005. (expand-file-name (org-strip-quotes value)))))
  4006. (when (and f (file-readable-p f) (not (member f files)))
  4007. (with-temp-buffer
  4008. (setq default-directory (file-name-directory f))
  4009. (insert-file-contents f)
  4010. (setq alist
  4011. ;; Fake Org mode to benefit from cache
  4012. ;; without recurring needlessly.
  4013. (let ((major-mode 'org-mode))
  4014. (org--setup-collect-keywords
  4015. regexp (cons f files) alist)))))))))))))))
  4016. alist)
  4017. (defun org-tag-string-to-alist (s)
  4018. "Return tag alist associated to string S.
  4019. S is a value for TAGS keyword or produced with
  4020. `org-tag-alist-to-string'. Return value is an alist suitable for
  4021. `org-tag-alist' or `org-tag-persistent-alist'."
  4022. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4023. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  4024. "\\(?:(\\(.\\))\\)?\\'"))
  4025. alist group-flag)
  4026. (dolist (tokens lines (cdr (nreverse alist)))
  4027. (push '(:newline) alist)
  4028. (while tokens
  4029. (let ((token (pop tokens)))
  4030. (pcase token
  4031. ("{"
  4032. (push '(:startgroup) alist)
  4033. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4034. ("}"
  4035. (push '(:endgroup) alist)
  4036. (setq group-flag nil))
  4037. ("["
  4038. (push '(:startgrouptag) alist)
  4039. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4040. ("]"
  4041. (push '(:endgrouptag) alist)
  4042. (setq group-flag nil))
  4043. (":"
  4044. (push '(:grouptags) alist))
  4045. ((guard (string-match tag-re token))
  4046. (let ((tag (match-string 1 token))
  4047. (key (and (match-beginning 2)
  4048. (string-to-char (match-string 2 token)))))
  4049. ;; Push all tags in groups, no matter if they already
  4050. ;; appear somewhere else in the list.
  4051. (when (or group-flag (not (assoc tag alist)))
  4052. (push (cons tag key) alist))))))))))
  4053. (defun org-tag-alist-to-string (alist &optional skip-key)
  4054. "Return tag string associated to ALIST.
  4055. ALIST is an alist, as defined in `org-tag-alist' or
  4056. `org-tag-persistent-alist', or produced with
  4057. `org-tag-string-to-alist'.
  4058. Return value is a string suitable as a value for \"TAGS\"
  4059. keyword.
  4060. When optional argument SKIP-KEY is non-nil, skip selection keys
  4061. next to tags."
  4062. (mapconcat (lambda (token)
  4063. (pcase token
  4064. (`(:startgroup) "{")
  4065. (`(:endgroup) "}")
  4066. (`(:startgrouptag) "[")
  4067. (`(:endgrouptag) "]")
  4068. (`(:grouptags) ":")
  4069. (`(:newline) "\\n")
  4070. ((and
  4071. (guard (not skip-key))
  4072. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4073. (format "%s(%c)" tag key))
  4074. (`(,(and tag (pred stringp)) . ,_) tag)
  4075. (_ (user-error "Invalid tag token: %S" token))))
  4076. alist
  4077. " "))
  4078. (defun org-tag-alist-to-groups (alist)
  4079. "Return group alist from tag ALIST.
  4080. ALIST is an alist, as defined in `org-tag-alist' or
  4081. `org-tag-persistent-alist', or produced with
  4082. `org-tag-string-to-alist'. Return value is an alist following
  4083. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4084. a string, summarizing TAGS, as a list of strings."
  4085. (let (groups group-status current-group)
  4086. (dolist (token alist (nreverse groups))
  4087. (pcase token
  4088. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4089. (`(,(or :endgroup :endgrouptag))
  4090. (when (eq group-status 'append)
  4091. (push (nreverse current-group) groups))
  4092. (setq group-status nil current-group nil))
  4093. (`(:grouptags) (setq group-status 'append))
  4094. ((and `(,tag . ,_) (guard group-status))
  4095. (if (eq group-status 'append) (push tag current-group)
  4096. (setq current-group (list tag))))
  4097. (_ nil)))))
  4098. (defvar org--file-cache (make-hash-table :test #'equal)
  4099. "Hash table to store contents of files referenced via a URL.
  4100. This is the cache of file URLs read using `org-file-contents'.")
  4101. (defun org-reset-file-cache ()
  4102. "Reset the cache of files downloaded by `org-file-contents'."
  4103. (clrhash org--file-cache))
  4104. (defun org-file-url-p (file)
  4105. "Non-nil if FILE is a URL."
  4106. (require 'ffap)
  4107. (string-match-p ffap-url-regexp file))
  4108. (defun org-file-contents (file &optional noerror nocache)
  4109. "Return the contents of FILE, as a string.
  4110. FILE can be a file name or URL.
  4111. If FILE is a URL, download the contents. If the URL contents are
  4112. already cached in the `org--file-cache' hash table, the download step
  4113. is skipped.
  4114. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4115. from file or URL.
  4116. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4117. is available. This option applies only if FILE is a URL."
  4118. (let* ((is-url (org-file-url-p file))
  4119. (cache (and is-url
  4120. (not nocache)
  4121. (gethash file org--file-cache))))
  4122. (cond
  4123. (cache)
  4124. (is-url
  4125. (with-current-buffer (url-retrieve-synchronously file)
  4126. (goto-char (point-min))
  4127. ;; Move point to after the url-retrieve header.
  4128. (search-forward "\n\n" nil :move)
  4129. ;; Search for the success code only in the url-retrieve header.
  4130. (if (save-excursion
  4131. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4132. ;; Update the cache `org--file-cache' and return contents.
  4133. (puthash file
  4134. (buffer-substring-no-properties (point) (point-max))
  4135. org--file-cache)
  4136. (funcall (if noerror #'message #'user-error)
  4137. "Unable to fetch file from %S"
  4138. file))))
  4139. (t
  4140. (with-temp-buffer
  4141. (condition-case nil
  4142. (progn
  4143. (insert-file-contents file)
  4144. (buffer-string))
  4145. (file-error
  4146. (funcall (if noerror #'message #'user-error)
  4147. "Unable to read file %S"
  4148. file))))))))
  4149. (defun org-extract-log-state-settings (x)
  4150. "Extract the log state setting from a TODO keyword string.
  4151. This will extract info from a string like \"WAIT(w@/!)\"."
  4152. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4153. (let ((kw (match-string 1 x))
  4154. (log1 (and (match-end 3) (match-string 3 x)))
  4155. (log2 (and (match-end 4) (match-string 4 x))))
  4156. (and (or log1 log2)
  4157. (list kw
  4158. (and log1 (if (equal log1 "!") 'time 'note))
  4159. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4160. (defun org-remove-keyword-keys (list)
  4161. "Remove a pair of parenthesis at the end of each string in LIST."
  4162. (mapcar (lambda (x)
  4163. (if (string-match "(.*)$" x)
  4164. (substring x 0 (match-beginning 0))
  4165. x))
  4166. list))
  4167. (defun org-assign-fast-keys (alist)
  4168. "Assign fast keys to a keyword-key alist.
  4169. Respect keys that are already there."
  4170. (let (new e (alt ?0))
  4171. (while (setq e (pop alist))
  4172. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4173. (cdr e)) ;; Key already assigned.
  4174. (push e new)
  4175. (let ((clist (string-to-list (downcase (car e))))
  4176. (used (append new alist)))
  4177. (when (= (car clist) ?@)
  4178. (pop clist))
  4179. (while (and clist (rassoc (car clist) used))
  4180. (pop clist))
  4181. (unless clist
  4182. (while (rassoc alt used)
  4183. (cl-incf alt)))
  4184. (push (cons (car e) (or (car clist) alt)) new))))
  4185. (nreverse new)))
  4186. ;;; Some variables used in various places
  4187. (defvar org-window-configuration nil
  4188. "Used in various places to store a window configuration.")
  4189. (defvar org-selected-window nil
  4190. "Used in various places to store a window configuration.")
  4191. (defvar org-finish-function nil
  4192. "Function to be called when `C-c C-c' is used.
  4193. This is for getting out of special buffers like capture.")
  4194. (defvar org-last-state)
  4195. ;; Defined somewhere in this file, but used before definition.
  4196. (defvar org-entities) ;; defined in org-entities.el
  4197. (defvar org-struct-menu)
  4198. (defvar org-org-menu)
  4199. (defvar org-tbl-menu)
  4200. ;;;; Define the Org mode
  4201. (defun org-before-change-function (_beg _end)
  4202. "Every change indicates that a table might need an update."
  4203. (setq org-table-may-need-update t))
  4204. (defvar org-mode-map)
  4205. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4206. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4207. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4208. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4209. (defvar bidi-paragraph-direction)
  4210. (defvar buffer-face-mode-face)
  4211. (require 'outline)
  4212. ;; Other stuff we need.
  4213. (require 'time-date)
  4214. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4215. (require 'easymenu)
  4216. (autoload 'easy-menu-add "easymenu")
  4217. (require 'overlay)
  4218. ;; (require 'org-macs) moved higher up in the file before it is first used
  4219. (require 'org-entities)
  4220. ;; (require 'org-compat) moved higher up in the file before it is first used
  4221. (require 'org-faces)
  4222. (require 'org-list)
  4223. (require 'org-pcomplete)
  4224. (require 'org-src)
  4225. (require 'org-footnote)
  4226. (require 'org-macro)
  4227. ;; babel
  4228. (require 'ob)
  4229. ;;;###autoload
  4230. (define-derived-mode org-mode outline-mode "Org"
  4231. "Outline-based notes management and organizer, alias
  4232. \"Carsten's outline-mode for keeping track of everything.\"
  4233. Org mode develops organizational tasks around a NOTES file which
  4234. contains information about projects as plain text. Org mode is
  4235. implemented on top of Outline mode, which is ideal to keep the content
  4236. of large files well structured. It supports ToDo items, deadlines and
  4237. time stamps, which magically appear in the diary listing of the Emacs
  4238. calendar. Tables are easily created with a built-in table editor.
  4239. Plain text URL-like links connect to websites, emails (VM), Usenet
  4240. messages (Gnus), BBDB entries, and any files related to the project.
  4241. For printing and sharing of notes, an Org file (or a part of it)
  4242. can be exported as a structured ASCII or HTML file.
  4243. The following commands are available:
  4244. \\{org-mode-map}"
  4245. (org-load-modules-maybe)
  4246. (org-install-agenda-files-menu)
  4247. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4248. (add-to-invisibility-spec '(org-hide-block . t))
  4249. (add-to-invisibility-spec '(org-hide-drawer . t))
  4250. (setq-local outline-regexp org-outline-regexp)
  4251. (setq-local outline-level 'org-outline-level)
  4252. (setq bidi-paragraph-direction 'left-to-right)
  4253. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4254. (unless org-display-table
  4255. (setq org-display-table (make-display-table)))
  4256. (set-display-table-slot
  4257. org-display-table 4
  4258. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4259. org-ellipsis)))
  4260. (setq buffer-display-table org-display-table))
  4261. (org-set-regexps-and-options)
  4262. (org-set-font-lock-defaults)
  4263. (when (and org-tag-faces (not org-tags-special-faces-re))
  4264. ;; tag faces set outside customize.... force initialization.
  4265. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4266. ;; Calc embedded
  4267. (setq-local calc-embedded-open-mode "# ")
  4268. ;; Modify a few syntax entries
  4269. (modify-syntax-entry ?\" "\"")
  4270. (modify-syntax-entry ?\\ "_")
  4271. (modify-syntax-entry ?~ "_")
  4272. (modify-syntax-entry ?< "(>")
  4273. (modify-syntax-entry ?> ")<")
  4274. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4275. ;; Activate before-change-function
  4276. (setq-local org-table-may-need-update t)
  4277. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4278. ;; Check for running clock before killing a buffer
  4279. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4280. ;; Initialize macros templates.
  4281. (org-macro-initialize-templates)
  4282. ;; Initialize radio targets.
  4283. (org-update-radio-target-regexp)
  4284. ;; Indentation.
  4285. (setq-local indent-line-function 'org-indent-line)
  4286. (setq-local indent-region-function 'org-indent-region)
  4287. ;; Filling and auto-filling.
  4288. (org-setup-filling)
  4289. ;; Comments.
  4290. (org-setup-comments-handling)
  4291. ;; Initialize cache.
  4292. (org-element-cache-reset)
  4293. ;; Beginning/end of defun
  4294. (setq-local beginning-of-defun-function 'org-backward-element)
  4295. (setq-local end-of-defun-function
  4296. (lambda ()
  4297. (if (not (org-at-heading-p))
  4298. (org-forward-element)
  4299. (org-forward-element)
  4300. (forward-char -1))))
  4301. ;; Next error for sparse trees
  4302. (setq-local next-error-function 'org-occur-next-match)
  4303. ;; Make commit log messages from Org documents easier.
  4304. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4305. ;; Make sure dependence stuff works reliably, even for users who set it
  4306. ;; too late :-(
  4307. (if org-enforce-todo-dependencies
  4308. (add-hook 'org-blocker-hook
  4309. 'org-block-todo-from-children-or-siblings-or-parent)
  4310. (remove-hook 'org-blocker-hook
  4311. 'org-block-todo-from-children-or-siblings-or-parent))
  4312. (if org-enforce-todo-checkbox-dependencies
  4313. (add-hook 'org-blocker-hook
  4314. 'org-block-todo-from-checkboxes)
  4315. (remove-hook 'org-blocker-hook
  4316. 'org-block-todo-from-checkboxes))
  4317. ;; Align options lines
  4318. (setq-local
  4319. align-mode-rules-list
  4320. '((org-in-buffer-settings
  4321. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4322. (modes . '(org-mode)))))
  4323. ;; Make isearch reveal context
  4324. (setq-local outline-isearch-open-invisible-function
  4325. (lambda (&rest _) (org-show-context 'isearch)))
  4326. ;; Setup the pcomplete hooks
  4327. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4328. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4329. (setq-local pcomplete-default-completion-function #'ignore)
  4330. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4331. (setq-local pcomplete-termination-string "")
  4332. (add-hook 'completion-at-point-functions
  4333. #'pcomplete-completions-at-point nil t)
  4334. (setq-local buffer-face-mode-face 'org-default)
  4335. ;; If empty file that did not turn on Org mode automatically, make
  4336. ;; it to.
  4337. (when (and org-insert-mode-line-in-empty-file
  4338. (called-interactively-p 'any)
  4339. (= (point-min) (point-max)))
  4340. (insert "# -*- mode: org -*-\n\n"))
  4341. (unless org-inhibit-startup
  4342. (org-unmodified
  4343. (when org-startup-with-beamer-mode (org-beamer-mode))
  4344. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4345. (org-table-map-tables
  4346. (cond ((and org-startup-align-all-tables
  4347. org-startup-shrink-all-tables)
  4348. (lambda () (org-table-align) (org-table-shrink)))
  4349. (org-startup-align-all-tables #'org-table-align)
  4350. (t #'org-table-shrink))
  4351. t))
  4352. (when org-startup-with-inline-images (org-display-inline-images))
  4353. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4354. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4355. (when org-startup-truncated (setq truncate-lines t))
  4356. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4357. ;; Activate `org-table-header-line-mode'
  4358. (when org-table-header-line-p
  4359. (org-table-header-line-mode 1))
  4360. ;; Set up Org menus
  4361. (org-menu-define)
  4362. ;; Try to set `org-hide' face correctly.
  4363. (let ((foreground (org-find-invisible-foreground)))
  4364. (when foreground
  4365. (set-face-foreground 'org-hide foreground))))
  4366. ;; Update `customize-package-emacs-version-alist'
  4367. (add-to-list 'customize-package-emacs-version-alist
  4368. '(Org ("8.0" . "24.4")
  4369. ("8.1" . "24.4")
  4370. ("8.2" . "24.4")
  4371. ("8.2.7" . "24.4")
  4372. ("8.3" . "26.1")
  4373. ("9.0" . "26.1")
  4374. ("9.1" . "26.1")
  4375. ("9.2" . "27.1")
  4376. ("9.3" . "27.1")))
  4377. (defvar org-mode-transpose-word-syntax-table
  4378. (let ((st (make-syntax-table text-mode-syntax-table)))
  4379. (dolist (c org-emphasis-alist st)
  4380. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4381. (when (fboundp 'abbrev-table-put)
  4382. (abbrev-table-put org-mode-abbrev-table
  4383. :parents (list text-mode-abbrev-table)))
  4384. (defun org-find-invisible-foreground ()
  4385. (let ((candidates (remove
  4386. "unspecified-bg"
  4387. (nconc
  4388. (list (face-background 'default)
  4389. (face-background 'org-default))
  4390. (mapcar
  4391. (lambda (alist)
  4392. (when (boundp alist)
  4393. (cdr (assq 'background-color (symbol-value alist)))))
  4394. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4395. (list (face-foreground 'org-hide))))))
  4396. (car (remove nil candidates))))
  4397. (defun org-current-time (&optional rounding-minutes past)
  4398. "Current time, possibly rounded to ROUNDING-MINUTES.
  4399. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4400. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4401. the rounding returns a past time."
  4402. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4403. (car org-time-stamp-rounding-minutes)))
  4404. (now (current-time)))
  4405. (if (< r 1)
  4406. now
  4407. (let* ((time (decode-time now))
  4408. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4409. (nthcdr 2 time))))
  4410. (if (or (not past) (org-time-less-p res now))
  4411. res
  4412. (org-time-subtract res (* r 60)))))))
  4413. (defun org-today ()
  4414. "Return today date, considering `org-extend-today-until'."
  4415. (time-to-days
  4416. (org-time-since (* 3600 org-extend-today-until))))
  4417. ;;;; Font-Lock stuff, including the activators
  4418. (require 'font-lock)
  4419. (defconst org-match-sexp-depth 3
  4420. "Number of stacked braces for sub/superscript matching.")
  4421. (defun org-create-multibrace-regexp (left right n)
  4422. "Create a regular expression which will match a balanced sexp.
  4423. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4424. as single character strings.
  4425. The regexp returned will match the entire expression including the
  4426. delimiters. It will also define a single group which contains the
  4427. match except for the outermost delimiters. The maximum depth of
  4428. stacked delimiters is N. Escaping delimiters is not possible."
  4429. (let* ((nothing (concat "[^" left right "]*?"))
  4430. (or "\\|")
  4431. (re nothing)
  4432. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4433. (while (> n 1)
  4434. (setq n (1- n)
  4435. re (concat re or next)
  4436. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4437. (concat left "\\(" re "\\)" right)))
  4438. (defconst org-match-substring-regexp
  4439. (concat
  4440. "\\(\\S-\\)\\([_^]\\)\\("
  4441. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4442. "\\|"
  4443. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4444. "\\|"
  4445. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4446. "The regular expression matching a sub- or superscript.")
  4447. (defconst org-match-substring-with-braces-regexp
  4448. (concat
  4449. "\\(\\S-\\)\\([_^]\\)"
  4450. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4451. "The regular expression matching a sub- or superscript, forcing braces.")
  4452. (defvar org-emph-face nil)
  4453. (defun org-do-emphasis-faces (limit)
  4454. "Run through the buffer and emphasize strings."
  4455. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4456. (car org-emphasis-regexp-components))))
  4457. (catch :exit
  4458. (while (re-search-forward quick-re limit t)
  4459. (let* ((marker (match-string 2))
  4460. (verbatim? (member marker '("~" "="))))
  4461. (when (save-excursion
  4462. (goto-char (match-beginning 0))
  4463. (and
  4464. ;; Do not match table hlines.
  4465. (not (and (equal marker "+")
  4466. (org-match-line
  4467. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4468. ;; Do not match headline stars. Do not consider
  4469. ;; stars of a headline as closing marker for bold
  4470. ;; markup either.
  4471. (not (and (equal marker "*")
  4472. (save-excursion
  4473. (forward-char)
  4474. (skip-chars-backward "*")
  4475. (looking-at-p org-outline-regexp-bol))))
  4476. ;; Match full emphasis markup regexp.
  4477. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4478. ;; Do not span over paragraph boundaries.
  4479. (not (string-match-p org-element-paragraph-separate
  4480. (match-string 2)))
  4481. ;; Do not span over cells in table rows.
  4482. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4483. (string-match-p "|" (match-string 4))))))
  4484. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  4485. (font-lock-prepend-text-property
  4486. (match-beginning 2) (match-end 2) 'face face)
  4487. (when verbatim?
  4488. (org-remove-flyspell-overlays-in
  4489. (match-beginning 0) (match-end 0))
  4490. (remove-text-properties (match-beginning 2) (match-end 2)
  4491. '(display t invisible t intangible t)))
  4492. (add-text-properties (match-beginning 2) (match-end 2)
  4493. '(font-lock-multiline t org-emphasis t))
  4494. (when (and org-hide-emphasis-markers
  4495. (not (org-at-comment-p)))
  4496. (add-text-properties (match-end 4) (match-beginning 5)
  4497. '(invisible org-link))
  4498. (add-text-properties (match-beginning 3) (match-end 3)
  4499. '(invisible org-link)))
  4500. (throw :exit t))))))))
  4501. (defun org-emphasize (&optional char)
  4502. "Insert or change an emphasis, i.e. a font like bold or italic.
  4503. If there is an active region, change that region to a new emphasis.
  4504. If there is no region, just insert the marker characters and position
  4505. the cursor between them.
  4506. CHAR should be the marker character. If it is a space, it means to
  4507. remove the emphasis of the selected region.
  4508. If CHAR is not given (for example in an interactive call) it will be
  4509. prompted for."
  4510. (interactive)
  4511. (let ((erc org-emphasis-regexp-components)
  4512. (string "") beg end move s)
  4513. (if (org-region-active-p)
  4514. (setq beg (region-beginning)
  4515. end (region-end)
  4516. string (buffer-substring beg end))
  4517. (setq move t))
  4518. (unless char
  4519. (message "Emphasis marker or tag: [%s]"
  4520. (mapconcat #'car org-emphasis-alist ""))
  4521. (setq char (read-char-exclusive)))
  4522. (if (equal char ?\s)
  4523. (setq s ""
  4524. move nil)
  4525. (unless (assoc (char-to-string char) org-emphasis-alist)
  4526. (user-error "No such emphasis marker: \"%c\"" char))
  4527. (setq s (char-to-string char)))
  4528. (while (and (> (length string) 1)
  4529. (equal (substring string 0 1) (substring string -1))
  4530. (assoc (substring string 0 1) org-emphasis-alist))
  4531. (setq string (substring string 1 -1)))
  4532. (setq string (concat s string s))
  4533. (when beg (delete-region beg end))
  4534. (unless (or (bolp)
  4535. (string-match (concat "[" (nth 0 erc) "\n]")
  4536. (char-to-string (char-before (point)))))
  4537. (insert " "))
  4538. (unless (or (eobp)
  4539. (string-match (concat "[" (nth 1 erc) "\n]")
  4540. (char-to-string (char-after (point)))))
  4541. (insert " ") (backward-char 1))
  4542. (insert string)
  4543. (and move (backward-char 1))))
  4544. (defconst org-nonsticky-props
  4545. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4546. (defsubst org-rear-nonsticky-at (pos)
  4547. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4548. (defun org-activate-links (limit)
  4549. "Add link properties to links.
  4550. This includes angle, plain, and bracket links."
  4551. (catch :exit
  4552. (while (re-search-forward org-link-any-re limit t)
  4553. (let* ((start (match-beginning 0))
  4554. (end (match-end 0))
  4555. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4556. (visible-end (or (match-end 3) (match-end 2)))
  4557. (style (cond ((eq ?< (char-after start)) 'angle)
  4558. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4559. (t 'plain))))
  4560. (when (and (memq style org-highlight-links)
  4561. ;; Do not span over paragraph boundaries.
  4562. (not (string-match-p org-element-paragraph-separate
  4563. (match-string 0)))
  4564. ;; Do not confuse plain links with tags.
  4565. (not (and (eq style 'plain)
  4566. (let ((face (get-text-property
  4567. (max (1- start) (point-min)) 'face)))
  4568. (if (consp face) (memq 'org-tag face)
  4569. (eq 'org-tag face))))))
  4570. (let* ((link-object (save-excursion
  4571. (goto-char start)
  4572. (save-match-data (org-element-link-parser))))
  4573. (link (org-element-property :raw-link link-object))
  4574. (type (org-element-property :type link-object))
  4575. (path (org-element-property :path link-object))
  4576. (properties ;for link's visible part
  4577. (list
  4578. 'face (pcase (org-link-get-parameter type :face)
  4579. ((and (pred functionp) face) (funcall face path))
  4580. ((and (pred facep) face) face)
  4581. ((and (pred consp) face) face) ;anonymous
  4582. (_ 'org-link))
  4583. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4584. 'highlight)
  4585. 'keymap (or (org-link-get-parameter type :keymap)
  4586. org-mouse-map)
  4587. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4588. ((and (pred stringp) echo) echo)
  4589. ((and (pred functionp) echo) echo)
  4590. (_ (concat "LINK: " link)))
  4591. 'htmlize-link (pcase (org-link-get-parameter type
  4592. :htmlize-link)
  4593. ((and (pred functionp) f) (funcall f))
  4594. (_ `(:uri ,link)))
  4595. 'font-lock-multiline t)))
  4596. (org-remove-flyspell-overlays-in start end)
  4597. (org-rear-nonsticky-at end)
  4598. (if (not (eq 'bracket style))
  4599. (add-text-properties start end properties)
  4600. ;; Handle invisible parts in bracket links.
  4601. (remove-text-properties start end '(invisible nil))
  4602. (let ((hidden
  4603. (append `(invisible
  4604. ,(or (org-link-get-parameter type :display)
  4605. 'org-link))
  4606. properties)))
  4607. (add-text-properties start visible-start hidden)
  4608. (add-text-properties visible-start visible-end properties)
  4609. (add-text-properties visible-end end hidden)
  4610. (org-rear-nonsticky-at visible-start)
  4611. (org-rear-nonsticky-at visible-end)))
  4612. (let ((f (org-link-get-parameter type :activate-func)))
  4613. (when (functionp f)
  4614. (funcall f start end path (eq style 'bracket))))
  4615. (throw :exit t))))) ;signal success
  4616. nil))
  4617. (defun org-activate-code (limit)
  4618. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4619. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4620. (remove-text-properties (match-beginning 0) (match-end 0)
  4621. '(display t invisible t intangible t))
  4622. t))
  4623. (defcustom org-src-fontify-natively t
  4624. "When non-nil, fontify code in code blocks.
  4625. See also the `org-block' face."
  4626. :type 'boolean
  4627. :version "26.1"
  4628. :package-version '(Org . "8.3")
  4629. :group 'org-appearance
  4630. :group 'org-babel)
  4631. (defcustom org-allow-promoting-top-level-subtree nil
  4632. "When non-nil, allow promoting a top level subtree.
  4633. The leading star of the top level headline will be replaced
  4634. by a #."
  4635. :type 'boolean
  4636. :version "24.1"
  4637. :group 'org-appearance)
  4638. (defun org-fontify-meta-lines-and-blocks (limit)
  4639. (condition-case nil
  4640. (org-fontify-meta-lines-and-blocks-1 limit)
  4641. (error (message "Org mode fontification error in %S at %d"
  4642. (current-buffer)
  4643. (line-number-at-pos)))))
  4644. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4645. "Fontify #+ lines and blocks."
  4646. (let ((case-fold-search t))
  4647. (when (re-search-forward
  4648. (rx bol (group (zero-or-more blank) "#"
  4649. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4650. space
  4651. eol))
  4652. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4653. (zero-or-more blank)
  4654. (group (group (zero-or-more (not (any " \t\n"))))
  4655. (zero-or-more blank)
  4656. (group (zero-or-more any)))))
  4657. limit t)
  4658. (let ((beg (match-beginning 0))
  4659. (end-of-beginline (match-end 0))
  4660. (block-start (match-end 0)) ; includes the \n at end of #+begin line
  4661. (block-end nil) ; will include \n after end of block content
  4662. (lang (match-string 7)) ; the language, if it is an src block
  4663. (bol-after-beginline (line-beginning-position 2))
  4664. (dc1 (downcase (match-string 2)))
  4665. (dc3 (downcase (match-string 3)))
  4666. (whole-blockline org-fontify-whole-block-delimiter-line)
  4667. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4668. (cond
  4669. ((and (match-end 4) (equal dc3 "+begin"))
  4670. ;; Truly a block
  4671. (setq block-type (downcase (match-string 5))
  4672. quoting (member block-type org-protecting-blocks)) ; src, example, export, maybe more
  4673. (when (re-search-forward
  4674. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4675. (seq (zero-or-more blank)
  4676. "#+end"
  4677. ,(match-string 4)
  4678. word-end
  4679. (zero-or-more any)))))
  4680. nil t) ;; on purpose, we look further than LIMIT
  4681. ;; We do have a matching #+end line
  4682. (setq beg-of-endline (match-beginning 0)
  4683. end-of-endline (match-end 0)
  4684. nl-before-endline (1- (match-beginning 0)))
  4685. (setq block-end (match-beginning 0)) ; includes the final newline.
  4686. (when quoting
  4687. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4688. (remove-text-properties beg end-of-endline
  4689. '(display t invisible t intangible t)))
  4690. (add-text-properties
  4691. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4692. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4693. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4694. (cond
  4695. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4696. (org-src-font-lock-fontify-block lang block-start block-end)
  4697. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4698. (quoting
  4699. (add-text-properties
  4700. bol-after-beginline beg-of-endline
  4701. (list 'face
  4702. (list :inherit
  4703. (let ((face-name
  4704. (intern (format "org-block-%s" lang))))
  4705. (append (and (facep face-name) (list face-name))
  4706. '(org-block)))))))
  4707. ((not org-fontify-quote-and-verse-blocks))
  4708. ((string= block-type "quote")
  4709. (add-face-text-property
  4710. bol-after-beginline beg-of-endline 'org-quote t))
  4711. ((string= block-type "verse")
  4712. (add-face-text-property
  4713. bol-after-beginline beg-of-endline 'org-verse t)))
  4714. ;; Fontify the #+begin and #+end lines of the blocks
  4715. (add-text-properties
  4716. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4717. '(face org-block-begin-line))
  4718. (unless (string-prefix-p "*" (match-string 1))
  4719. (add-text-properties
  4720. beg-of-endline
  4721. (if whole-blockline
  4722. (let ((beg-of-next-line (1+ end-of-endline)))
  4723. (min (point-max) beg-of-next-line))
  4724. (min (point-max) end-of-endline))
  4725. '(face org-block-end-line)))
  4726. t))
  4727. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  4728. (org-remove-flyspell-overlays-in
  4729. (match-beginning 0)
  4730. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4731. (add-text-properties
  4732. beg (match-end 3)
  4733. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4734. '(font-lock-fontified t invisible t)
  4735. '(font-lock-fontified t face org-document-info-keyword)))
  4736. (add-text-properties
  4737. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4738. (if (string-equal dc1 "+title:")
  4739. '(font-lock-fontified t face org-document-title)
  4740. '(font-lock-fontified t face org-document-info))))
  4741. ((string-prefix-p "+caption" dc1)
  4742. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4743. (remove-text-properties (match-beginning 0) (match-end 0)
  4744. '(display t invisible t intangible t))
  4745. ;; Handle short captions.
  4746. (save-excursion
  4747. (beginning-of-line)
  4748. (looking-at (rx (group (zero-or-more blank)
  4749. "#+caption"
  4750. (optional "[" (zero-or-more any) "]")
  4751. ":")
  4752. (zero-or-more blank))))
  4753. (add-text-properties (line-beginning-position) (match-end 1)
  4754. '(font-lock-fontified t face org-meta-line))
  4755. (add-text-properties (match-end 0) (line-end-position)
  4756. '(font-lock-fontified t face org-block))
  4757. t)
  4758. ((member dc3 '(" " ""))
  4759. ; Just a comment, the plus was not there
  4760. (org-remove-flyspell-overlays-in beg (match-end 0))
  4761. (add-text-properties
  4762. beg (match-end 0)
  4763. '(font-lock-fontified t face font-lock-comment-face)))
  4764. (t ;; just any other in-buffer setting, but not indented
  4765. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4766. (remove-text-properties (match-beginning 0) (match-end 0)
  4767. '(display t invisible t intangible t))
  4768. (add-text-properties beg (match-end 0)
  4769. '(font-lock-fontified t face org-meta-line))
  4770. t))))))
  4771. (defun org-fontify-drawers (limit)
  4772. "Fontify drawers."
  4773. (when (re-search-forward org-drawer-regexp limit t)
  4774. (add-text-properties
  4775. (line-beginning-position) (line-beginning-position 2)
  4776. '(font-lock-fontified t face org-drawer))
  4777. (org-remove-flyspell-overlays-in
  4778. (line-beginning-position) (line-beginning-position 2))
  4779. t))
  4780. (defun org-fontify-macros (limit)
  4781. "Fontify macros."
  4782. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4783. (let ((begin (match-beginning 0))
  4784. (opening-end (match-beginning 1)))
  4785. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4786. (match-string 1))
  4787. (let ((end (match-end 1))
  4788. (closing-start (match-beginning 1)))
  4789. (add-text-properties
  4790. begin end
  4791. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4792. (org-remove-flyspell-overlays-in begin end)
  4793. (when org-hide-macro-markers
  4794. (add-text-properties begin opening-end '(invisible t))
  4795. (add-text-properties closing-start end '(invisible t)))
  4796. t)))))
  4797. (defun org-fontify-extend-region (beg end _old-len)
  4798. (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4799. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4800. (extend (lambda (r1 r2 dir)
  4801. (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
  4802. (replace-regexp-in-string "[][]" r2
  4803. (match-string-no-properties 0)))))
  4804. (re-search-forward (regexp-quote re) nil t dir)))))
  4805. (save-match-data
  4806. (save-excursion
  4807. (goto-char beg)
  4808. (back-to-indentation)
  4809. (cond ((looking-at end-re)
  4810. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4811. ((looking-at begin-re)
  4812. (cons beg (or (funcall extend "end" "]" 1) end)))
  4813. (t (cons beg end)))))))
  4814. (defun org-activate-footnote-links (limit)
  4815. "Add text properties for footnotes."
  4816. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4817. (when fn
  4818. (let* ((beg (nth 1 fn))
  4819. (end (nth 2 fn))
  4820. (label (car fn))
  4821. (referencep (/= (line-beginning-position) beg)))
  4822. (when (and referencep (nth 3 fn))
  4823. (save-excursion
  4824. (goto-char beg)
  4825. (search-forward (or label "fn:"))
  4826. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4827. (add-text-properties beg end
  4828. (list 'mouse-face 'highlight
  4829. 'keymap org-mouse-map
  4830. 'help-echo
  4831. (if referencep "Footnote reference"
  4832. "Footnote definition")
  4833. 'font-lock-fontified t
  4834. 'font-lock-multiline t
  4835. 'face 'org-footnote))))))
  4836. (defun org-activate-dates (limit)
  4837. "Add text properties for dates."
  4838. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4839. (not (equal (char-before (match-beginning 0)) 91)))
  4840. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4841. (add-text-properties (match-beginning 0) (match-end 0)
  4842. (list 'mouse-face 'highlight
  4843. 'keymap org-mouse-map))
  4844. (org-rear-nonsticky-at (match-end 0))
  4845. (when org-display-custom-times
  4846. ;; If it's a date range, activate custom time for second date.
  4847. (when (match-end 3)
  4848. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4849. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4850. t))
  4851. (defun org-activate-target-links (limit)
  4852. "Add text properties for target matches."
  4853. (when org-target-link-regexp
  4854. (let ((case-fold-search t))
  4855. ;; `org-target-link-regexp' matches one character before the
  4856. ;; actual target.
  4857. (unless (bolp) (forward-char -1))
  4858. (when (re-search-forward org-target-link-regexp limit t)
  4859. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4860. (add-text-properties (match-beginning 1) (match-end 1)
  4861. (list 'mouse-face 'highlight
  4862. 'keymap org-mouse-map
  4863. 'help-echo "Radio target link"
  4864. 'org-linked-text t))
  4865. (org-rear-nonsticky-at (match-end 1))
  4866. t))))
  4867. (defvar org-latex-and-related-regexp nil
  4868. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4869. (defun org-compute-latex-and-related-regexp ()
  4870. "Compute regular expression for LaTeX, entities and sub/superscript.
  4871. Result depends on variable `org-highlight-latex-and-related'."
  4872. (let ((re-sub
  4873. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4874. ((eq org-use-sub-superscripts '{})
  4875. (list org-match-substring-with-braces-regexp))
  4876. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4877. (re-latex
  4878. (when (or (memq 'latex org-highlight-latex-and-related)
  4879. (memq 'native org-highlight-latex-and-related))
  4880. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4881. (delq nil
  4882. (mapcar (lambda (x)
  4883. (and (member (car x) matchers) (nth 1 x)))
  4884. org-latex-regexps)))))
  4885. (re-entities
  4886. (when (memq 'entities org-highlight-latex-and-related)
  4887. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4888. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4889. (setq-local org-latex-and-related-regexp
  4890. (mapconcat #'identity
  4891. (append re-latex re-entities re-sub)
  4892. "\\|"))))
  4893. (defun org-do-latex-and-related (_limit)
  4894. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4895. Stop at first highlighted object, if any. Return t if some
  4896. highlighting was done, nil otherwise."
  4897. (when (org-string-nw-p org-latex-and-related-regexp)
  4898. (catch 'found
  4899. (while (re-search-forward org-latex-and-related-regexp
  4900. nil t) ;; on purpose, we ignore LIMIT
  4901. (unless (cl-some (lambda (f) (memq f '(org-code org-verbatim underline
  4902. org-special-keyword)))
  4903. (save-excursion
  4904. (goto-char (1+ (match-beginning 0)))
  4905. (face-at-point nil t)))
  4906. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4907. '(?_ ?^))
  4908. 1
  4909. 0))
  4910. (start (+ offset (match-beginning 0)))
  4911. (end (match-end 0)))
  4912. (if (memq 'native org-highlight-latex-and-related)
  4913. (org-src-font-lock-fontify-block "latex" start end)
  4914. (font-lock-prepend-text-property start end
  4915. 'face 'org-latex-and-related))
  4916. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4917. '(font-lock-multiline t)))
  4918. (throw 'found t)))
  4919. nil)))
  4920. (defun org-restart-font-lock ()
  4921. "Restart `font-lock-mode', to force refontification."
  4922. (when (and (boundp 'font-lock-mode) font-lock-mode)
  4923. (font-lock-mode -1)
  4924. (font-lock-mode 1)))
  4925. (defun org-activate-tags (limit)
  4926. (when (re-search-forward org-tag-line-re limit t)
  4927. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4928. (add-text-properties (match-beginning 1) (match-end 1)
  4929. (list 'mouse-face 'highlight
  4930. 'keymap org-mouse-map))
  4931. (org-rear-nonsticky-at (match-end 1))
  4932. t))
  4933. (defun org-outline-level ()
  4934. "Compute the outline level of the heading at point.
  4935. If this is called at a normal headline, the level is the number
  4936. of stars. Use `org-reduced-level' to remove the effect of
  4937. `org-odd-levels'. Unlike to `org-current-level', this function
  4938. takes into consideration inlinetasks."
  4939. (org-with-wide-buffer
  4940. (end-of-line)
  4941. (if (re-search-backward org-outline-regexp-bol nil t)
  4942. (1- (- (match-end 0) (match-beginning 0)))
  4943. 0)))
  4944. (defvar org-font-lock-keywords nil)
  4945. (defsubst org-re-property (property &optional literal allow-null value)
  4946. "Return a regexp matching a PROPERTY line.
  4947. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4948. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4949. non-nil, match properties even without a value.
  4950. Match group 3 is set to the value when it exists. If there is no
  4951. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4952. With optional argument VALUE, match only property lines with
  4953. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4954. unless LITERAL is non-nil."
  4955. (concat
  4956. "^\\(?4:[ \t]*\\)"
  4957. (format "\\(?1::\\(?2:%s\\):\\)"
  4958. (if literal property (regexp-quote property)))
  4959. (cond (value
  4960. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4961. (if literal value (regexp-quote value))))
  4962. (allow-null
  4963. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4964. (t
  4965. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4966. (defconst org-property-re
  4967. (org-re-property "\\S-+" 'literal t)
  4968. "Regular expression matching a property line.
  4969. There are four matching groups:
  4970. 1: :PROPKEY: including the leading and trailing colon,
  4971. 2: PROPKEY without the leading and trailing colon,
  4972. 3: PROPVAL without leading or trailing spaces,
  4973. 4: the indentation of the current line,
  4974. 5: trailing whitespace.")
  4975. (defvar org-font-lock-hook nil
  4976. "Functions to be called for special font lock stuff.")
  4977. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4978. (defvar org-font-lock-set-keywords-hook nil
  4979. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4980. This is called after `org-font-lock-extra-keywords' is defined, but before
  4981. it is installed to be used by font lock. This can be useful if something
  4982. needs to be inserted at a specific position in the font-lock sequence.")
  4983. (defun org-font-lock-hook (limit)
  4984. "Run `org-font-lock-hook' within LIMIT."
  4985. (run-hook-with-args 'org-font-lock-hook limit))
  4986. (defun org-set-font-lock-defaults ()
  4987. "Set font lock defaults for the current buffer."
  4988. (let* ((em org-fontify-emphasized-text)
  4989. (lk org-highlight-links)
  4990. (org-font-lock-extra-keywords
  4991. (list
  4992. ;; Call the hook
  4993. '(org-font-lock-hook)
  4994. ;; Headlines
  4995. `(,(if org-fontify-whole-heading-line
  4996. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4997. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4998. (1 (org-get-level-face 1))
  4999. (2 (org-get-level-face 2))
  5000. (3 (org-get-level-face 3)))
  5001. ;; Table lines
  5002. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5003. (1 'org-table t))
  5004. ;; Table internals
  5005. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5006. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5007. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5008. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5009. ;; Properties
  5010. (list org-property-re
  5011. '(1 'org-special-keyword t)
  5012. '(3 'org-property-value t))
  5013. ;; Drawers
  5014. '(org-fontify-drawers)
  5015. ;; Link related fontification.
  5016. '(org-activate-links)
  5017. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5018. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5019. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5020. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5021. ;; Targets.
  5022. (list org-radio-target-regexp '(0 'org-target t))
  5023. (list org-target-regexp '(0 'org-target t))
  5024. ;; Diary sexps.
  5025. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5026. ;; Macro
  5027. '(org-fontify-macros)
  5028. ;; TODO keyword
  5029. (list (format org-heading-keyword-regexp-format
  5030. org-todo-regexp)
  5031. '(2 (org-get-todo-face 2) t))
  5032. ;; TODO
  5033. (when org-fontify-todo-headline
  5034. (list (format org-heading-keyword-regexp-format
  5035. (concat
  5036. "\\(?:"
  5037. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  5038. "\\)"))
  5039. '(2 'org-headline-todo t)))
  5040. ;; DONE
  5041. (when org-fontify-done-headline
  5042. (list (format org-heading-keyword-regexp-format
  5043. (concat
  5044. "\\(?:"
  5045. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5046. "\\)"))
  5047. '(2 'org-headline-done t)))
  5048. ;; Priorities
  5049. '(org-font-lock-add-priority-faces)
  5050. ;; Tags
  5051. '(org-font-lock-add-tag-faces)
  5052. ;; Tags groups
  5053. (when (and org-group-tags org-tag-groups-alist)
  5054. (list (concat org-outline-regexp-bol ".+\\(:"
  5055. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5056. ":\\).*$")
  5057. '(1 'org-tag-group prepend)))
  5058. ;; Special keywords
  5059. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5060. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5061. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5062. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5063. ;; Emphasis
  5064. (when em '(org-do-emphasis-faces))
  5065. ;; Checkboxes
  5066. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5067. 1 'org-checkbox prepend)
  5068. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5069. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5070. (0 (org-get-checkbox-statistics-face) t)))
  5071. ;; Description list items
  5072. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5073. 1 'org-list-dt prepend)
  5074. ;; ARCHIVEd headings
  5075. (list (concat
  5076. org-outline-regexp-bol
  5077. "\\(.*:" org-archive-tag ":.*\\)")
  5078. '(1 'org-archived prepend))
  5079. ;; Specials
  5080. '(org-do-latex-and-related)
  5081. '(org-fontify-entities)
  5082. '(org-raise-scripts)
  5083. ;; Code
  5084. '(org-activate-code (1 'org-code t))
  5085. ;; COMMENT
  5086. (list (format
  5087. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5088. org-todo-regexp
  5089. org-comment-string)
  5090. '(9 'org-special-keyword t))
  5091. ;; Blocks and meta lines
  5092. '(org-fontify-meta-lines-and-blocks))))
  5093. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5094. (run-hooks 'org-font-lock-set-keywords-hook)
  5095. ;; Now set the full font-lock-keywords
  5096. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5097. (setq-local font-lock-defaults
  5098. '(org-font-lock-keywords t nil nil backward-paragraph))
  5099. (setq-local font-lock-extend-after-change-region-function
  5100. #'org-fontify-extend-region)
  5101. (kill-local-variable 'font-lock-keywords)
  5102. nil))
  5103. (defun org-toggle-pretty-entities ()
  5104. "Toggle the composition display of entities as UTF8 characters."
  5105. (interactive)
  5106. (setq-local org-pretty-entities (not org-pretty-entities))
  5107. (org-restart-font-lock)
  5108. (if org-pretty-entities
  5109. (message "Entities are now displayed as UTF8 characters")
  5110. (save-restriction
  5111. (widen)
  5112. (decompose-region (point-min) (point-max))
  5113. (message "Entities are now displayed as plain text"))))
  5114. (defvar-local org-custom-properties-overlays nil
  5115. "List of overlays used for custom properties.")
  5116. (defun org-toggle-custom-properties-visibility ()
  5117. "Display or hide properties in `org-custom-properties'."
  5118. (interactive)
  5119. (if org-custom-properties-overlays
  5120. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5121. (setq org-custom-properties-overlays nil))
  5122. (when org-custom-properties
  5123. (org-with-wide-buffer
  5124. (goto-char (point-min))
  5125. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5126. (while (re-search-forward regexp nil t)
  5127. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5128. (when (and end (< (point) end))
  5129. ;; Hide first custom property in current drawer.
  5130. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5131. (overlay-put o 'invisible t)
  5132. (overlay-put o 'org-custom-property t)
  5133. (push o org-custom-properties-overlays))
  5134. ;; Hide additional custom properties in the same drawer.
  5135. (while (re-search-forward regexp end t)
  5136. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5137. (overlay-put o 'invisible t)
  5138. (overlay-put o 'org-custom-property t)
  5139. (push o org-custom-properties-overlays)))))
  5140. ;; Each entry is limited to a single property drawer.
  5141. (outline-next-heading)))))))
  5142. (defun org-fontify-entities (limit)
  5143. "Find an entity to fontify."
  5144. (let (ee)
  5145. (when org-pretty-entities
  5146. (catch 'match
  5147. ;; "\_ "-family is left out on purpose. Only the first one,
  5148. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5149. ;; confusing when adding a second white space character.
  5150. (while (re-search-forward
  5151. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5152. limit t)
  5153. (when (and (not (org-at-comment-p))
  5154. (setq ee (org-entity-get (match-string 1)))
  5155. (= (length (nth 6 ee)) 1))
  5156. (let* ((end (if (equal (match-string 2) "{}")
  5157. (match-end 2)
  5158. (match-end 1))))
  5159. (add-text-properties
  5160. (match-beginning 0) end
  5161. (list 'font-lock-fontified t))
  5162. (compose-region (match-beginning 0) end
  5163. (nth 6 ee) nil)
  5164. (backward-char 1)
  5165. (throw 'match t))))
  5166. nil))))
  5167. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5168. "Fontify string S like in Org mode."
  5169. (with-temp-buffer
  5170. (insert s)
  5171. (let ((org-odd-levels-only odd-levels))
  5172. (org-mode)
  5173. (org-font-lock-ensure)
  5174. (buffer-string))))
  5175. (defun org-get-level-face (n)
  5176. "Get the right face for match N in font-lock matching of headlines."
  5177. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5178. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5179. (org-f (if org-cycle-level-faces
  5180. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5181. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5182. (cond
  5183. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5184. ((eq n 2) org-f)
  5185. (t (unless org-level-color-stars-only org-f)))))
  5186. (defun org-face-from-face-or-color (context inherit face-or-color)
  5187. "Create a face list that inherits INHERIT, but sets the foreground color.
  5188. When FACE-OR-COLOR is not a string, just return it."
  5189. (if (stringp face-or-color)
  5190. (list :inherit inherit
  5191. (cdr (assoc context org-faces-easy-properties))
  5192. face-or-color)
  5193. face-or-color))
  5194. (defun org-get-todo-face (kwd)
  5195. "Get the right face for a TODO keyword KWD.
  5196. If KWD is a number, get the corresponding match group."
  5197. (when (numberp kwd) (setq kwd (match-string kwd)))
  5198. (or (org-face-from-face-or-color
  5199. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5200. (and (member kwd org-done-keywords) 'org-done)
  5201. 'org-todo))
  5202. (defun org-get-priority-face (priority)
  5203. "Get the right face for PRIORITY.
  5204. PRIORITY is a character."
  5205. (or (org-face-from-face-or-color
  5206. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5207. 'org-priority))
  5208. (defun org-get-tag-face (tag)
  5209. "Get the right face for TAG.
  5210. If TAG is a number, get the corresponding match group."
  5211. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5212. (or (org-face-from-face-or-color
  5213. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5214. 'org-tag)))
  5215. (defvar org-priority-regexp) ; defined later in the file
  5216. (defun org-font-lock-add-priority-faces (limit)
  5217. "Add the special priority faces."
  5218. (while (re-search-forward org-priority-regexp limit t)
  5219. (add-text-properties
  5220. (match-beginning 1) (match-end 1)
  5221. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5222. 'font-lock-fontified t))))
  5223. (defun org-font-lock-add-tag-faces (limit)
  5224. "Add the special tag faces."
  5225. (when (and org-tag-faces org-tags-special-faces-re)
  5226. (while (re-search-forward org-tags-special-faces-re limit t)
  5227. (add-text-properties (match-beginning 1) (match-end 1)
  5228. (list 'face (org-get-tag-face 1)
  5229. 'font-lock-fontified t))
  5230. (backward-char 1))))
  5231. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5232. "Remove fontification and activation overlays from links."
  5233. (font-lock-default-unfontify-region beg end)
  5234. (let* ((buffer-undo-list t)
  5235. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5236. (inhibit-modification-hooks t)
  5237. deactivate-mark buffer-file-name buffer-file-truename)
  5238. (decompose-region beg end)
  5239. (remove-text-properties beg end
  5240. '(mouse-face t keymap t org-linked-text t
  5241. invisible t intangible t
  5242. org-emphasis t))
  5243. (org-remove-font-lock-display-properties beg end)))
  5244. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5245. ((raise 0.3) (height 0.7))
  5246. ((raise -0.5))
  5247. ((raise 0.5)))
  5248. "Display properties for showing superscripts and subscripts.")
  5249. (defun org-remove-font-lock-display-properties (beg end)
  5250. "Remove specific display properties that have been added by font lock.
  5251. The will remove the raise properties that are used to show superscripts
  5252. and subscripts."
  5253. (let (next prop)
  5254. (while (< beg end)
  5255. (setq next (next-single-property-change beg 'display nil end)
  5256. prop (get-text-property beg 'display))
  5257. (when (member prop org-script-display)
  5258. (put-text-property beg next 'display nil))
  5259. (setq beg next))))
  5260. (defun org-raise-scripts (limit)
  5261. "Add raise properties to sub/superscripts."
  5262. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5263. (re-search-forward
  5264. (if (eq org-use-sub-superscripts t)
  5265. org-match-substring-regexp
  5266. org-match-substring-with-braces-regexp)
  5267. limit t))
  5268. (let* ((pos (point)) table-p comment-p
  5269. (mpos (match-beginning 3))
  5270. (emph-p (get-text-property mpos 'org-emphasis))
  5271. (link-p (get-text-property mpos 'mouse-face))
  5272. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5273. (goto-char (point-at-bol))
  5274. (setq table-p (looking-at-p org-table-dataline-regexp)
  5275. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5276. (goto-char pos)
  5277. ;; Handle a_b^c
  5278. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5279. (unless (or comment-p emph-p link-p keyw-p)
  5280. (put-text-property (match-beginning 3) (match-end 0)
  5281. 'display
  5282. (if (equal (char-after (match-beginning 2)) ?^)
  5283. (nth (if table-p 3 1) org-script-display)
  5284. (nth (if table-p 2 0) org-script-display)))
  5285. (add-text-properties (match-beginning 2) (match-end 2)
  5286. (list 'invisible t))
  5287. (when (and (eq (char-after (match-beginning 3)) ?{)
  5288. (eq (char-before (match-end 3)) ?}))
  5289. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5290. (list 'invisible t))
  5291. (add-text-properties (1- (match-end 3)) (match-end 3)
  5292. (list 'invisible t))))
  5293. t)))
  5294. (defun org-remove-empty-overlays-at (pos)
  5295. "Remove outline overlays that do not contain non-white stuff."
  5296. (dolist (o (overlays-at pos))
  5297. (and (eq 'outline (overlay-get o 'invisible))
  5298. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5299. (overlay-end o))))
  5300. (delete-overlay o))))
  5301. (defun org-show-empty-lines-in-parent ()
  5302. "Move to the parent and re-show empty lines before visible headlines."
  5303. (save-excursion
  5304. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5305. (org-cycle-show-empty-lines context))))
  5306. (defun org-files-list ()
  5307. "Return `org-agenda-files' list, plus all open Org files.
  5308. This is useful for operations that need to scan all of a user's
  5309. open and agenda-wise Org files."
  5310. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5311. (dolist (buf (buffer-list))
  5312. (with-current-buffer buf
  5313. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5314. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5315. :test #'equal))))
  5316. files))
  5317. (defsubst org-entry-beginning-position ()
  5318. "Return the beginning position of the current entry."
  5319. (save-excursion (org-back-to-heading t) (point)))
  5320. (defsubst org-entry-end-position ()
  5321. "Return the end position of the current entry."
  5322. (save-excursion (outline-next-heading) (point)))
  5323. (defun org-subtree-end-visible-p ()
  5324. "Is the end of the current subtree visible?"
  5325. (pos-visible-in-window-p
  5326. (save-excursion (org-end-of-subtree t) (point))))
  5327. (defun org-first-headline-recenter ()
  5328. "Move cursor to the first headline and recenter the headline."
  5329. (let ((window (get-buffer-window)))
  5330. (when window
  5331. (goto-char (point-min))
  5332. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5333. (set-window-start window (line-beginning-position))))))
  5334. ;;; Visibility (headlines, blocks, drawers)
  5335. ;;;; Headlines visibility
  5336. (defun org-show-entry ()
  5337. "Show the body directly following this heading.
  5338. Show the heading too, if it is currently invisible."
  5339. (interactive)
  5340. (save-excursion
  5341. (ignore-errors
  5342. (org-back-to-heading t)
  5343. (org-flag-region
  5344. (line-end-position 0)
  5345. (save-excursion
  5346. (if (re-search-forward
  5347. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5348. (match-beginning 1)
  5349. (point-max)))
  5350. nil
  5351. 'outline))))
  5352. (defun org-show-children (&optional level)
  5353. "Show all direct subheadings of this heading.
  5354. Prefix arg LEVEL is how many levels below the current level
  5355. should be shown. Default is enough to cause the following
  5356. heading to appear."
  5357. (interactive "p")
  5358. (save-excursion
  5359. (org-back-to-heading t)
  5360. (let* ((current-level (funcall outline-level))
  5361. (max-level (org-get-valid-level
  5362. current-level
  5363. (if level (prefix-numeric-value level) 1)))
  5364. (end (save-excursion (org-end-of-subtree t t)))
  5365. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5366. (past-first-child nil)
  5367. ;; Make sure to skip inlinetasks.
  5368. (re (format regexp-fmt
  5369. current-level
  5370. (cond
  5371. ((not (featurep 'org-inlinetask)) "")
  5372. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5373. 3))
  5374. (t (1- org-inlinetask-min-level))))))
  5375. ;; Display parent heading.
  5376. (org-flag-heading nil)
  5377. (forward-line)
  5378. ;; Display children. First child may be deeper than expected
  5379. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5380. ;; MAX-LEVEL accordingly.
  5381. (while (re-search-forward re end t)
  5382. (unless past-first-child
  5383. (setq re (format regexp-fmt
  5384. current-level
  5385. (max (funcall outline-level) max-level)))
  5386. (setq past-first-child t))
  5387. (org-flag-heading nil)))))
  5388. (defun org-show-subtree ()
  5389. "Show everything after this heading at deeper levels."
  5390. (interactive)
  5391. (org-flag-region
  5392. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5393. ;;;; Blocks visibility
  5394. (defun org-hide-block-toggle-maybe ()
  5395. "Toggle visibility of block at point.
  5396. Unlike to `org-hide-block-toggle', this function does not throw
  5397. an error. Return a non-nil value when toggling is successful."
  5398. (interactive)
  5399. (ignore-errors (org-hide-block-toggle)))
  5400. (defun org-hide-block-toggle (&optional force)
  5401. "Toggle the visibility of the current block.
  5402. When optional argument FORCE is `off', make block visible. If it
  5403. is non-nil, hide it unconditionally. Throw an error when not at
  5404. a block. Return a non-nil value when toggling is successful."
  5405. (interactive)
  5406. (let ((element (org-element-at-point)))
  5407. (unless (memq (org-element-type element)
  5408. '(center-block comment-block dynamic-block example-block
  5409. export-block quote-block special-block
  5410. src-block verse-block))
  5411. (user-error "Not at a block"))
  5412. (let* ((post (org-element-property :post-affiliated element))
  5413. (start (save-excursion
  5414. (goto-char post)
  5415. (line-end-position)))
  5416. (end (save-excursion
  5417. (goto-char (org-element-property :end element))
  5418. (skip-chars-backward " \t\n")
  5419. (line-end-position))))
  5420. ;; Do nothing when not before or at the block opening line or at
  5421. ;; the block closing line.
  5422. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5423. (cond ((eq force 'off)
  5424. (org-flag-region start end nil 'org-hide-block))
  5425. (force
  5426. (org-flag-region start end t 'org-hide-block))
  5427. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5428. (org-flag-region start end nil 'org-hide-block))
  5429. (t
  5430. (org-flag-region start end t 'org-hide-block)))
  5431. ;; When the block is hidden away, make sure point is left in
  5432. ;; a visible part of the buffer.
  5433. (when (invisible-p (max (1- (point)) (point-min)))
  5434. (goto-char post))
  5435. ;; Signal success.
  5436. t))))
  5437. (defun org-hide-block-toggle-all ()
  5438. "Toggle the visibility of all blocks in the current buffer."
  5439. (org-block-map 'org-hide-block-toggle))
  5440. (defun org-hide-block-all ()
  5441. "Fold all blocks in the current buffer."
  5442. (interactive)
  5443. (org-show-all '(blocks))
  5444. (org-block-map 'org-hide-block-toggle-maybe))
  5445. ;;;; Drawers visibility
  5446. (defun org-cycle-hide-drawers (state &optional exceptions)
  5447. "Re-hide all drawers after a visibility state change.
  5448. STATE should be one of the symbols listed in the docstring of
  5449. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5450. a list of strings specifying which drawers should not be hidden."
  5451. (when (and (derived-mode-p 'org-mode)
  5452. (not (memq state '(overview folded contents))))
  5453. (save-excursion
  5454. (let* ((globalp (eq state 'all))
  5455. (beg (if globalp (point-min) (point)))
  5456. (end (if globalp (point-max)
  5457. (if (eq state 'children)
  5458. (save-excursion (outline-next-heading) (point))
  5459. (org-end-of-subtree t)))))
  5460. (goto-char beg)
  5461. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5462. (unless (member-ignore-case (match-string 1) exceptions)
  5463. (let ((drawer (org-element-at-point)))
  5464. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5465. (org-flag-drawer t drawer)
  5466. ;; Make sure to skip drawer entirely or we might flag
  5467. ;; it another time when matching its ending line with
  5468. ;; `org-drawer-regexp'.
  5469. (goto-char (org-element-property :end drawer))))))))))
  5470. (defun org-flag-drawer (flag &optional element beg end)
  5471. "When FLAG is non-nil, hide the drawer we are at.
  5472. Otherwise make it visible.
  5473. When optional argument ELEMENT is a parsed drawer, as returned by
  5474. `org-element-at-point', hide or show that drawer instead.
  5475. When buffer positions BEG and END are provided, hide or show that
  5476. region as a drawer without further ado."
  5477. (if (and beg end) (org-flag-region beg end flag 'org-hide-drawer)
  5478. (let ((drawer (or element
  5479. (and (save-excursion
  5480. (beginning-of-line)
  5481. (looking-at-p org-drawer-regexp))
  5482. (org-element-at-point)))))
  5483. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5484. (let ((post (org-element-property :post-affiliated drawer)))
  5485. (org-flag-region
  5486. (save-excursion (goto-char post) (line-end-position))
  5487. (save-excursion (goto-char (org-element-property :end drawer))
  5488. (skip-chars-backward " \t\n")
  5489. (line-end-position))
  5490. flag 'org-hide-drawer)
  5491. ;; When the drawer is hidden away, make sure point lies in
  5492. ;; a visible part of the buffer.
  5493. (when (invisible-p (max (1- (point)) (point-min)))
  5494. (goto-char post)))))))
  5495. ;;;; Visibility cycling
  5496. (defvar-local org-cycle-global-status nil)
  5497. (put 'org-cycle-global-status 'org-state t)
  5498. (defvar-local org-cycle-subtree-status nil)
  5499. (put 'org-cycle-subtree-status 'org-state t)
  5500. (defun org-show-all (&optional types)
  5501. "Show all contents in the visible part of the buffer.
  5502. By default, the function expands headings, blocks and drawers.
  5503. When optional argument TYPE is a list of symbols among `blocks',
  5504. `drawers' and `headings', to only expand one specific type."
  5505. (interactive)
  5506. (dolist (type (or types '(blocks drawers headings)))
  5507. (org-flag-region (point-min) (point-max) nil
  5508. (pcase type
  5509. (`blocks 'org-hide-block)
  5510. (`drawers 'org-hide-drawer)
  5511. (`headings 'outline)
  5512. (_ (error "Invalid type: %S" type))))))
  5513. ;;;###autoload
  5514. (defun org-cycle (&optional arg)
  5515. "TAB-action and visibility cycling for Org mode.
  5516. This is the command invoked in Org mode by the `TAB' key. Its main
  5517. purpose is outline visibility cycling, but it also invokes other actions
  5518. in special contexts.
  5519. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5520. the entire
  5521. buffer through 3 states (global cycling)
  5522. 1. OVERVIEW: Show only top-level headlines.
  5523. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5524. 3. SHOW ALL: Show everything.
  5525. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5526. switch to the startup visibility,
  5527. determined by the variable `org-startup-folded', and by any VISIBILITY
  5528. properties in the buffer.
  5529. With a `\\[universal-argument] \\[universal-argument] \
  5530. \\[universal-argument]' prefix argument, show the entire buffer, including
  5531. any drawers.
  5532. When inside a table, re-align the table and move to the next field.
  5533. When point is at the beginning of a headline, rotate the subtree started
  5534. by this line through 3 different states (local cycling)
  5535. 1. FOLDED: Only the main headline is shown.
  5536. 2. CHILDREN: The main headline and the direct children are shown.
  5537. From this state, you can move to one of the children
  5538. and zoom in further.
  5539. 3. SUBTREE: Show the entire subtree, including body text.
  5540. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5541. When point is at the beginning of an empty headline and the variable
  5542. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5543. of the headline by demoting and promoting it to likely levels. This
  5544. speeds up creation document structure by pressing `TAB' once or several
  5545. times right after creating a new headline.
  5546. When there is a numeric prefix, go up to a heading with level ARG, do
  5547. a `show-subtree' and return to the previous cursor position. If ARG
  5548. is negative, go up that many levels.
  5549. When point is not at the beginning of a headline, execute the global
  5550. binding for `TAB', which is re-indenting the line. See the option
  5551. `org-cycle-emulate-tab' for details.
  5552. As a special case, if point is at the beginning of the buffer and there is
  5553. no headline in line 1, this function will act as if called with prefix arg
  5554. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5555. prefix arg, but only
  5556. if the variable `org-cycle-global-at-bob' is t."
  5557. (interactive "P")
  5558. (org-load-modules-maybe)
  5559. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5560. (and org-cycle-level-after-item/entry-creation
  5561. (or (org-cycle-level)
  5562. (org-cycle-item-indentation))))
  5563. (let* ((limit-level
  5564. (or org-cycle-max-level
  5565. (and (boundp 'org-inlinetask-min-level)
  5566. org-inlinetask-min-level
  5567. (1- org-inlinetask-min-level))))
  5568. (nstars (and limit-level
  5569. (if org-odd-levels-only
  5570. (and limit-level (1- (* limit-level 2)))
  5571. limit-level)))
  5572. (org-outline-regexp
  5573. (if (not (derived-mode-p 'org-mode))
  5574. outline-regexp
  5575. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5576. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5577. (not (looking-at org-outline-regexp))))
  5578. (org-cycle-hook
  5579. (if bob-special
  5580. (delq 'org-optimize-window-after-visibility-change
  5581. (copy-sequence org-cycle-hook))
  5582. org-cycle-hook))
  5583. (pos (point)))
  5584. (cond
  5585. ((equal arg '(16))
  5586. (setq last-command 'dummy)
  5587. (org-set-startup-visibility)
  5588. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5589. ((equal arg '(64))
  5590. (org-show-all)
  5591. (org-unlogged-message "Entire buffer visible, including drawers"))
  5592. ((equal arg '(4)) (org-cycle-internal-global))
  5593. ;; Try hiding block at point.
  5594. ((org-hide-block-toggle-maybe))
  5595. ;; Try cdlatex TAB completion
  5596. ((org-try-cdlatex-tab))
  5597. ;; Table: enter it or move to the next field.
  5598. ((org-at-table-p 'any)
  5599. (if (org-at-table.el-p)
  5600. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5601. Use `\\[org-edit-special]' to edit table.el tables"))
  5602. (if arg (org-table-edit-field t)
  5603. (org-table-justify-field-maybe)
  5604. (call-interactively 'org-table-next-field))))
  5605. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5606. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5607. (bob-special (org-cycle-internal-global))
  5608. ;; Drawers: delegate to `org-flag-drawer'.
  5609. ((save-excursion
  5610. (beginning-of-line 1)
  5611. (looking-at org-drawer-regexp))
  5612. (org-flag-drawer ; toggle block visibility
  5613. (not (get-char-property (match-end 0) 'invisible))))
  5614. ;; Show-subtree, ARG levels up from here.
  5615. ((integerp arg)
  5616. (save-excursion
  5617. (org-back-to-heading)
  5618. (outline-up-heading (if (< arg 0) (- arg)
  5619. (- (funcall outline-level) arg)))
  5620. (org-show-subtree)))
  5621. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5622. ((and (featurep 'org-inlinetask)
  5623. (org-inlinetask-at-task-p)
  5624. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5625. (org-inlinetask-toggle-visibility))
  5626. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5627. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5628. (save-excursion (move-beginning-of-line 1)
  5629. (looking-at org-outline-regexp)))
  5630. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5631. (org-cycle-internal-local))
  5632. ;; From there: TAB emulation and template completion.
  5633. (buffer-read-only (org-back-to-heading))
  5634. ((run-hook-with-args-until-success
  5635. 'org-tab-after-check-for-cycling-hook))
  5636. ((run-hook-with-args-until-success
  5637. 'org-tab-before-tab-emulation-hook))
  5638. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5639. (or (not (bolp))
  5640. (not (looking-at org-outline-regexp))))
  5641. (call-interactively (global-key-binding "\t")))
  5642. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5643. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5644. (or (and (eq org-cycle-emulate-tab 'white)
  5645. (= (match-end 0) (point-at-eol)))
  5646. (and (eq org-cycle-emulate-tab 'whitestart)
  5647. (>= (match-end 0) pos))))
  5648. t
  5649. (eq org-cycle-emulate-tab t))
  5650. (call-interactively (global-key-binding "\t")))
  5651. (t (save-excursion
  5652. (org-back-to-heading)
  5653. (org-cycle)))))))
  5654. (defun org-cycle-internal-global ()
  5655. "Do the global cycling action."
  5656. ;; Hack to avoid display of messages for .org attachments in Gnus
  5657. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5658. (cond
  5659. ((and (eq last-command this-command)
  5660. (eq org-cycle-global-status 'overview))
  5661. ;; We just created the overview - now do table of contents
  5662. ;; This can be slow in very large buffers, so indicate action
  5663. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5664. (unless ga (org-unlogged-message "CONTENTS..."))
  5665. (org-content)
  5666. (unless ga (org-unlogged-message "CONTENTS...done"))
  5667. (setq org-cycle-global-status 'contents)
  5668. (run-hook-with-args 'org-cycle-hook 'contents))
  5669. ((and (eq last-command this-command)
  5670. (eq org-cycle-global-status 'contents))
  5671. ;; We just showed the table of contents - now show everything
  5672. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5673. (org-show-all '(headings blocks))
  5674. (unless ga (org-unlogged-message "SHOW ALL"))
  5675. (setq org-cycle-global-status 'all)
  5676. (run-hook-with-args 'org-cycle-hook 'all))
  5677. (t
  5678. ;; Default action: go to overview
  5679. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5680. (org-overview)
  5681. (unless ga (org-unlogged-message "OVERVIEW"))
  5682. (setq org-cycle-global-status 'overview)
  5683. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5684. (defvar org-called-with-limited-levels nil
  5685. "Non-nil when `org-with-limited-levels' is currently active.")
  5686. (defun org-cycle-internal-local ()
  5687. "Do the local cycling action."
  5688. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5689. ;; First, determine end of headline (EOH), end of subtree or item
  5690. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5691. (save-excursion
  5692. (if (org-at-item-p)
  5693. (progn
  5694. (beginning-of-line)
  5695. (setq struct (org-list-struct))
  5696. (setq eoh (point-at-eol))
  5697. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5698. (setq has-children (org-list-has-child-p (point) struct)))
  5699. (org-back-to-heading)
  5700. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5701. (setq eos (save-excursion (org-end-of-subtree t t)
  5702. (when (bolp) (backward-char)) (point)))
  5703. (setq has-children
  5704. (save-excursion
  5705. (let ((level (funcall outline-level)))
  5706. (outline-next-heading)
  5707. (and (org-at-heading-p t)
  5708. (> (funcall outline-level) level))))))
  5709. ;; Determine end invisible part of buffer (EOL)
  5710. (beginning-of-line 2)
  5711. (while (and (not (eobp)) ;This is like `next-line'.
  5712. (get-char-property (1- (point)) 'invisible))
  5713. (goto-char (next-single-char-property-change (point) 'invisible))
  5714. (and (eolp) (beginning-of-line 2)))
  5715. (setq eol (point)))
  5716. ;; Find out what to do next and set `this-command'
  5717. (cond
  5718. ((= eos eoh)
  5719. ;; Nothing is hidden behind this heading
  5720. (unless (org-before-first-heading-p)
  5721. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5722. (org-unlogged-message "EMPTY ENTRY")
  5723. (setq org-cycle-subtree-status nil)
  5724. (save-excursion
  5725. (goto-char eos)
  5726. (outline-next-heading)
  5727. (when (org-invisible-p) (org-flag-heading nil))))
  5728. ((and (or (>= eol eos)
  5729. (not (string-match "\\S-" (buffer-substring eol eos))))
  5730. (or has-children
  5731. (not (setq children-skipped
  5732. org-cycle-skip-children-state-if-no-children))))
  5733. ;; Entire subtree is hidden in one line: children view
  5734. (unless (org-before-first-heading-p)
  5735. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5736. (if (org-at-item-p)
  5737. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5738. (org-show-entry)
  5739. (org-with-limited-levels (org-show-children))
  5740. (org-show-set-visibility 'canonical)
  5741. ;; Fold every list in subtree to top-level items.
  5742. (when (eq org-cycle-include-plain-lists 'integrate)
  5743. (save-excursion
  5744. (org-back-to-heading)
  5745. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5746. (beginning-of-line 1)
  5747. (let* ((struct (org-list-struct))
  5748. (prevs (org-list-prevs-alist struct))
  5749. (end (org-list-get-bottom-point struct)))
  5750. (dolist (e (org-list-get-all-items (point) struct prevs))
  5751. (org-list-set-item-visibility e struct 'folded))
  5752. (goto-char (if (< end eos) end eos)))))))
  5753. (org-unlogged-message "CHILDREN")
  5754. (save-excursion
  5755. (goto-char eos)
  5756. (outline-next-heading)
  5757. (when (org-invisible-p) (org-flag-heading nil)))
  5758. (setq org-cycle-subtree-status 'children)
  5759. (unless (org-before-first-heading-p)
  5760. (run-hook-with-args 'org-cycle-hook 'children)))
  5761. ((or children-skipped
  5762. (and (eq last-command this-command)
  5763. (eq org-cycle-subtree-status 'children)))
  5764. ;; We just showed the children, or no children are there,
  5765. ;; now show everything.
  5766. (unless (org-before-first-heading-p)
  5767. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5768. (org-flag-region eoh eos nil 'outline)
  5769. (org-unlogged-message
  5770. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5771. (setq org-cycle-subtree-status 'subtree)
  5772. (unless (org-before-first-heading-p)
  5773. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5774. (t
  5775. ;; Default action: hide the subtree.
  5776. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5777. (org-flag-region eoh eos t 'outline)
  5778. (org-unlogged-message "FOLDED")
  5779. (setq org-cycle-subtree-status 'folded)
  5780. (unless (org-before-first-heading-p)
  5781. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5782. ;;;###autoload
  5783. (defun org-global-cycle (&optional arg)
  5784. "Cycle the global visibility. For details see `org-cycle'.
  5785. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5786. With a numeric prefix, show all headlines up to that level."
  5787. (interactive "P")
  5788. (let ((org-cycle-include-plain-lists
  5789. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  5790. (cond
  5791. ((integerp arg)
  5792. (org-show-all '(headings blocks))
  5793. (outline-hide-sublevels arg)
  5794. (setq org-cycle-global-status 'contents))
  5795. ((equal arg '(4))
  5796. (org-set-startup-visibility)
  5797. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5798. (t
  5799. (org-cycle '(4))))))
  5800. (defun org-set-startup-visibility ()
  5801. "Set the visibility required by startup options and properties."
  5802. (cond
  5803. ((eq org-startup-folded t)
  5804. (org-overview))
  5805. ((eq org-startup-folded 'content)
  5806. (org-content))
  5807. ((or (eq org-startup-folded 'showeverything)
  5808. (eq org-startup-folded nil))
  5809. (org-show-all)))
  5810. (unless (eq org-startup-folded 'showeverything)
  5811. (when org-hide-block-startup (org-hide-block-all))
  5812. (org-set-visibility-according-to-property)
  5813. (org-cycle-hide-archived-subtrees 'all)
  5814. (org-cycle-hide-drawers 'all)
  5815. (org-cycle-show-empty-lines t)))
  5816. (defun org-set-visibility-according-to-property ()
  5817. "Switch subtree visibility according to VISIBILITY property."
  5818. (interactive)
  5819. (let ((regexp (org-re-property "VISIBILITY")))
  5820. (org-with-point-at 1
  5821. (while (re-search-forward regexp nil t)
  5822. (let ((state (match-string 3)))
  5823. (if (not (org-at-property-p)) (outline-next-heading)
  5824. (save-excursion
  5825. (org-back-to-heading t)
  5826. (org-flag-subtree t)
  5827. (org-reveal)
  5828. (pcase state
  5829. ("folded"
  5830. (org-flag-subtree t))
  5831. ("children"
  5832. (org-show-hidden-entry)
  5833. (org-show-children))
  5834. ("content"
  5835. (save-excursion
  5836. (save-restriction
  5837. (org-narrow-to-subtree)
  5838. (org-content))))
  5839. ((or "all" "showall")
  5840. (outline-show-subtree))
  5841. (_ nil)))
  5842. (org-end-of-subtree)))))))
  5843. (defun org-overview ()
  5844. "Switch to overview mode, showing only top-level headlines.
  5845. This shows all headlines with a level equal or greater than the level
  5846. of the first headline in the buffer. This is important, because if the
  5847. first headline is not level one, then (hide-sublevels 1) gives confusing
  5848. results."
  5849. (interactive)
  5850. (save-excursion
  5851. (let ((level
  5852. (save-excursion
  5853. (goto-char (point-min))
  5854. (when (re-search-forward org-outline-regexp-bol nil t)
  5855. (goto-char (match-beginning 0))
  5856. (funcall outline-level)))))
  5857. (and level (outline-hide-sublevels level)))))
  5858. (defun org-content (&optional arg)
  5859. "Show all headlines in the buffer, like a table of contents.
  5860. With numerical argument N, show content up to level N."
  5861. (interactive "P")
  5862. (org-overview)
  5863. (save-excursion
  5864. ;; Visit all headings and show their offspring
  5865. (and (integerp arg) (org-overview))
  5866. (goto-char (point-max))
  5867. (catch 'exit
  5868. (while (and (progn (condition-case nil
  5869. (outline-previous-visible-heading 1)
  5870. (error (goto-char (point-min))))
  5871. t)
  5872. (looking-at org-outline-regexp))
  5873. (if (integerp arg)
  5874. (org-show-children (1- arg))
  5875. (outline-show-branches))
  5876. (when (bobp) (throw 'exit nil))))))
  5877. (defun org-optimize-window-after-visibility-change (state)
  5878. "Adjust the window after a change in outline visibility.
  5879. This function is the default value of the hook `org-cycle-hook'."
  5880. (when (get-buffer-window (current-buffer))
  5881. (cond
  5882. ((eq state 'content) nil)
  5883. ((eq state 'all) nil)
  5884. ((eq state 'folded) nil)
  5885. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  5886. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  5887. (defun org-clean-visibility-after-subtree-move ()
  5888. "Fix visibility issues after moving a subtree."
  5889. ;; First, find a reasonable region to look at:
  5890. ;; Start two siblings above, end three below
  5891. (let* ((beg (save-excursion
  5892. (and (org-get-last-sibling)
  5893. (org-get-last-sibling))
  5894. (point)))
  5895. (end (save-excursion
  5896. (and (org-get-next-sibling)
  5897. (org-get-next-sibling)
  5898. (org-get-next-sibling))
  5899. (if (org-at-heading-p)
  5900. (point-at-eol)
  5901. (point))))
  5902. (level (looking-at "\\*+"))
  5903. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5904. (save-excursion
  5905. (save-restriction
  5906. (narrow-to-region beg end)
  5907. (when re
  5908. ;; Properly fold already folded siblings
  5909. (goto-char (point-min))
  5910. (while (re-search-forward re nil t)
  5911. (when (and (not (org-invisible-p))
  5912. (org-invisible-p (line-end-position)))
  5913. (outline-hide-entry))))
  5914. (org-cycle-hide-drawers 'all)
  5915. (org-cycle-show-empty-lines 'overview)))))
  5916. (defun org-cycle-show-empty-lines (state)
  5917. "Show empty lines above all visible headlines.
  5918. The region to be covered depends on STATE when called through
  5919. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5920. entire buffer covered. Note that an empty line is only shown if there
  5921. are at least `org-cycle-separator-lines' empty lines before the headline."
  5922. (when (/= org-cycle-separator-lines 0)
  5923. (save-excursion
  5924. (let* ((n (abs org-cycle-separator-lines))
  5925. (re (cond
  5926. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5927. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5928. (t (let ((ns (number-to-string (- n 2))))
  5929. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5930. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5931. beg end)
  5932. (cond
  5933. ((memq state '(overview contents t))
  5934. (setq beg (point-min) end (point-max)))
  5935. ((memq state '(children folded))
  5936. (setq beg (point)
  5937. end (progn (org-end-of-subtree t t)
  5938. (line-beginning-position 2)))))
  5939. (when beg
  5940. (goto-char beg)
  5941. (while (re-search-forward re end t)
  5942. (unless (get-char-property (match-end 1) 'invisible)
  5943. (let ((e (match-end 1))
  5944. (b (if (>= org-cycle-separator-lines 0)
  5945. (match-beginning 1)
  5946. (save-excursion
  5947. (goto-char (match-beginning 0))
  5948. (skip-chars-backward " \t\n")
  5949. (line-end-position)))))
  5950. (org-flag-region b e nil 'outline))))))))
  5951. ;; Never hide empty lines at the end of the file.
  5952. (save-excursion
  5953. (goto-char (point-max))
  5954. (outline-previous-heading)
  5955. (outline-end-of-heading)
  5956. (when (and (looking-at "[ \t\n]+")
  5957. (= (match-end 0) (point-max)))
  5958. (org-flag-region (point) (match-end 0) nil 'outline))))
  5959. ;;;; Reveal point location
  5960. (defun org-show-context (&optional key)
  5961. "Make sure point and context are visible.
  5962. Optional argument KEY, when non-nil, is a symbol. See
  5963. `org-show-context-detail' for allowed values and how much is to
  5964. be shown."
  5965. (org-show-set-visibility
  5966. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  5967. ((cdr (assq key org-show-context-detail)))
  5968. (t (cdr (assq 'default org-show-context-detail))))))
  5969. (defun org-show-set-visibility (detail)
  5970. "Set visibility around point according to DETAIL.
  5971. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  5972. `tree', `canonical' or t. See `org-show-context-detail' for more
  5973. information."
  5974. ;; Show current heading and possibly its entry, following headline
  5975. ;; or all children.
  5976. (if (and (org-at-heading-p) (not (eq detail 'local)))
  5977. (org-flag-heading nil)
  5978. (org-show-entry)
  5979. ;; If point is hidden within a drawer or a block, make sure to
  5980. ;; expose it.
  5981. (dolist (o (overlays-at (point)))
  5982. (when (memq (overlay-get o 'invisible)
  5983. '(org-hide-block org-hide-drawer outline))
  5984. (delete-overlay o)))
  5985. (unless (org-before-first-heading-p)
  5986. (org-with-limited-levels
  5987. (cl-case detail
  5988. ((tree canonical t) (org-show-children))
  5989. ((nil minimal ancestors))
  5990. (t (save-excursion
  5991. (outline-next-heading)
  5992. (org-flag-heading nil)))))))
  5993. ;; Show all siblings.
  5994. (when (eq detail 'lineage) (org-show-siblings))
  5995. ;; Show ancestors, possibly with their children.
  5996. (when (memq detail '(ancestors lineage tree canonical t))
  5997. (save-excursion
  5998. (while (org-up-heading-safe)
  5999. (org-flag-heading nil)
  6000. (when (memq detail '(canonical t)) (org-show-entry))
  6001. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6002. (defvar org-reveal-start-hook nil
  6003. "Hook run before revealing a location.")
  6004. (defun org-reveal (&optional siblings)
  6005. "Show current entry, hierarchy above it, and the following headline.
  6006. This can be used to show a consistent set of context around
  6007. locations exposed with `org-show-context'.
  6008. With optional argument SIBLINGS, on each level of the hierarchy all
  6009. siblings are shown. This repairs the tree structure to what it would
  6010. look like when opened with hierarchical calls to `org-cycle'.
  6011. With a \\[universal-argument] \\[universal-argument] prefix, \
  6012. go to the parent and show the entire tree."
  6013. (interactive "P")
  6014. (run-hooks 'org-reveal-start-hook)
  6015. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6016. ((equal siblings '(16))
  6017. (save-excursion
  6018. (when (org-up-heading-safe)
  6019. (org-show-subtree)
  6020. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6021. (t (org-show-set-visibility 'lineage))))
  6022. ;;; Indirect buffer display of subtrees
  6023. (defvar org-indirect-dedicated-frame nil
  6024. "This is the frame being used for indirect tree display.")
  6025. (defvar org-last-indirect-buffer nil)
  6026. (defun org-tree-to-indirect-buffer (&optional arg)
  6027. "Create indirect buffer and narrow it to current subtree.
  6028. With a numerical prefix ARG, go up to this level and then take that tree.
  6029. If ARG is negative, go up that many levels.
  6030. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6031. indirect buffer previously made with this command, to avoid proliferation of
  6032. indirect buffers. However, when you call the command with a \
  6033. `\\[universal-argument]' prefix, or
  6034. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6035. so that you can work with several indirect buffers at the same time. If
  6036. `org-indirect-buffer-display' is `dedicated-frame', the \
  6037. `\\[universal-argument]' prefix also
  6038. requests that a new frame be made for the new buffer, so that the dedicated
  6039. frame is not changed."
  6040. (interactive "P")
  6041. (let ((cbuf (current-buffer))
  6042. (cwin (selected-window))
  6043. (pos (point))
  6044. beg end level heading ibuf)
  6045. (save-excursion
  6046. (org-back-to-heading t)
  6047. (when (numberp arg)
  6048. (setq level (org-outline-level))
  6049. (when (< arg 0) (setq arg (+ level arg)))
  6050. (while (> (setq level (org-outline-level)) arg)
  6051. (org-up-heading-safe)))
  6052. (setq beg (point)
  6053. heading (org-get-heading 'no-tags))
  6054. (org-end-of-subtree t t)
  6055. (when (org-at-heading-p) (backward-char 1))
  6056. (setq end (point)))
  6057. (when (and (buffer-live-p org-last-indirect-buffer)
  6058. (not (eq org-indirect-buffer-display 'new-frame))
  6059. (not arg))
  6060. (kill-buffer org-last-indirect-buffer))
  6061. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6062. org-last-indirect-buffer ibuf)
  6063. (cond
  6064. ((or (eq org-indirect-buffer-display 'new-frame)
  6065. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6066. (select-frame (make-frame))
  6067. (delete-other-windows)
  6068. (pop-to-buffer-same-window ibuf)
  6069. (org-set-frame-title heading))
  6070. ((eq org-indirect-buffer-display 'dedicated-frame)
  6071. (raise-frame
  6072. (select-frame (or (and org-indirect-dedicated-frame
  6073. (frame-live-p org-indirect-dedicated-frame)
  6074. org-indirect-dedicated-frame)
  6075. (setq org-indirect-dedicated-frame (make-frame)))))
  6076. (delete-other-windows)
  6077. (pop-to-buffer-same-window ibuf)
  6078. (org-set-frame-title (concat "Indirect: " heading)))
  6079. ((eq org-indirect-buffer-display 'current-window)
  6080. (pop-to-buffer-same-window ibuf))
  6081. ((eq org-indirect-buffer-display 'other-window)
  6082. (pop-to-buffer ibuf))
  6083. (t (error "Invalid value")))
  6084. (narrow-to-region beg end)
  6085. (org-show-all '(headings blocks))
  6086. (goto-char pos)
  6087. (run-hook-with-args 'org-cycle-hook 'all)
  6088. (and (window-live-p cwin) (select-window cwin))))
  6089. (defun org-get-indirect-buffer (&optional buffer heading)
  6090. (setq buffer (or buffer (current-buffer)))
  6091. (let ((n 1) (base (buffer-name buffer)) bname)
  6092. (while (buffer-live-p
  6093. (get-buffer
  6094. (setq bname
  6095. (concat base "-"
  6096. (if heading (concat heading "-" (number-to-string n))
  6097. (number-to-string n))))))
  6098. (setq n (1+ n)))
  6099. (condition-case nil
  6100. (make-indirect-buffer buffer bname 'clone)
  6101. (error (make-indirect-buffer buffer bname)))))
  6102. (defun org-set-frame-title (title)
  6103. "Set the title of the current frame to the string TITLE."
  6104. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6105. ;;;; Structure editing
  6106. ;;; Inserting headlines
  6107. (defun org--line-empty-p (n)
  6108. "Is the Nth next line empty?
  6109. Counts the current line as N = 1 and the previous line as N = 0;
  6110. see `beginning-of-line'."
  6111. (save-excursion
  6112. (and (not (bobp))
  6113. (or (beginning-of-line n) t)
  6114. (save-match-data
  6115. (looking-at "[ \t]*$")))))
  6116. (defun org-previous-line-empty-p ()
  6117. "Is the previous line a blank line?
  6118. When NEXT is non-nil, check the next line instead."
  6119. (org--line-empty-p 0))
  6120. (defun org-next-line-empty-p ()
  6121. "Is the previous line a blank line?
  6122. When NEXT is non-nil, check the next line instead."
  6123. (org--line-empty-p 2))
  6124. (defun org--blank-before-heading-p (&optional parent)
  6125. "Non-nil when an empty line should precede a new heading here.
  6126. When optional argument PARENT is non-nil, consider parent
  6127. headline instead of current one."
  6128. (pcase (assq 'heading org-blank-before-new-entry)
  6129. (`(heading . auto)
  6130. (save-excursion
  6131. (org-with-limited-levels
  6132. (unless (and (org-before-first-heading-p)
  6133. (not (outline-next-heading)))
  6134. (org-back-to-heading t)
  6135. (when parent (org-up-heading-safe))
  6136. (cond ((not (bobp))
  6137. (org-previous-line-empty-p))
  6138. ((outline-next-heading)
  6139. (org-previous-line-empty-p))
  6140. ;; Ignore trailing spaces on last buffer line.
  6141. ((progn (skip-chars-backward " \t") (bolp))
  6142. (org-previous-line-empty-p))
  6143. (t nil))))))
  6144. (`(heading . ,value) value)
  6145. (_ nil)))
  6146. (defun org-insert-heading (&optional arg invisible-ok top)
  6147. "Insert a new heading or an item with the same depth at point.
  6148. If point is at the beginning of a heading, insert a new heading
  6149. or a new headline above the current one. When at the beginning
  6150. of a regular line of text, turn it into a heading.
  6151. If point is in the middle of a line, split it and create a new
  6152. headline with the text in the current line after point (see
  6153. `org-M-RET-may-split-line' on how to modify this behavior). As
  6154. a special case, on a headline, splitting can only happen on the
  6155. title itself. E.g., this excludes breaking stars or tags.
  6156. With a `\\[universal-argument]' prefix, set \
  6157. `org-insert-heading-respect-content' to
  6158. a non-nil value for the duration of the command. This forces the
  6159. insertion of a heading after the current subtree, independently
  6160. on the location of point.
  6161. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6162. insert the heading at the end of the tree
  6163. above the current heading. For example, if point is within a
  6164. 2nd-level heading, then it will insert a 2nd-level heading at
  6165. the end of the 1st-level parent subtree.
  6166. When INVISIBLE-OK is set, stop at invisible headlines when going
  6167. back. This is important for non-interactive uses of the
  6168. command.
  6169. When optional argument TOP is non-nil, insert a level 1 heading,
  6170. unconditionally."
  6171. (interactive "P")
  6172. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6173. (level (org-current-level))
  6174. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6175. (cond
  6176. ((or org-insert-heading-respect-content
  6177. (member arg '((4) (16)))
  6178. (and (not invisible-ok)
  6179. (invisible-p (max (1- (point)) (point-min)))))
  6180. ;; Position point at the location of insertion. Make sure we
  6181. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6182. (org-with-limited-levels
  6183. (if (not level) (outline-next-heading) ;before first headline
  6184. (org-back-to-heading invisible-ok)
  6185. (when (equal arg '(16)) (org-up-heading-safe))
  6186. (org-end-of-subtree)))
  6187. (unless (bolp) (insert "\n"))
  6188. (unless (and blank? (org-previous-line-empty-p))
  6189. (org-N-empty-lines-before-current (if blank? 1 0)))
  6190. (insert stars " ")
  6191. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6192. ;; is visible.
  6193. (unless invisible-ok
  6194. (pcase (get-char-property-and-overlay (point) 'invisible)
  6195. (`(outline . ,o)
  6196. (move-overlay o (overlay-start o) (line-end-position 0)))
  6197. (_ nil))))
  6198. ;; At a headline...
  6199. ((org-at-heading-p)
  6200. (cond ((bolp)
  6201. (when blank? (save-excursion (insert "\n")))
  6202. (save-excursion (insert stars " \n"))
  6203. (unless (and blank? (org-previous-line-empty-p))
  6204. (org-N-empty-lines-before-current (if blank? 1 0)))
  6205. (end-of-line))
  6206. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6207. (org-match-line org-complex-heading-regexp)
  6208. (org-pos-in-match-range (point) 4))
  6209. ;; Grab the text that should moved to the new headline.
  6210. ;; Preserve tags.
  6211. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6212. (if (looking-at "[ \t]*$") (replace-match "")
  6213. (org-align-tags))
  6214. (end-of-line)
  6215. (when blank? (insert "\n"))
  6216. (insert "\n" stars " ")
  6217. (when (org-string-nw-p split) (insert split))))
  6218. (t
  6219. (end-of-line)
  6220. (when blank? (insert "\n"))
  6221. (insert "\n" stars " "))))
  6222. ;; On regular text, turn line into a headline or split, if
  6223. ;; appropriate.
  6224. ((bolp)
  6225. (insert stars " ")
  6226. (unless (and blank? (org-previous-line-empty-p))
  6227. (org-N-empty-lines-before-current (if blank? 1 0))))
  6228. (t
  6229. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6230. (end-of-line))
  6231. (insert "\n" stars " ")
  6232. (unless (and blank? (org-previous-line-empty-p))
  6233. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6234. (run-hooks 'org-insert-heading-hook))
  6235. (defun org-N-empty-lines-before-current (n)
  6236. "Make the number of empty lines before current exactly N.
  6237. So this will delete or add empty lines."
  6238. (let ((column (current-column)))
  6239. (beginning-of-line)
  6240. (unless (bobp)
  6241. (let ((start (save-excursion
  6242. (skip-chars-backward " \r\t\n")
  6243. (line-end-position))))
  6244. (delete-region start (line-end-position 0))))
  6245. (insert (make-string n ?\n))
  6246. (move-to-column column)))
  6247. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6248. "Return the heading of the current entry, without the stars.
  6249. When NO-TAGS is non-nil, don't include tags.
  6250. When NO-TODO is non-nil, don't include TODO keywords.
  6251. When NO-PRIORITY is non-nil, don't include priority cookie.
  6252. When NO-COMMENT is non-nil, don't include COMMENT string.
  6253. Return nil before first heading."
  6254. (unless (org-before-first-heading-p)
  6255. (save-excursion
  6256. (org-back-to-heading t)
  6257. (let ((case-fold-search nil))
  6258. (looking-at org-complex-heading-regexp)
  6259. (let ((todo (and (not no-todo) (match-string 2)))
  6260. (priority (and (not no-priority) (match-string 3)))
  6261. (headline (pcase (match-string 4)
  6262. (`nil "")
  6263. ((and (guard no-comment) h)
  6264. (replace-regexp-in-string
  6265. (eval-when-compile
  6266. (format "\\`%s[ \t]+" org-comment-string))
  6267. "" h))
  6268. (h h)))
  6269. (tags (and (not no-tags) (match-string 5))))
  6270. (mapconcat #'identity
  6271. (delq nil (list todo priority headline tags))
  6272. " "))))))
  6273. (defun org-heading-components ()
  6274. "Return the components of the current heading.
  6275. This is a list with the following elements:
  6276. - the level as an integer
  6277. - the reduced level, different if `org-odd-levels-only' is set.
  6278. - the TODO keyword, or nil
  6279. - the priority character, like ?A, or nil if no priority is given
  6280. - the headline text itself, or the tags string if no headline text
  6281. - the tags string, or nil."
  6282. (save-excursion
  6283. (org-back-to-heading t)
  6284. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6285. (list (length (match-string 1))
  6286. (org-reduced-level (length (match-string 1)))
  6287. (match-string-no-properties 2)
  6288. (and (match-end 3) (aref (match-string 3) 2))
  6289. (match-string-no-properties 4)
  6290. (match-string-no-properties 5)))))
  6291. (defun org-get-entry ()
  6292. "Get the entry text, after heading, entire subtree."
  6293. (save-excursion
  6294. (org-back-to-heading t)
  6295. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6296. (defun org-edit-headline (&optional heading)
  6297. "Edit the current headline.
  6298. Set it to HEADING when provided."
  6299. (interactive)
  6300. (org-with-wide-buffer
  6301. (org-back-to-heading t)
  6302. (let ((case-fold-search nil))
  6303. (when (looking-at org-complex-heading-regexp)
  6304. (let* ((old (match-string-no-properties 4))
  6305. (new (save-match-data
  6306. (org-trim (or heading (read-string "Edit: " old))))))
  6307. (unless (equal old new)
  6308. (if old (replace-match new t t nil 4)
  6309. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6310. (insert " " new))
  6311. (org-align-tags)
  6312. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6313. (defun org-insert-heading-after-current ()
  6314. "Insert a new heading with same level as current, after current subtree."
  6315. (interactive)
  6316. (org-back-to-heading)
  6317. (org-insert-heading)
  6318. (org-move-subtree-down)
  6319. (end-of-line 1))
  6320. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6321. "Insert heading with `org-insert-heading-respect-content' set to t."
  6322. (interactive)
  6323. (org-insert-heading '(4) invisible-ok))
  6324. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6325. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6326. (interactive)
  6327. (org-insert-todo-heading force-state '(4)))
  6328. (defun org-insert-todo-heading (arg &optional force-heading)
  6329. "Insert a new heading with the same level and TODO state as current heading.
  6330. If the heading has no TODO state, or if the state is DONE, use
  6331. the first state (TODO by default). Also with one prefix arg,
  6332. force first state. With two prefix args, force inserting at the
  6333. end of the parent subtree.
  6334. When called at a plain list item, insert a new item with an
  6335. unchecked check box."
  6336. (interactive "P")
  6337. (when (or force-heading (not (org-insert-item 'checkbox)))
  6338. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6339. force-heading))
  6340. (save-excursion
  6341. (org-forward-heading-same-level -1)
  6342. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6343. (let* ((new-mark-x
  6344. (if (or (equal arg '(4))
  6345. (not (match-beginning 2))
  6346. (member (match-string 2) org-done-keywords))
  6347. (car org-todo-keywords-1)
  6348. (match-string 2)))
  6349. (new-mark
  6350. (or
  6351. (run-hook-with-args-until-success
  6352. 'org-todo-get-default-hook new-mark-x nil)
  6353. new-mark-x)))
  6354. (beginning-of-line 1)
  6355. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6356. (if org-treat-insert-todo-heading-as-state-change
  6357. (org-todo new-mark)
  6358. (insert new-mark " "))))
  6359. (when org-provide-todo-statistics
  6360. (org-update-parent-todo-statistics))))
  6361. (defun org-insert-subheading (arg)
  6362. "Insert a new subheading and demote it.
  6363. Works for outline headings and for plain lists alike."
  6364. (interactive "P")
  6365. (org-insert-heading arg)
  6366. (cond
  6367. ((org-at-heading-p) (org-do-demote))
  6368. ((org-at-item-p) (org-indent-item))))
  6369. (defun org-insert-todo-subheading (arg)
  6370. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6371. Works for outline headings and for plain lists alike."
  6372. (interactive "P")
  6373. (org-insert-todo-heading arg)
  6374. (cond
  6375. ((org-at-heading-p) (org-do-demote))
  6376. ((org-at-item-p) (org-indent-item))))
  6377. ;;; Promotion and Demotion
  6378. (defvar org-after-demote-entry-hook nil
  6379. "Hook run after an entry has been demoted.
  6380. The cursor will be at the beginning of the entry.
  6381. When a subtree is being demoted, the hook will be called for each node.")
  6382. (defvar org-after-promote-entry-hook nil
  6383. "Hook run after an entry has been promoted.
  6384. The cursor will be at the beginning of the entry.
  6385. When a subtree is being promoted, the hook will be called for each node.")
  6386. (defun org-promote-subtree ()
  6387. "Promote the entire subtree.
  6388. See also `org-promote'."
  6389. (interactive)
  6390. (save-excursion
  6391. (org-with-limited-levels (org-map-tree 'org-promote)))
  6392. (org-fix-position-after-promote))
  6393. (defun org-demote-subtree ()
  6394. "Demote the entire subtree.
  6395. See `org-demote' and `org-promote'."
  6396. (interactive)
  6397. (save-excursion
  6398. (org-with-limited-levels (org-map-tree 'org-demote)))
  6399. (org-fix-position-after-promote))
  6400. (defun org-do-promote ()
  6401. "Promote the current heading higher up the tree.
  6402. If the region is active in `transient-mark-mode', promote all
  6403. headings in the region."
  6404. (interactive)
  6405. (save-excursion
  6406. (if (org-region-active-p)
  6407. (org-map-region 'org-promote (region-beginning) (region-end))
  6408. (org-promote)))
  6409. (org-fix-position-after-promote))
  6410. (defun org-do-demote ()
  6411. "Demote the current heading lower down the tree.
  6412. If the region is active in `transient-mark-mode', demote all
  6413. headings in the region."
  6414. (interactive)
  6415. (save-excursion
  6416. (if (org-region-active-p)
  6417. (org-map-region 'org-demote (region-beginning) (region-end))
  6418. (org-demote)))
  6419. (org-fix-position-after-promote))
  6420. (defun org-fix-position-after-promote ()
  6421. "Fix cursor position and indentation after demoting/promoting."
  6422. (let ((pos (point)))
  6423. (when (save-excursion
  6424. (beginning-of-line)
  6425. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6426. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6427. (cond ((eobp) (insert " "))
  6428. ((eolp) (insert " "))
  6429. ((equal (char-after) ?\s) (forward-char 1))))))
  6430. (defun org-current-level ()
  6431. "Return the level of the current entry, or nil if before the first headline.
  6432. The level is the number of stars at the beginning of the
  6433. headline. Use `org-reduced-level' to remove the effect of
  6434. `org-odd-levels'. Unlike to `org-outline-level', this function
  6435. ignores inlinetasks."
  6436. (let ((level (org-with-limited-levels (org-outline-level))))
  6437. (and (> level 0) level)))
  6438. (defun org-get-previous-line-level ()
  6439. "Return the outline depth of the last headline before the current line.
  6440. Returns 0 for the first headline in the buffer, and nil if before the
  6441. first headline."
  6442. (and (org-current-level)
  6443. (or (and (/= (line-beginning-position) (point-min))
  6444. (save-excursion (beginning-of-line 0) (org-current-level)))
  6445. 0)))
  6446. (defun org-reduced-level (l)
  6447. "Compute the effective level of a heading.
  6448. This takes into account the setting of `org-odd-levels-only'."
  6449. (cond
  6450. ((zerop l) 0)
  6451. (org-odd-levels-only (1+ (floor (/ l 2))))
  6452. (t l)))
  6453. (defun org-level-increment ()
  6454. "Return the number of stars that will be added or removed at a
  6455. time to headlines when structure editing, based on the value of
  6456. `org-odd-levels-only'."
  6457. (if org-odd-levels-only 2 1))
  6458. (defun org-get-valid-level (level &optional change)
  6459. "Rectify a level change under the influence of `org-odd-levels-only'.
  6460. LEVEL is a current level, CHANGE is by how much the level should
  6461. be modified. Even if CHANGE is nil, LEVEL may be returned
  6462. modified because even level numbers will become the next higher
  6463. odd number. Returns values greater than 0."
  6464. (if org-odd-levels-only
  6465. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6466. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6467. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6468. (max 1 (+ level (or change 0)))))
  6469. (defun org-promote ()
  6470. "Promote the current heading higher up the tree."
  6471. (org-with-wide-buffer
  6472. (org-back-to-heading t)
  6473. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6474. after-change-functions))
  6475. (level (save-match-data (funcall outline-level)))
  6476. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6477. (diff (abs (- level (length up-head) -1))))
  6478. (cond
  6479. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6480. (replace-match "# " nil t))
  6481. ((= level 1)
  6482. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6483. (t (replace-match up-head nil t)))
  6484. (unless (= level 1)
  6485. (when org-auto-align-tags (org-align-tags))
  6486. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6487. (run-hooks 'org-after-promote-entry-hook))))
  6488. (defun org-demote ()
  6489. "Demote the current heading lower down the tree."
  6490. (org-with-wide-buffer
  6491. (org-back-to-heading t)
  6492. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6493. after-change-functions))
  6494. (level (save-match-data (funcall outline-level)))
  6495. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6496. (diff (abs (- level (length down-head) -1))))
  6497. (replace-match down-head nil t)
  6498. (when org-auto-align-tags (org-align-tags))
  6499. (when org-adapt-indentation (org-fixup-indentation diff))
  6500. (run-hooks 'org-after-demote-entry-hook))))
  6501. (defun org-cycle-level ()
  6502. "Cycle the level of an empty headline through possible states.
  6503. This goes first to child, then to parent, level, then up the hierarchy.
  6504. After top level, it switches back to sibling level."
  6505. (interactive)
  6506. (let ((org-adapt-indentation nil))
  6507. (when (org-point-at-end-of-empty-headline)
  6508. (setq this-command 'org-cycle-level) ; Only needed for caching
  6509. (let ((cur-level (org-current-level))
  6510. (prev-level (org-get-previous-line-level)))
  6511. (cond
  6512. ;; If first headline in file, promote to top-level.
  6513. ((= prev-level 0)
  6514. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6515. do (org-do-promote)))
  6516. ;; If same level as prev, demote one.
  6517. ((= prev-level cur-level)
  6518. (org-do-demote))
  6519. ;; If parent is top-level, promote to top level if not already.
  6520. ((= prev-level 1)
  6521. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6522. do (org-do-promote)))
  6523. ;; If top-level, return to prev-level.
  6524. ((= cur-level 1)
  6525. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6526. do (org-do-demote)))
  6527. ;; If less than prev-level, promote one.
  6528. ((< cur-level prev-level)
  6529. (org-do-promote))
  6530. ;; If deeper than prev-level, promote until higher than
  6531. ;; prev-level.
  6532. ((> cur-level prev-level)
  6533. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6534. do (org-do-promote))))
  6535. t))))
  6536. (defun org-map-tree (fun)
  6537. "Call FUN for every heading underneath the current one."
  6538. (org-back-to-heading t)
  6539. (let ((level (funcall outline-level)))
  6540. (save-excursion
  6541. (funcall fun)
  6542. (while (and (progn
  6543. (outline-next-heading)
  6544. (> (funcall outline-level) level))
  6545. (not (eobp)))
  6546. (funcall fun)))))
  6547. (defun org-map-region (fun beg end)
  6548. "Call FUN for every heading between BEG and END."
  6549. (let ((org-ignore-region t))
  6550. (save-excursion
  6551. (setq end (copy-marker end))
  6552. (goto-char beg)
  6553. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6554. (< (point) end))
  6555. (funcall fun))
  6556. (while (and (progn
  6557. (outline-next-heading)
  6558. (< (point) end))
  6559. (not (eobp)))
  6560. (funcall fun)))))
  6561. (defun org-fixup-indentation (diff)
  6562. "Change the indentation in the current entry by DIFF.
  6563. DIFF is an integer. Indentation is done according to the
  6564. following rules:
  6565. - Planning information and property drawers are always indented
  6566. according to the new level of the headline;
  6567. - Footnote definitions and their contents are ignored;
  6568. - Inlinetasks' boundaries are not shifted;
  6569. - Empty lines are ignored;
  6570. - Other lines' indentation are shifted by DIFF columns, unless
  6571. it would introduce a structural change in the document, in
  6572. which case no shifting is done at all.
  6573. Assume point is at a heading or an inlinetask beginning."
  6574. (org-with-wide-buffer
  6575. (narrow-to-region (line-beginning-position)
  6576. (save-excursion
  6577. (if (org-with-limited-levels (org-at-heading-p))
  6578. (org-with-limited-levels (outline-next-heading))
  6579. (org-inlinetask-goto-end))
  6580. (point)))
  6581. (forward-line)
  6582. ;; Indent properly planning info and property drawer.
  6583. (when (looking-at-p org-planning-line-re)
  6584. (org-indent-line)
  6585. (forward-line))
  6586. (when (looking-at org-property-drawer-re)
  6587. (goto-char (match-end 0))
  6588. (forward-line)
  6589. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  6590. (catch 'no-shift
  6591. (when (zerop diff) (throw 'no-shift nil))
  6592. ;; If DIFF is negative, first check if a shift is possible at all
  6593. ;; (e.g., it doesn't break structure). This can only happen if
  6594. ;; some contents are not properly indented.
  6595. (let ((case-fold-search t))
  6596. (when (< diff 0)
  6597. (let ((diff (- diff))
  6598. (forbidden-re (concat org-outline-regexp
  6599. "\\|"
  6600. (substring org-footnote-definition-re 1))))
  6601. (save-excursion
  6602. (while (not (eobp))
  6603. (cond
  6604. ((looking-at-p "[ \t]*$") (forward-line))
  6605. ((and (looking-at-p org-footnote-definition-re)
  6606. (let ((e (org-element-at-point)))
  6607. (and (eq (org-element-type e) 'footnote-definition)
  6608. (goto-char (org-element-property :end e))))))
  6609. ((looking-at-p org-outline-regexp) (forward-line))
  6610. ;; Give up if shifting would move before column 0 or
  6611. ;; if it would introduce a headline or a footnote
  6612. ;; definition.
  6613. (t
  6614. (skip-chars-forward " \t")
  6615. (let ((ind (current-column)))
  6616. (when (or (< ind diff)
  6617. (and (= ind diff) (looking-at-p forbidden-re)))
  6618. (throw 'no-shift nil)))
  6619. ;; Ignore contents of example blocks and source
  6620. ;; blocks if their indentation is meant to be
  6621. ;; preserved. Jump to block's closing line.
  6622. (beginning-of-line)
  6623. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6624. (let ((e (org-element-at-point)))
  6625. (and (memq (org-element-type e)
  6626. '(example-block src-block))
  6627. (or org-src-preserve-indentation
  6628. (org-element-property :preserve-indent e))
  6629. (goto-char (org-element-property :end e))
  6630. (progn (skip-chars-backward " \r\t\n")
  6631. (beginning-of-line)
  6632. t))))
  6633. (forward-line))))))))
  6634. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6635. ;; by DIFF. Also skip contents of source or example blocks
  6636. ;; when indentation is meant to be preserved.
  6637. (while (not (eobp))
  6638. (cond
  6639. ((and (looking-at-p org-footnote-definition-re)
  6640. (let ((e (org-element-at-point)))
  6641. (and (eq (org-element-type e) 'footnote-definition)
  6642. (goto-char (org-element-property :end e))))))
  6643. ((looking-at-p org-outline-regexp) (forward-line))
  6644. ((looking-at-p "[ \t]*$") (forward-line))
  6645. (t
  6646. (indent-line-to (+ (current-indentation) diff))
  6647. (beginning-of-line)
  6648. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6649. (let ((e (org-element-at-point)))
  6650. (and (memq (org-element-type e)
  6651. '(example-block src-block))
  6652. (or org-src-preserve-indentation
  6653. (org-element-property :preserve-indent e))
  6654. (goto-char (org-element-property :end e))
  6655. (progn (skip-chars-backward " \r\t\n")
  6656. (beginning-of-line)
  6657. t))))
  6658. (forward-line)))))))))
  6659. (defun org-convert-to-odd-levels ()
  6660. "Convert an Org file with all levels allowed to one with odd levels.
  6661. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6662. level 5 etc."
  6663. (interactive)
  6664. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6665. (let ((outline-level 'org-outline-level)
  6666. (org-odd-levels-only nil) n)
  6667. (save-excursion
  6668. (goto-char (point-min))
  6669. (while (re-search-forward "^\\*\\*+ " nil t)
  6670. (setq n (- (length (match-string 0)) 2))
  6671. (while (>= (setq n (1- n)) 0)
  6672. (org-demote))
  6673. (end-of-line 1))))))
  6674. (defun org-convert-to-oddeven-levels ()
  6675. "Convert an Org file with only odd levels to one with odd/even levels.
  6676. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6677. file contains a section with an even level, conversion would
  6678. destroy the structure of the file. An error is signaled in this
  6679. case."
  6680. (interactive)
  6681. (goto-char (point-min))
  6682. ;; First check if there are no even levels
  6683. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6684. (org-show-set-visibility 'canonical)
  6685. (error "Not all levels are odd in this file. Conversion not possible"))
  6686. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6687. (let ((outline-regexp org-outline-regexp)
  6688. (outline-level 'org-outline-level)
  6689. (org-odd-levels-only nil) n)
  6690. (save-excursion
  6691. (goto-char (point-min))
  6692. (while (re-search-forward "^\\*\\*+ " nil t)
  6693. (setq n (/ (1- (length (match-string 0))) 2))
  6694. (while (>= (setq n (1- n)) 0)
  6695. (org-promote))
  6696. (end-of-line 1))))))
  6697. (defun org-tr-level (n)
  6698. "Make N odd if required."
  6699. (if org-odd-levels-only (1+ (/ n 2)) n))
  6700. ;;; Vertical tree motion, cutting and pasting of subtrees
  6701. (defun org-move-subtree-up (&optional arg)
  6702. "Move the current subtree up past ARG headlines of the same level."
  6703. (interactive "p")
  6704. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6705. (defun org-move-subtree-down (&optional arg)
  6706. "Move the current subtree down past ARG headlines of the same level."
  6707. (interactive "p")
  6708. (setq arg (prefix-numeric-value arg))
  6709. (org-preserve-local-variables
  6710. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6711. 'org-get-last-sibling))
  6712. (ins-point (make-marker))
  6713. (cnt (abs arg))
  6714. (col (current-column))
  6715. beg end txt folded)
  6716. ;; Select the tree
  6717. (org-back-to-heading)
  6718. (setq beg (point))
  6719. (save-match-data
  6720. (save-excursion (outline-end-of-heading)
  6721. (setq folded (org-invisible-p)))
  6722. (progn (org-end-of-subtree nil t)
  6723. (unless (eobp) (backward-char))))
  6724. (outline-next-heading)
  6725. (setq end (point))
  6726. (goto-char beg)
  6727. ;; Find insertion point, with error handling
  6728. (while (> cnt 0)
  6729. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6730. (goto-char beg)
  6731. (user-error "Cannot move past superior level or buffer limit"))
  6732. (setq cnt (1- cnt)))
  6733. (when (> arg 0)
  6734. ;; Moving forward - still need to move over subtree
  6735. (org-end-of-subtree t t)
  6736. (save-excursion
  6737. (org-back-over-empty-lines)
  6738. (or (bolp) (newline))))
  6739. (move-marker ins-point (point))
  6740. (setq txt (buffer-substring beg end))
  6741. (org-save-markers-in-region beg end)
  6742. (delete-region beg end)
  6743. (org-remove-empty-overlays-at beg)
  6744. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6745. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6746. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6747. (let ((bbb (point)))
  6748. (insert-before-markers txt)
  6749. (org-reinstall-markers-in-region bbb)
  6750. (move-marker ins-point bbb))
  6751. (or (bolp) (insert "\n"))
  6752. (goto-char ins-point)
  6753. (org-skip-whitespace)
  6754. (move-marker ins-point nil)
  6755. (if folded
  6756. (org-flag-subtree t)
  6757. (org-show-entry)
  6758. (org-show-children))
  6759. (org-clean-visibility-after-subtree-move)
  6760. ;; move back to the initial column we were at
  6761. (move-to-column col))))
  6762. (defvar org-subtree-clip ""
  6763. "Clipboard for cut and paste of subtrees.
  6764. This is actually only a copy of the kill, because we use the normal kill
  6765. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6766. (defvar org-subtree-clip-folded nil
  6767. "Was the last copied subtree folded?
  6768. This is used to fold the tree back after pasting.")
  6769. (defun org-cut-subtree (&optional n)
  6770. "Cut the current subtree into the clipboard.
  6771. With prefix arg N, cut this many sequential subtrees.
  6772. This is a short-hand for marking the subtree and then cutting it."
  6773. (interactive "p")
  6774. (org-copy-subtree n 'cut))
  6775. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6776. "Copy the current subtree into the clipboard.
  6777. With prefix arg N, copy this many sequential subtrees.
  6778. This is a short-hand for marking the subtree and then copying it.
  6779. If CUT is non-nil, actually cut the subtree.
  6780. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6781. of some markers in the region, even if CUT is non-nil. This is
  6782. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6783. (interactive "p")
  6784. (org-preserve-local-variables
  6785. (let (beg end folded (beg0 (point)))
  6786. (if (called-interactively-p 'any)
  6787. (org-back-to-heading nil) ; take what looks like a subtree
  6788. (org-back-to-heading t)) ; take what is really there
  6789. (setq beg (point))
  6790. (skip-chars-forward " \t\r\n")
  6791. (save-match-data
  6792. (if nosubtrees
  6793. (outline-next-heading)
  6794. (save-excursion (outline-end-of-heading)
  6795. (setq folded (org-invisible-p)))
  6796. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6797. (org-end-of-subtree t t)))
  6798. ;; Include the end of an inlinetask
  6799. (when (and (featurep 'org-inlinetask)
  6800. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6801. "END[ \t]*$")))
  6802. (end-of-line))
  6803. (setq end (point))
  6804. (goto-char beg0)
  6805. (when (> end beg)
  6806. (setq org-subtree-clip-folded folded)
  6807. (when (or cut force-store-markers)
  6808. (org-save-markers-in-region beg end))
  6809. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6810. (setq org-subtree-clip (current-kill 0))
  6811. (message "%s: Subtree(s) with %d characters"
  6812. (if cut "Cut" "Copied")
  6813. (length org-subtree-clip))))))
  6814. (defun org-paste-subtree (&optional level tree for-yank remove)
  6815. "Paste the clipboard as a subtree, with modification of headline level.
  6816. The entire subtree is promoted or demoted in order to match a new headline
  6817. level.
  6818. If the cursor is at the beginning of a headline, the same level as
  6819. that headline is used to paste the tree.
  6820. If not, the new level is derived from the *visible* headings
  6821. before and after the insertion point, and taken to be the inferior headline
  6822. level of the two. So if the previous visible heading is level 3 and the
  6823. next is level 4 (or vice versa), level 4 will be used for insertion.
  6824. This makes sure that the subtree remains an independent subtree and does
  6825. not swallow low level entries.
  6826. You can also force a different level, either by using a numeric prefix
  6827. argument, or by inserting the heading marker by hand. For example, if the
  6828. cursor is after \"*****\", then the tree will be shifted to level 5.
  6829. If optional TREE is given, use this text instead of the kill ring.
  6830. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6831. move back over whitespace before inserting, and move point to the end of
  6832. the inserted text when done.
  6833. When REMOVE is non-nil, remove the subtree from the clipboard."
  6834. (interactive "P")
  6835. (setq tree (or tree (and kill-ring (current-kill 0))))
  6836. (unless (org-kill-is-subtree-p tree)
  6837. (user-error
  6838. (substitute-command-keys
  6839. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6840. (org-with-limited-levels
  6841. (let* ((visp (not (org-invisible-p)))
  6842. (txt tree)
  6843. (old-level (if (string-match org-outline-regexp-bol txt)
  6844. (- (match-end 0) (match-beginning 0) 1)
  6845. -1))
  6846. (force-level
  6847. (cond
  6848. (level (prefix-numeric-value level))
  6849. ;; When point is after the stars in an otherwise empty
  6850. ;; headline, use the number of stars as the forced level.
  6851. ((and (org-match-line "^\\*+[ \t]*$")
  6852. (not (eq ?* (char-after))))
  6853. (org-outline-level))
  6854. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6855. (previous-level
  6856. (save-excursion
  6857. (org-previous-visible-heading 1)
  6858. (if (org-at-heading-p) (org-outline-level) 1)))
  6859. (next-level
  6860. (save-excursion
  6861. (if (org-at-heading-p) (org-outline-level)
  6862. (org-next-visible-heading 1)
  6863. (if (org-at-heading-p) (org-outline-level) 1))))
  6864. (new-level (or force-level (max previous-level next-level)))
  6865. (shift (if (or (= old-level -1)
  6866. (= new-level -1)
  6867. (= old-level new-level))
  6868. 0
  6869. (- new-level old-level)))
  6870. (delta (if (> shift 0) -1 1))
  6871. (func (if (> shift 0) #'org-demote #'org-promote))
  6872. (org-odd-levels-only nil)
  6873. beg end newend)
  6874. ;; Remove the forced level indicator.
  6875. (when (and force-level (not level))
  6876. (delete-region (line-beginning-position) (point)))
  6877. ;; Paste before the next visible heading or at end of buffer,
  6878. ;; unless point is at the beginning of a headline.
  6879. (unless (and (bolp) (org-at-heading-p))
  6880. (org-next-visible-heading 1)
  6881. (unless (bolp) (insert "\n")))
  6882. (setq beg (point))
  6883. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6884. (insert-before-markers txt)
  6885. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6886. (setq newend (point))
  6887. (org-reinstall-markers-in-region beg)
  6888. (setq end (point))
  6889. (goto-char beg)
  6890. (skip-chars-forward " \t\n\r")
  6891. (setq beg (point))
  6892. (when (and (org-invisible-p) visp)
  6893. (save-excursion (outline-show-heading)))
  6894. ;; Shift if necessary.
  6895. (unless (= shift 0)
  6896. (save-restriction
  6897. (narrow-to-region beg end)
  6898. (while (not (= shift 0))
  6899. (org-map-region func (point-min) (point-max))
  6900. (setq shift (+ delta shift)))
  6901. (goto-char (point-min))
  6902. (setq newend (point-max))))
  6903. (when (or for-yank (called-interactively-p 'interactive))
  6904. (message "Clipboard pasted as level %d subtree" new-level))
  6905. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6906. kill-ring
  6907. (equal org-subtree-clip (current-kill 0))
  6908. org-subtree-clip-folded)
  6909. ;; The tree was folded before it was killed/copied
  6910. (org-flag-subtree t))
  6911. (when for-yank (goto-char newend))
  6912. (when remove (pop kill-ring)))))
  6913. (defun org-kill-is-subtree-p (&optional txt)
  6914. "Check if the current kill is an outline subtree, or a set of trees.
  6915. Returns nil if kill does not start with a headline, or if the first
  6916. headline level is not the largest headline level in the tree.
  6917. So this will actually accept several entries of equal levels as well,
  6918. which is OK for `org-paste-subtree'.
  6919. If optional TXT is given, check this string instead of the current kill."
  6920. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6921. (re (org-get-limited-outline-regexp))
  6922. (^re (concat "^" re))
  6923. (start-level (and kill
  6924. (string-match
  6925. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6926. kill)
  6927. (- (match-end 2) (match-beginning 2) 1)))
  6928. (start (1+ (or (match-beginning 2) -1))))
  6929. (if (not start-level)
  6930. (progn
  6931. nil) ;; does not even start with a heading
  6932. (catch 'exit
  6933. (while (setq start (string-match ^re kill (1+ start)))
  6934. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6935. (throw 'exit nil)))
  6936. t))))
  6937. (defvar org-markers-to-move nil
  6938. "Markers that should be moved with a cut-and-paste operation.
  6939. Those markers are stored together with their positions relative to
  6940. the start of the region.")
  6941. (defun org-save-markers-in-region (beg end)
  6942. "Check markers in region.
  6943. If these markers are between BEG and END, record their position relative
  6944. to BEG, so that after moving the block of text, we can put the markers back
  6945. into place.
  6946. This function gets called just before an entry or tree gets cut from the
  6947. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6948. called immediately, to move the markers with the entries."
  6949. (setq org-markers-to-move nil)
  6950. (when (featurep 'org-clock)
  6951. (org-clock-save-markers-for-cut-and-paste beg end))
  6952. (when (featurep 'org-agenda)
  6953. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6954. (defun org-check-and-save-marker (marker beg end)
  6955. "Check if MARKER is between BEG and END.
  6956. If yes, remember the marker and the distance to BEG."
  6957. (when (and (marker-buffer marker)
  6958. (equal (marker-buffer marker) (current-buffer))
  6959. (>= marker beg) (< marker end))
  6960. (push (cons marker (- marker beg)) org-markers-to-move)))
  6961. (defun org-reinstall-markers-in-region (beg)
  6962. "Move all remembered markers to their position relative to BEG."
  6963. (dolist (x org-markers-to-move)
  6964. (move-marker (car x) (+ beg (cdr x))))
  6965. (setq org-markers-to-move nil))
  6966. (defun org-narrow-to-subtree ()
  6967. "Narrow buffer to the current subtree."
  6968. (interactive)
  6969. (save-excursion
  6970. (save-match-data
  6971. (org-with-limited-levels
  6972. (narrow-to-region
  6973. (progn (org-back-to-heading t) (point))
  6974. (progn (org-end-of-subtree t t)
  6975. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6976. (point)))))))
  6977. (defun org-toggle-narrow-to-subtree ()
  6978. "Narrow to the subtree at point or widen a narrowed buffer."
  6979. (interactive)
  6980. (if (buffer-narrowed-p)
  6981. (progn (widen) (message "Buffer widen"))
  6982. (org-narrow-to-subtree)
  6983. (message "Buffer narrowed to current subtree")))
  6984. (defun org-narrow-to-block ()
  6985. "Narrow buffer to the current block."
  6986. (interactive)
  6987. (let* ((case-fold-search t)
  6988. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6989. "^[ \t]*#\\+end_.*")))
  6990. (if blockp
  6991. (narrow-to-region (car blockp) (cdr blockp))
  6992. (user-error "Not in a block"))))
  6993. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6994. "Clone the task (subtree) at point N times.
  6995. The clones will be inserted as siblings.
  6996. In interactive use, the user will be prompted for the number of
  6997. clones to be produced. If the entry has a timestamp, the user
  6998. will also be prompted for a time shift, which may be a repeater
  6999. as used in time stamps, for example `+3d'. To disable this,
  7000. you can call the function with a universal prefix argument.
  7001. When a valid repeater is given and the entry contains any time
  7002. stamps, the clones will become a sequence in time, with time
  7003. stamps in the subtree shifted for each clone produced. If SHIFT
  7004. is nil or the empty string, time stamps will be left alone. The
  7005. ID property of the original subtree is removed.
  7006. In each clone, all the CLOCK entries will be removed. This
  7007. prevents Org from considering that the clocked times overlap.
  7008. If the original subtree did contain time stamps with a repeater,
  7009. the following will happen:
  7010. - the repeater will be removed in each clone
  7011. - an additional clone will be produced, with the current, unshifted
  7012. date(s) in the entry.
  7013. - the original entry will be placed *after* all the clones, with
  7014. repeater intact.
  7015. - the start days in the repeater in the original entry will be shifted
  7016. to past the last clone.
  7017. In this way you can spell out a number of instances of a repeating task,
  7018. and still retain the repeater to cover future instances of the task.
  7019. As described above, N+1 clones are produced when the original
  7020. subtree has a repeater. Setting N to 0, then, can be used to
  7021. remove the repeater from a subtree and create a shifted clone
  7022. with the original repeater."
  7023. (interactive "nNumber of clones to produce: ")
  7024. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7025. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7026. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7027. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7028. (shift
  7029. (or shift
  7030. (if (and (not (equal current-prefix-arg '(4)))
  7031. (save-excursion
  7032. (goto-char beg)
  7033. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7034. (read-from-minibuffer
  7035. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7036. ""))) ;No time shift
  7037. (doshift
  7038. (and (org-string-nw-p shift)
  7039. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7040. shift)
  7041. (user-error "Invalid shift specification %s" shift)))))
  7042. (goto-char end-of-tree)
  7043. (unless (bolp) (insert "\n"))
  7044. (let* ((end (point))
  7045. (template (buffer-substring beg end))
  7046. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7047. (shift-what (pcase (and doshift (match-string 2 shift))
  7048. (`nil nil)
  7049. ("d" 'day)
  7050. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7051. ("m" 'month)
  7052. ("y" 'year)
  7053. (_ (error "Unsupported time unit"))))
  7054. (nmin 1)
  7055. (nmax n)
  7056. (n-no-remove -1)
  7057. (idprop (org-entry-get beg "ID")))
  7058. (when (and doshift
  7059. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7060. template))
  7061. (delete-region beg end)
  7062. (setq end beg)
  7063. (setq nmin 0)
  7064. (setq nmax (1+ nmax))
  7065. (setq n-no-remove nmax))
  7066. (goto-char end)
  7067. (cl-loop for n from nmin to nmax do
  7068. (insert
  7069. ;; Prepare clone.
  7070. (with-temp-buffer
  7071. (insert template)
  7072. (org-mode)
  7073. (goto-char (point-min))
  7074. (org-show-subtree)
  7075. (and idprop (if org-clone-delete-id
  7076. (org-entry-delete nil "ID")
  7077. (org-id-get-create t)))
  7078. (unless (= n 0)
  7079. (while (re-search-forward org-clock-line-re nil t)
  7080. (delete-region (line-beginning-position)
  7081. (line-beginning-position 2)))
  7082. (goto-char (point-min))
  7083. (while (re-search-forward org-drawer-regexp nil t)
  7084. (org-remove-empty-drawer-at (point))))
  7085. (goto-char (point-min))
  7086. (when doshift
  7087. (while (re-search-forward org-ts-regexp-both nil t)
  7088. (org-timestamp-change (* n shift-n) shift-what))
  7089. (unless (= n n-no-remove)
  7090. (goto-char (point-min))
  7091. (while (re-search-forward org-ts-regexp nil t)
  7092. (save-excursion
  7093. (goto-char (match-beginning 0))
  7094. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7095. (delete-region (match-beginning 1) (match-end 1)))))))
  7096. (buffer-string)))))
  7097. (goto-char beg)))
  7098. ;;; Outline Sorting
  7099. (defun org-sort (&optional with-case)
  7100. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7101. Optional argument WITH-CASE means sort case-sensitively."
  7102. (interactive "P")
  7103. (org-call-with-arg
  7104. (cond ((org-at-table-p) #'org-table-sort-lines)
  7105. ((org-at-item-p) #'org-sort-list)
  7106. (t #'org-sort-entries))
  7107. with-case))
  7108. (defun org-sort-remove-invisible (s)
  7109. "Remove invisible part of links and emphasis markers from string S."
  7110. (remove-text-properties 0 (length s) org-rm-props s)
  7111. (replace-regexp-in-string
  7112. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7113. (replace-regexp-in-string
  7114. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7115. (org-link-display-format s)
  7116. t t) t t))
  7117. (defvar org-after-sorting-entries-or-items-hook nil
  7118. "Hook that is run after a bunch of entries or items have been sorted.
  7119. When children are sorted, the cursor is in the parent line when this
  7120. hook gets called. When a region or a plain list is sorted, the cursor
  7121. will be in the first entry of the sorted region/list.")
  7122. (defun org-sort-entries
  7123. (&optional with-case sorting-type getkey-func compare-func property
  7124. interactive?)
  7125. "Sort entries on a certain level of an outline tree.
  7126. If there is an active region, the entries in the region are sorted.
  7127. Else, if the cursor is before the first entry, sort the top-level items.
  7128. Else, the children of the entry at point are sorted.
  7129. Sorting can be alphabetically, numerically, by date/time as given by
  7130. a time stamp, by a property, by priority order, or by a custom function.
  7131. The command prompts for the sorting type unless it has been given to the
  7132. function through the SORTING-TYPE argument, which needs to be a character,
  7133. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7134. the precise meaning of each character:
  7135. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7136. c By creation time, which is assumed to be the first inactive time stamp
  7137. at the beginning of a line.
  7138. d By deadline date/time.
  7139. k By clocking time.
  7140. n Numerically, by converting the beginning of the entry/item to a number.
  7141. o By order of TODO keywords.
  7142. p By priority according to the cookie.
  7143. r By the value of a property.
  7144. s By scheduled date/time.
  7145. t By date/time, either the first active time stamp in the entry, or, if
  7146. none exist, by the first inactive one.
  7147. Capital letters will reverse the sort order.
  7148. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7149. called with point at the beginning of the record. It must return a
  7150. value that is compatible with COMPARE-FUNC, the function used to
  7151. compare entries.
  7152. Comparing entries ignores case by default. However, with an optional argument
  7153. WITH-CASE, the sorting considers case as well.
  7154. Sorting is done against the visible part of the headlines, it ignores hidden
  7155. links.
  7156. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7157. A non-nil value for INTERACTIVE? is used to signal that this
  7158. function is being called interactively."
  7159. (interactive (list current-prefix-arg nil nil nil nil t))
  7160. (let ((case-func (if with-case 'identity 'downcase))
  7161. start beg end stars re re2
  7162. txt what tmp)
  7163. ;; Find beginning and end of region to sort
  7164. (cond
  7165. ((org-region-active-p)
  7166. ;; we will sort the region
  7167. (setq end (region-end)
  7168. what "region")
  7169. (goto-char (region-beginning))
  7170. (unless (org-at-heading-p) (outline-next-heading))
  7171. (setq start (point)))
  7172. ((or (org-at-heading-p)
  7173. (ignore-errors (progn (org-back-to-heading) t)))
  7174. ;; we will sort the children of the current headline
  7175. (org-back-to-heading)
  7176. (setq start (point)
  7177. end (progn (org-end-of-subtree t t)
  7178. (or (bolp) (insert "\n"))
  7179. (when (>= (org-back-over-empty-lines) 1)
  7180. (forward-line 1))
  7181. (point))
  7182. what "children")
  7183. (goto-char start)
  7184. (outline-show-subtree)
  7185. (outline-next-heading))
  7186. (t
  7187. ;; we will sort the top-level entries in this file
  7188. (goto-char (point-min))
  7189. (or (org-at-heading-p) (outline-next-heading))
  7190. (setq start (point))
  7191. (goto-char (point-max))
  7192. (beginning-of-line 1)
  7193. (when (looking-at ".*?\\S-")
  7194. ;; File ends in a non-white line
  7195. (end-of-line 1)
  7196. (insert "\n"))
  7197. (setq end (point-max))
  7198. (setq what "top-level")
  7199. (goto-char start)
  7200. (org-show-all '(headings blocks))))
  7201. (setq beg (point))
  7202. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7203. (looking-at "\\(\\*+\\)")
  7204. (setq stars (match-string 1)
  7205. re (concat "^" (regexp-quote stars) " +")
  7206. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7207. txt (buffer-substring beg end))
  7208. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7209. (when (and (not (equal stars "*")) (string-match re2 txt))
  7210. (user-error "Region to sort contains a level above the first entry"))
  7211. (unless sorting-type
  7212. (message
  7213. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7214. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7215. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7216. what)
  7217. (setq sorting-type (read-char-exclusive)))
  7218. (unless getkey-func
  7219. (and (= (downcase sorting-type) ?f)
  7220. (setq getkey-func
  7221. (or (and interactive?
  7222. (org-read-function
  7223. "Function for extracting keys: "))
  7224. (error "Missing key extractor")))))
  7225. (and (= (downcase sorting-type) ?r)
  7226. (not property)
  7227. (setq property
  7228. (completing-read "Property: "
  7229. (mapcar #'list (org-buffer-property-keys t))
  7230. nil t)))
  7231. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7232. (message "Sorting entries...")
  7233. (save-restriction
  7234. (narrow-to-region start end)
  7235. (let ((restore-clock?
  7236. ;; The clock marker is lost when using `sort-subr'; mark
  7237. ;; the clock with temporary `:org-clock-marker-backup'
  7238. ;; text property.
  7239. (when (and (eq (org-clock-is-active) (current-buffer))
  7240. (<= start (marker-position org-clock-marker))
  7241. (>= end (marker-position org-clock-marker)))
  7242. (with-silent-modifications
  7243. (put-text-property (1- org-clock-marker) org-clock-marker
  7244. :org-clock-marker-backup t))
  7245. t))
  7246. (dcst (downcase sorting-type))
  7247. (case-fold-search nil)
  7248. (now (current-time)))
  7249. (org-preserve-local-variables
  7250. (sort-subr
  7251. (/= dcst sorting-type)
  7252. ;; This function moves to the beginning character of the
  7253. ;; "record" to be sorted.
  7254. (lambda nil
  7255. (if (re-search-forward re nil t)
  7256. (goto-char (match-beginning 0))
  7257. (goto-char (point-max))))
  7258. ;; This function moves to the last character of the "record" being
  7259. ;; sorted.
  7260. (lambda nil
  7261. (save-match-data
  7262. (condition-case nil
  7263. (outline-forward-same-level 1)
  7264. (error
  7265. (goto-char (point-max))))))
  7266. ;; This function returns the value that gets sorted against.
  7267. (lambda ()
  7268. (cond
  7269. ((= dcst ?n)
  7270. (string-to-number
  7271. (org-sort-remove-invisible (org-get-heading t t t t))))
  7272. ((= dcst ?a)
  7273. (funcall case-func
  7274. (org-sort-remove-invisible (org-get-heading t t t t))))
  7275. ((= dcst ?k)
  7276. (or (get-text-property (point) :org-clock-minutes) 0))
  7277. ((= dcst ?t)
  7278. (let ((end (save-excursion (outline-next-heading) (point))))
  7279. (if (or (re-search-forward org-ts-regexp end t)
  7280. (re-search-forward org-ts-regexp-both end t))
  7281. (org-time-string-to-seconds (match-string 0))
  7282. (float-time now))))
  7283. ((= dcst ?c)
  7284. (let ((end (save-excursion (outline-next-heading) (point))))
  7285. (if (re-search-forward
  7286. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7287. end t)
  7288. (org-time-string-to-seconds (match-string 0))
  7289. (float-time now))))
  7290. ((= dcst ?s)
  7291. (let ((end (save-excursion (outline-next-heading) (point))))
  7292. (if (re-search-forward org-scheduled-time-regexp end t)
  7293. (org-time-string-to-seconds (match-string 1))
  7294. (float-time now))))
  7295. ((= dcst ?d)
  7296. (let ((end (save-excursion (outline-next-heading) (point))))
  7297. (if (re-search-forward org-deadline-time-regexp end t)
  7298. (org-time-string-to-seconds (match-string 1))
  7299. (float-time now))))
  7300. ((= dcst ?p)
  7301. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7302. (string-to-char (match-string 2))
  7303. org-priority-default))
  7304. ((= dcst ?r)
  7305. (or (org-entry-get nil property) ""))
  7306. ((= dcst ?o)
  7307. (when (looking-at org-complex-heading-regexp)
  7308. (let* ((m (match-string 2))
  7309. (s (if (member m org-done-keywords) '- '+)))
  7310. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7311. ((= dcst ?f)
  7312. (if getkey-func
  7313. (progn
  7314. (setq tmp (funcall getkey-func))
  7315. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7316. tmp)
  7317. (error "Invalid key function `%s'" getkey-func)))
  7318. (t (error "Invalid sorting type `%c'" sorting-type))))
  7319. nil
  7320. (cond
  7321. ((= dcst ?a) 'org-string-collate-lessp)
  7322. ((= dcst ?f)
  7323. (or compare-func
  7324. (and interactive?
  7325. (org-read-function
  7326. (concat "Function for comparing keys "
  7327. "(empty for default `sort-subr' predicate): ")
  7328. 'allow-empty))))
  7329. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7330. (org-cycle-hide-drawers 'all)
  7331. (when restore-clock?
  7332. (move-marker org-clock-marker
  7333. (1+ (next-single-property-change
  7334. start :org-clock-marker-backup)))
  7335. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7336. '(:org-clock-marker-backup t)))))
  7337. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7338. (message "Sorting entries...done")))
  7339. (defun org-contextualize-keys (alist contexts)
  7340. "Return valid elements in ALIST depending on CONTEXTS.
  7341. `org-agenda-custom-commands' or `org-capture-templates' are the
  7342. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7343. or `org-capture-templates-contexts' are the associated contexts
  7344. definitions."
  7345. (let ((contexts
  7346. ;; normalize contexts
  7347. (mapcar
  7348. (lambda(c) (cond ((listp (cadr c))
  7349. (list (car c) (car c) (nth 1 c)))
  7350. ((string= "" (cadr c))
  7351. (list (car c) (car c) (nth 2 c)))
  7352. (t c)))
  7353. contexts))
  7354. (a alist) r s)
  7355. ;; loop over all commands or templates
  7356. (dolist (c a)
  7357. (let (vrules repl)
  7358. (cond
  7359. ((not (assoc (car c) contexts))
  7360. (push c r))
  7361. ((and (assoc (car c) contexts)
  7362. (setq vrules (org-contextualize-validate-key
  7363. (car c) contexts)))
  7364. (mapc (lambda (vr)
  7365. (unless (equal (car vr) (cadr vr))
  7366. (setq repl vr)))
  7367. vrules)
  7368. (if (not repl) (push c r)
  7369. (push (cadr repl) s)
  7370. (push
  7371. (cons (car c)
  7372. (cdr (or (assoc (cadr repl) alist)
  7373. (error "Undefined key `%s' as contextual replacement for `%s'"
  7374. (cadr repl) (car c)))))
  7375. r))))))
  7376. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7377. (delq
  7378. nil
  7379. (delete-dups
  7380. (mapcar (lambda (x)
  7381. (let ((tpl (car x)))
  7382. (unless (delq
  7383. nil
  7384. (mapcar (lambda (y)
  7385. (equal y tpl))
  7386. s))
  7387. x)))
  7388. (reverse r))))))
  7389. (defun org-contextualize-validate-key (key contexts)
  7390. "Check CONTEXTS for agenda or capture KEY."
  7391. (let (res)
  7392. (dolist (r contexts)
  7393. (dolist (rr (car (last r)))
  7394. (when
  7395. (and (equal key (car r))
  7396. (if (functionp rr) (funcall rr)
  7397. (or (and (eq (car rr) 'in-file)
  7398. (buffer-file-name)
  7399. (string-match (cdr rr) (buffer-file-name)))
  7400. (and (eq (car rr) 'in-mode)
  7401. (string-match (cdr rr) (symbol-name major-mode)))
  7402. (and (eq (car rr) 'in-buffer)
  7403. (string-match (cdr rr) (buffer-name)))
  7404. (when (and (eq (car rr) 'not-in-file)
  7405. (buffer-file-name))
  7406. (not (string-match (cdr rr) (buffer-file-name))))
  7407. (when (eq (car rr) 'not-in-mode)
  7408. (not (string-match (cdr rr) (symbol-name major-mode))))
  7409. (when (eq (car rr) 'not-in-buffer)
  7410. (not (string-match (cdr rr) (buffer-name)))))))
  7411. (push r res))))
  7412. (delete-dups (delq nil res))))
  7413. ;; Defined to provide a value for defcustom, since there is no
  7414. ;; string-collate-greaterp in Emacs.
  7415. (defun org-string-collate-greaterp (s1 s2)
  7416. "Return non-nil if S1 is greater than S2 in collation order."
  7417. (not (org-string-collate-lessp s1 s2)))
  7418. ;;;###autoload
  7419. (defun org-run-like-in-org-mode (cmd)
  7420. "Run a command, pretending that the current buffer is in Org mode.
  7421. This will temporarily bind local variables that are typically bound in
  7422. Org mode to the values they have in Org mode, and then interactively
  7423. call CMD."
  7424. (org-load-modules-maybe)
  7425. (let (binds)
  7426. (dolist (var (org-get-local-variables))
  7427. (when (or (not (boundp (car var)))
  7428. (eq (symbol-value (car var))
  7429. (default-value (car var))))
  7430. (push (list (car var) `(quote ,(cadr var))) binds)))
  7431. (eval `(let ,binds
  7432. (call-interactively (quote ,cmd))))))
  7433. (defun org-get-category (&optional pos force-refresh)
  7434. "Get the category applying to position POS."
  7435. (save-match-data
  7436. (when force-refresh (org-refresh-category-properties))
  7437. (let ((pos (or pos (point))))
  7438. (or (get-text-property pos 'org-category)
  7439. (progn (org-refresh-category-properties)
  7440. (get-text-property pos 'org-category))))))
  7441. ;;; Refresh properties
  7442. (defun org-refresh-properties (dprop tprop)
  7443. "Refresh buffer text properties.
  7444. DPROP is the drawer property and TPROP is either the
  7445. corresponding text property to set, or an alist with each element
  7446. being a text property (as a symbol) and a function to apply to
  7447. the value of the drawer property."
  7448. (let* ((case-fold-search t)
  7449. (inhibit-read-only t)
  7450. (inherit? (org-property-inherit-p dprop))
  7451. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7452. (global-or-keyword (and inherit?
  7453. (org--property-global-or-keyword-value dprop nil))))
  7454. (with-silent-modifications
  7455. (org-with-point-at 1
  7456. ;; Set global and keyword based values to the whole buffer.
  7457. (when global-or-keyword
  7458. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7459. ;; Set values based on property-drawers throughout the document.
  7460. (while (re-search-forward property-re nil t)
  7461. (when (org-at-property-p)
  7462. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7463. (outline-next-heading))))))
  7464. (defun org-refresh-property (tprop p &optional inherit)
  7465. "Refresh the buffer text property TPROP from the drawer property P.
  7466. The refresh happens only for the current entry, or the whole
  7467. sub-tree if optional argument INHERIT is non-nil.
  7468. If point is before first headline, the function applies to the
  7469. part before the first headline. In that particular case, when
  7470. optional argument INHERIT is non-nil, it refreshes properties for
  7471. the whole buffer."
  7472. (save-excursion
  7473. (org-back-to-heading-or-point-min t)
  7474. (let ((start (point))
  7475. (end (save-excursion
  7476. (cond ((and inherit (org-before-first-heading-p))
  7477. (point-max))
  7478. (inherit
  7479. (org-end-of-subtree t t))
  7480. ((outline-next-heading))
  7481. ((point-max))))))
  7482. (if (symbolp tprop)
  7483. ;; TPROP is a text property symbol.
  7484. (put-text-property start end tprop p)
  7485. ;; TPROP is an alist with (property . function) elements.
  7486. (pcase-dolist (`(,prop . ,f) tprop)
  7487. (put-text-property start end prop (funcall f p)))))))
  7488. (defun org-refresh-category-properties ()
  7489. "Refresh category text properties in the buffer."
  7490. (let ((case-fold-search t)
  7491. (inhibit-read-only t)
  7492. (default-category
  7493. (cond ((null org-category)
  7494. (if buffer-file-name
  7495. (file-name-sans-extension
  7496. (file-name-nondirectory buffer-file-name))
  7497. "???"))
  7498. ((symbolp org-category) (symbol-name org-category))
  7499. (t org-category))))
  7500. (with-silent-modifications
  7501. (org-with-wide-buffer
  7502. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7503. ;; keyword. If none is found, fall-back to `org-category' or
  7504. ;; buffer file name, or set it by the document property drawer.
  7505. (put-text-property
  7506. (point-min) (point-max)
  7507. 'org-category
  7508. (catch 'buffer-category
  7509. (goto-char (point-max))
  7510. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7511. (let ((element (org-element-at-point)))
  7512. (when (eq (org-element-type element) 'keyword)
  7513. (throw 'buffer-category
  7514. (org-element-property :value element)))))
  7515. default-category))
  7516. ;; Set categories from the document property drawer or
  7517. ;; property drawers in the outline. If category is found in
  7518. ;; the property drawer for the whole buffer that value
  7519. ;; overrides the keyword-based value set above.
  7520. (goto-char (point-min))
  7521. (let ((regexp (org-re-property "CATEGORY")))
  7522. (while (re-search-forward regexp nil t)
  7523. (let ((value (match-string-no-properties 3)))
  7524. (when (org-at-property-p)
  7525. (put-text-property
  7526. (save-excursion (org-back-to-heading-or-point-min t))
  7527. (save-excursion (if (org-before-first-heading-p)
  7528. (point-max)
  7529. (org-end-of-subtree t t)))
  7530. 'org-category
  7531. value)))))))))
  7532. (defun org-refresh-stats-properties ()
  7533. "Refresh stats text properties in the buffer."
  7534. (with-silent-modifications
  7535. (org-with-point-at 1
  7536. (let ((regexp (concat org-outline-regexp-bol
  7537. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7538. (while (re-search-forward regexp nil t)
  7539. (let* ((numerator (string-to-number (match-string 1)))
  7540. (denominator (and (match-end 2)
  7541. (string-to-number (match-string 2))))
  7542. (stats (cond ((not denominator) numerator) ;percent
  7543. ((= denominator 0) 0)
  7544. (t (/ (* numerator 100) denominator)))))
  7545. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7546. 'org-stats stats)))))))
  7547. (defun org-refresh-effort-properties ()
  7548. "Refresh effort properties."
  7549. (org-refresh-properties
  7550. org-effort-property
  7551. '((effort . identity)
  7552. (effort-minutes . org-duration-to-minutes))))
  7553. (defun org-find-file-at-mouse (ev)
  7554. "Open file link or URL at mouse."
  7555. (interactive "e")
  7556. (mouse-set-point ev)
  7557. (org-open-at-point 'in-emacs))
  7558. (defun org-open-at-mouse (ev)
  7559. "Open file link or URL at mouse.
  7560. See the docstring of `org-open-file' for details."
  7561. (interactive "e")
  7562. (mouse-set-point ev)
  7563. (when (eq major-mode 'org-agenda-mode)
  7564. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7565. (org-open-at-point))
  7566. (defvar org-window-config-before-follow-link nil
  7567. "The window configuration before following a link.
  7568. This is saved in case the need arises to restore it.")
  7569. (defun org--file-default-apps ()
  7570. "Return the default applications for this operating system."
  7571. (pcase system-type
  7572. (`darwin org-file-apps-macos)
  7573. (`windows-nt org-file-apps-windowsnt)
  7574. (_ org-file-apps-gnu)))
  7575. (defun org--file-apps-entry-dlink-p (entry)
  7576. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7577. It assumes that is the case when the entry uses a regular
  7578. expression which has at least one grouping construct and the
  7579. action is either a Lisp form or a command string containing
  7580. \"%1\", i.e., using at least one subexpression match as
  7581. a parameter."
  7582. (pcase entry
  7583. (`(,selector . ,action)
  7584. (and (stringp selector)
  7585. (> (regexp-opt-depth selector) 0)
  7586. (or (and (stringp action)
  7587. (string-match "%[0-9]" action))
  7588. (consp action))))
  7589. (_ nil)))
  7590. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7591. "Convert extensions to regular expressions in the cars of LIST.
  7592. Also, weed out any non-string entries, because the return value
  7593. is used only for regexp matching.
  7594. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7595. point to the symbol `emacs', indicating that the file should be
  7596. opened in Emacs."
  7597. (append
  7598. (delq nil
  7599. (mapcar (lambda (x)
  7600. (unless (not (stringp (car x)))
  7601. (if (string-match "\\W" (car x))
  7602. x
  7603. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7604. list))
  7605. (when add-auto-mode
  7606. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7607. ;;;###autoload
  7608. (defun org-open-file (path &optional in-emacs line search)
  7609. "Open the file at PATH.
  7610. First, this expands any special file name abbreviations. Then the
  7611. configuration variable `org-file-apps' is checked if it contains an
  7612. entry for this file type, and if yes, the corresponding command is launched.
  7613. If no application is found, Emacs simply visits the file.
  7614. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7615. With a double \\[universal-argument] \\[universal-argument] \
  7616. prefix arg, Org tries to avoid opening in Emacs
  7617. and to use an external application to visit the file.
  7618. Optional LINE specifies a line to go to, optional SEARCH a string
  7619. to search for. If LINE or SEARCH is given, the file will be
  7620. opened in Emacs, unless an entry from `org-file-apps' that makes
  7621. use of groups in a regexp matches.
  7622. If you want to change the way frames are used when following a
  7623. link, please customize `org-link-frame-setup'.
  7624. If the file does not exist, throw an error."
  7625. (let* ((file (if (equal path "") buffer-file-name
  7626. (substitute-in-file-name (expand-file-name path))))
  7627. (file-apps (append org-file-apps (org--file-default-apps)))
  7628. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7629. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7630. file-apps))
  7631. (remp (and (assq 'remote apps) (file-remote-p file)))
  7632. (dirp (unless remp (file-directory-p file)))
  7633. (file (if (and dirp org-open-directory-means-index-dot-org)
  7634. (concat (file-name-as-directory file) "index.org")
  7635. file))
  7636. (a-m-a-p (assq 'auto-mode apps))
  7637. (dfile (downcase file))
  7638. ;; Reconstruct the original link from the PATH, LINE and
  7639. ;; SEARCH args.
  7640. (link (cond (line (concat file "::" (number-to-string line)))
  7641. (search (concat file "::" search))
  7642. (t file)))
  7643. (dlink (downcase link))
  7644. (ext
  7645. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7646. (match-string 1 dfile)))
  7647. (save-position-maybe
  7648. (let ((old-buffer (current-buffer))
  7649. (old-pos (point))
  7650. (old-mode major-mode))
  7651. (lambda ()
  7652. (and (derived-mode-p 'org-mode)
  7653. (eq old-mode 'org-mode)
  7654. (or (not (eq old-buffer (current-buffer)))
  7655. (not (eq old-pos (point))))
  7656. (org-mark-ring-push old-pos old-buffer)))))
  7657. cmd link-match-data)
  7658. (cond
  7659. ((member in-emacs '((16) system))
  7660. (setq cmd (cdr (assq 'system apps))))
  7661. (in-emacs (setq cmd 'emacs))
  7662. (t
  7663. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7664. (and dirp (cdr (assq 'directory apps)))
  7665. ;; First, try matching against apps-dlink if we
  7666. ;; get a match here, store the match data for
  7667. ;; later.
  7668. (let ((match (assoc-default dlink apps-dlink
  7669. 'string-match)))
  7670. (if match
  7671. (progn (setq link-match-data (match-data))
  7672. match)
  7673. (progn (setq in-emacs (or in-emacs line search))
  7674. nil))) ; if we have no match in apps-dlink,
  7675. ; always open the file in emacs if line or search
  7676. ; is given (for backwards compatibility)
  7677. (assoc-default dfile
  7678. (org--file-apps-regexp-alist apps a-m-a-p)
  7679. 'string-match)
  7680. (cdr (assoc ext apps))
  7681. (cdr (assq t apps))))))
  7682. (when (eq cmd 'system)
  7683. (setq cmd (cdr (assq 'system apps))))
  7684. (when (eq cmd 'default)
  7685. (setq cmd (cdr (assoc t apps))))
  7686. (when (eq cmd 'mailcap)
  7687. (require 'mailcap)
  7688. (mailcap-parse-mailcaps)
  7689. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7690. (command (mailcap-mime-info mime-type)))
  7691. (if (stringp command)
  7692. (setq cmd command)
  7693. (setq cmd 'emacs))))
  7694. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7695. (not (file-exists-p file))
  7696. (not org-open-non-existing-files))
  7697. (user-error "No such file: %s" file))
  7698. (cond
  7699. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7700. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7701. (while (string-match "['\"]%s['\"]" cmd)
  7702. (setq cmd (replace-match "%s" t t cmd)))
  7703. (setq cmd (replace-regexp-in-string
  7704. "%s"
  7705. (shell-quote-argument (convert-standard-filename file))
  7706. cmd
  7707. nil t))
  7708. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7709. (save-match-data
  7710. (let ((match-index 1)
  7711. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7712. (set-match-data link-match-data)
  7713. (while (<= match-index number-of-groups)
  7714. (let ((regex (concat "%" (number-to-string match-index)))
  7715. (replace-with (match-string match-index dlink)))
  7716. (while (string-match regex cmd)
  7717. (setq cmd (replace-match replace-with t t cmd))))
  7718. (setq match-index (+ match-index 1)))))
  7719. (save-window-excursion
  7720. (message "Running %s...done" cmd)
  7721. (start-process-shell-command cmd nil cmd)
  7722. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7723. ((or (stringp cmd)
  7724. (eq cmd 'emacs))
  7725. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7726. (widen)
  7727. (cond (line (org-goto-line line)
  7728. (when (derived-mode-p 'org-mode) (org-reveal)))
  7729. (search (condition-case err
  7730. (org-link-search search)
  7731. ;; Save position before error-ing out so user
  7732. ;; can easily move back to the original buffer.
  7733. (error (funcall save-position-maybe)
  7734. (error (nth 1 err)))))))
  7735. ((functionp cmd)
  7736. (save-match-data
  7737. (set-match-data link-match-data)
  7738. (condition-case nil
  7739. (funcall cmd file link)
  7740. ;; FIXME: Remove this check when most default installations
  7741. ;; of Emacs have at least Org 9.0.
  7742. ((debug wrong-number-of-arguments wrong-type-argument
  7743. invalid-function)
  7744. (user-error "Please see Org News for version 9.0 about \
  7745. `org-file-apps'--Lisp error: %S" cmd)))))
  7746. ((consp cmd)
  7747. ;; FIXME: Remove this check when most default installations of
  7748. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7749. ;; fall back to `org-link-frame-setup' for an old usage of
  7750. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7751. (user-error "Please see Org News for version 9.0 about \
  7752. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7753. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7754. (funcall save-position-maybe)))
  7755. ;;;###autoload
  7756. (defun org-open-at-point-global ()
  7757. "Follow a link or a time-stamp like Org mode does.
  7758. Also follow links and emails as seen by `thing-at-point'.
  7759. This command can be called in any mode to follow an external
  7760. link or a time-stamp that has Org mode syntax. Its behavior
  7761. is undefined when called on internal links like fuzzy links.
  7762. Raise a user error when there is nothing to follow."
  7763. (interactive)
  7764. (let ((tap-url (thing-at-point 'url))
  7765. (tap-email (thing-at-point 'email)))
  7766. (cond ((org-in-regexp org-link-any-re)
  7767. (org-link-open-from-string (match-string-no-properties 0)))
  7768. ((or (org-in-regexp org-ts-regexp-both nil t)
  7769. (org-in-regexp org-tsr-regexp-both nil t))
  7770. (org-follow-timestamp-link))
  7771. (tap-url (org-link-open-from-string tap-url))
  7772. (tap-email (org-link-open-from-string
  7773. (concat "mailto:" tap-email)))
  7774. (t (user-error "No link found")))))
  7775. (defvar org-open-at-point-functions nil
  7776. "Hook that is run when following a link at point.
  7777. Functions in this hook must return t if they identify and follow
  7778. a link at point. If they don't find anything interesting at point,
  7779. they must return nil.")
  7780. (defun org-open-at-point (&optional arg)
  7781. "Open link, timestamp, footnote or tags at point.
  7782. When point is on a link, follow it. Normally, files will be
  7783. opened by an appropriate application. If the optional prefix
  7784. argument ARG is non-nil, Emacs will visit the file. With
  7785. a double prefix argument, try to open outside of Emacs, in the
  7786. application the system uses for this file type.
  7787. When point is on a timestamp, open the agenda at the day
  7788. specified.
  7789. When point is a footnote definition, move to the first reference
  7790. found. If it is on a reference, move to the associated
  7791. definition.
  7792. When point is on a headline, display a list of every link in the
  7793. entry, so it is possible to pick one, or all, of them. If point
  7794. is on a tag, call `org-tags-view' instead.
  7795. On top of syntactically correct links, this function also tries
  7796. to open links and time-stamps in comments, node properties, and
  7797. keywords if point is on something looking like a timestamp or
  7798. a link."
  7799. (interactive "P")
  7800. (org-load-modules-maybe)
  7801. (setq org-window-config-before-follow-link (current-window-configuration))
  7802. (org-remove-occur-highlights nil nil t)
  7803. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7804. (let* ((context
  7805. ;; Only consider supported types, even if they are not the
  7806. ;; closest one.
  7807. (org-element-lineage
  7808. (org-element-context)
  7809. '(clock comment comment-block footnote-definition
  7810. footnote-reference headline inline-src-block inlinetask
  7811. keyword link node-property planning src-block timestamp)
  7812. t))
  7813. (type (org-element-type context))
  7814. (value (org-element-property :value context)))
  7815. (cond
  7816. ((not type) (user-error "No link found"))
  7817. ;; No valid link at point. For convenience, look if something
  7818. ;; looks like a link under point in some specific places.
  7819. ((memq type '(comment comment-block node-property keyword))
  7820. (call-interactively #'org-open-at-point-global))
  7821. ;; On a headline or an inlinetask, but not on a timestamp,
  7822. ;; a link, a footnote reference.
  7823. ((memq type '(headline inlinetask))
  7824. (org-match-line org-complex-heading-regexp)
  7825. (let ((tags-beg (match-beginning 5))
  7826. (tags-end (match-end 5)))
  7827. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7828. ;; On tags.
  7829. (org-tags-view
  7830. arg
  7831. (save-excursion
  7832. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7833. (end-tag (search-forward ":" tags-end nil 2)))
  7834. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7835. ;; Not on tags.
  7836. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7837. (`(nil . ,_)
  7838. (require 'org-attach)
  7839. (when (org-attach-dir)
  7840. (message "Opening attachment")
  7841. (if (equal arg '(4))
  7842. (org-attach-reveal-in-emacs)
  7843. (org-attach-reveal))))
  7844. (`(,links . ,links-end)
  7845. (dolist (link (if (stringp links) (list links) links))
  7846. (search-forward link nil links-end)
  7847. (goto-char (match-beginning 0))
  7848. (org-open-at-point arg)))))))
  7849. ;; On a footnote reference or at definition's label.
  7850. ((or (eq type 'footnote-reference)
  7851. (and (eq type 'footnote-definition)
  7852. (save-excursion
  7853. ;; Do not validate action when point is on the
  7854. ;; spaces right after the footnote label, in order
  7855. ;; to be on par with behavior on links.
  7856. (skip-chars-forward " \t")
  7857. (let ((begin
  7858. (org-element-property :contents-begin context)))
  7859. (if begin (< (point) begin)
  7860. (= (org-element-property :post-affiliated context)
  7861. (line-beginning-position)))))))
  7862. (org-footnote-action))
  7863. ;; On a planning line. Check if we are really on a timestamp.
  7864. ((and (eq type 'planning)
  7865. (org-in-regexp org-ts-regexp-both nil t))
  7866. (org-follow-timestamp-link))
  7867. ;; On a clock line, make sure point is on the timestamp
  7868. ;; before opening it.
  7869. ((and (eq type 'clock)
  7870. value
  7871. (>= (point) (org-element-property :begin value))
  7872. (<= (point) (org-element-property :end value)))
  7873. (org-follow-timestamp-link))
  7874. ((eq type 'src-block) (org-babel-open-src-block-result))
  7875. ;; Do nothing on white spaces after an object.
  7876. ((>= (point)
  7877. (save-excursion
  7878. (goto-char (org-element-property :end context))
  7879. (skip-chars-backward " \t")
  7880. (point)))
  7881. (user-error "No link found"))
  7882. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7883. ((eq type 'timestamp) (org-follow-timestamp-link))
  7884. ((eq type 'link) (org-link-open context arg))
  7885. (t (user-error "No link found")))))
  7886. (run-hook-with-args 'org-follow-link-hook))
  7887. ;;;###autoload
  7888. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7889. "Offer links in the current entry and return the selected link.
  7890. If there is only one link, return it.
  7891. If NTH is an integer, return the NTH link found.
  7892. If ZERO is a string, check also this string for a link, and if
  7893. there is one, return it."
  7894. (with-current-buffer buffer
  7895. (org-with-wide-buffer
  7896. (goto-char marker)
  7897. (let ((cnt ?0)
  7898. have-zero end links link c)
  7899. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7900. (push (match-string 0 zero) links)
  7901. (setq cnt (1- cnt) have-zero t))
  7902. (save-excursion
  7903. (org-back-to-heading t)
  7904. (setq end (save-excursion (outline-next-heading) (point)))
  7905. (while (re-search-forward org-link-any-re end t)
  7906. (push (match-string 0) links))
  7907. (setq links (org-uniquify (reverse links))))
  7908. (cond
  7909. ((null links)
  7910. (message "No links"))
  7911. ((equal (length links) 1)
  7912. (setq link (car links)))
  7913. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7914. (setq link (nth (if have-zero nth (1- nth)) links)))
  7915. (t ; we have to select a link
  7916. (save-excursion
  7917. (save-window-excursion
  7918. (delete-other-windows)
  7919. (with-output-to-temp-buffer "*Select Link*"
  7920. (dolist (l links)
  7921. (cond
  7922. ((not (string-match org-link-bracket-re l))
  7923. (princ (format "[%c] %s\n" (cl-incf cnt)
  7924. (org-unbracket-string "<" ">" l))))
  7925. ((match-end 2)
  7926. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7927. (match-string 2 l) (match-string 1 l))))
  7928. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7929. (match-string 1 l)))))))
  7930. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7931. (message "Select link to open, RET to open all:")
  7932. (setq c (read-char-exclusive))
  7933. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7934. (when (equal c ?q) (user-error "Abort"))
  7935. (if (equal c ?\C-m)
  7936. (setq link links)
  7937. (setq nth (- c ?0))
  7938. (when have-zero (setq nth (1+ nth)))
  7939. (unless (and (integerp nth) (>= (length links) nth))
  7940. (user-error "Invalid link selection"))
  7941. (setq link (nth (1- nth) links)))))
  7942. (cons link end)))))
  7943. ;;; File search
  7944. (defun org-do-occur (regexp &optional cleanup)
  7945. "Call the Emacs command `occur'.
  7946. If CLEANUP is non-nil, remove the printout of the regular expression
  7947. in the *Occur* buffer. This is useful if the regex is long and not useful
  7948. to read."
  7949. (occur regexp)
  7950. (when cleanup
  7951. (let ((cwin (selected-window)) win beg end)
  7952. (when (setq win (get-buffer-window "*Occur*"))
  7953. (select-window win))
  7954. (goto-char (point-min))
  7955. (when (re-search-forward "match[a-z]+" nil t)
  7956. (setq beg (match-end 0))
  7957. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7958. (setq end (1- (match-beginning 0)))))
  7959. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7960. (goto-char (point-min))
  7961. (select-window cwin))))
  7962. ;;; The Mark Ring
  7963. (defvar org-mark-ring nil
  7964. "Mark ring for positions before jumps in Org mode.")
  7965. (defvar org-mark-ring-last-goto nil
  7966. "Last position in the mark ring used to go back.")
  7967. ;; Fill and close the ring
  7968. (setq org-mark-ring nil)
  7969. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7970. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7971. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7972. org-mark-ring)
  7973. (defun org-mark-ring-push (&optional pos buffer)
  7974. "Put the current position into the mark ring and rotate it.
  7975. Also push position into the Emacs mark ring. If optional
  7976. argument POS and BUFFER are not nil, mark this location instead."
  7977. (interactive)
  7978. (let ((pos (or pos (point)))
  7979. (buffer (or buffer (current-buffer))))
  7980. (with-current-buffer buffer
  7981. (org-with-point-at pos (push-mark nil t)))
  7982. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  7983. (move-marker (car org-mark-ring) pos buffer))
  7984. (message
  7985. (substitute-command-keys
  7986. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  7987. (defun org-mark-ring-goto (&optional n)
  7988. "Jump to the previous position in the mark ring.
  7989. With prefix arg N, jump back that many stored positions. When
  7990. called several times in succession, walk through the entire ring.
  7991. Org mode commands jumping to a different position in the current file,
  7992. or to another Org file, automatically push the old position onto the ring."
  7993. (interactive "p")
  7994. (let (p m)
  7995. (if (eq last-command this-command)
  7996. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  7997. (setq p org-mark-ring))
  7998. (setq org-mark-ring-last-goto p)
  7999. (setq m (car p))
  8000. (pop-to-buffer-same-window (marker-buffer m))
  8001. (goto-char m)
  8002. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  8003. ;;; Following specific links
  8004. (defvar org-agenda-buffer-tmp-name)
  8005. (defvar org-agenda-start-on-weekday)
  8006. (defun org-follow-timestamp-link ()
  8007. "Open an agenda view for the time-stamp date/range at point."
  8008. (cond
  8009. ((org-at-date-range-p t)
  8010. (let ((org-agenda-start-on-weekday)
  8011. (t1 (match-string 1))
  8012. (t2 (match-string 2)) tt1 tt2)
  8013. (setq tt1 (time-to-days (org-time-string-to-time t1))
  8014. tt2 (time-to-days (org-time-string-to-time t2)))
  8015. (let ((org-agenda-buffer-tmp-name
  8016. (format "*Org Agenda(a:%s)"
  8017. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  8018. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  8019. ((org-at-timestamp-p 'lax)
  8020. (let ((org-agenda-buffer-tmp-name
  8021. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  8022. (org-agenda-list nil (time-to-days (org-time-string-to-time
  8023. (substring (match-string 1) 0 10)))
  8024. 1)))
  8025. (t (error "This should not happen"))))
  8026. ;;; Following file links
  8027. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  8028. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  8029. (declare-function mailcap-mime-info
  8030. "mailcap" (string &optional request no-decode))
  8031. (defvar org-wait nil)
  8032. ;;;; Refiling
  8033. (defun org-get-org-file ()
  8034. "Read a filename, with default directory `org-directory'."
  8035. (let ((default (or org-default-notes-file remember-data-file)))
  8036. (read-file-name (format "File name [%s]: " default)
  8037. (file-name-as-directory org-directory)
  8038. default)))
  8039. (defun org-notes-order-reversed-p ()
  8040. "Check if the current file should receive notes in reversed order."
  8041. (cond
  8042. ((not org-reverse-note-order) nil)
  8043. ((eq t org-reverse-note-order) t)
  8044. ((not (listp org-reverse-note-order)) nil)
  8045. (t (catch 'exit
  8046. (dolist (entry org-reverse-note-order)
  8047. (when (string-match (car entry) buffer-file-name)
  8048. (throw 'exit (cdr entry))))))))
  8049. (defvar org-refile-target-table nil
  8050. "The list of refile targets, created by `org-refile'.")
  8051. (defvar org-agenda-new-buffers nil
  8052. "Buffers created to visit agenda files.")
  8053. (defvar org-refile-cache nil
  8054. "Cache for refile targets.")
  8055. (defvar org-refile-markers nil
  8056. "All the markers used for caching refile locations.")
  8057. (defun org-refile-marker (pos)
  8058. "Get a new refile marker, but only if caching is in use."
  8059. (if (not org-refile-use-cache)
  8060. pos
  8061. (let ((m (make-marker)))
  8062. (move-marker m pos)
  8063. (push m org-refile-markers)
  8064. m)))
  8065. (defun org-refile-cache-clear ()
  8066. "Clear the refile cache and disable all the markers."
  8067. (dolist (m org-refile-markers) (move-marker m nil))
  8068. (setq org-refile-markers nil)
  8069. (setq org-refile-cache nil)
  8070. (message "Refile cache has been cleared"))
  8071. (defun org-refile-cache-check-set (set)
  8072. "Check if all the markers in the cache still have live buffers."
  8073. (let (marker)
  8074. (catch 'exit
  8075. (while (and set (setq marker (nth 3 (pop set))))
  8076. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  8077. (when (and marker (null (marker-buffer marker)))
  8078. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  8079. (sit-for 3)
  8080. (throw 'exit nil)))
  8081. t)))
  8082. (defun org-refile-cache-put (set &rest identifiers)
  8083. "Push the refile targets SET into the cache, under IDENTIFIERS."
  8084. (let* ((key (sha1 (prin1-to-string identifiers)))
  8085. (entry (assoc key org-refile-cache)))
  8086. (if entry
  8087. (setcdr entry set)
  8088. (push (cons key set) org-refile-cache))))
  8089. (defun org-refile-cache-get (&rest identifiers)
  8090. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  8091. (cond
  8092. ((not org-refile-cache) nil)
  8093. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  8094. (t
  8095. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  8096. org-refile-cache))))
  8097. (and set (org-refile-cache-check-set set) set)))))
  8098. (defvar org-outline-path-cache nil
  8099. "Alist between buffer positions and outline paths.
  8100. It value is an alist (POSITION . PATH) where POSITION is the
  8101. buffer position at the beginning of an entry and PATH is a list
  8102. of strings describing the outline path for that entry, in reverse
  8103. order.")
  8104. (defun org-refile-get-targets (&optional default-buffer)
  8105. "Produce a table with refile targets."
  8106. (let ((case-fold-search nil)
  8107. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  8108. (entries (or org-refile-targets '((nil . (:level . 1)))))
  8109. targets tgs files desc descre)
  8110. (message "Getting targets...")
  8111. (with-current-buffer (or default-buffer (current-buffer))
  8112. (dolist (entry entries)
  8113. (setq files (car entry) desc (cdr entry))
  8114. (cond
  8115. ((null files) (setq files (list (current-buffer))))
  8116. ((eq files 'org-agenda-files)
  8117. (setq files (org-agenda-files 'unrestricted)))
  8118. ((and (symbolp files) (fboundp files))
  8119. (setq files (funcall files)))
  8120. ((and (symbolp files) (boundp files))
  8121. (setq files (symbol-value files))))
  8122. (when (stringp files) (setq files (list files)))
  8123. (cond
  8124. ((eq (car desc) :tag)
  8125. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  8126. ((eq (car desc) :todo)
  8127. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  8128. ((eq (car desc) :regexp)
  8129. (setq descre (cdr desc)))
  8130. ((eq (car desc) :level)
  8131. (setq descre (concat "^\\*\\{" (number-to-string
  8132. (if org-odd-levels-only
  8133. (1- (* 2 (cdr desc)))
  8134. (cdr desc)))
  8135. "\\}[ \t]")))
  8136. ((eq (car desc) :maxlevel)
  8137. (setq descre (concat "^\\*\\{1," (number-to-string
  8138. (if org-odd-levels-only
  8139. (1- (* 2 (cdr desc)))
  8140. (cdr desc)))
  8141. "\\}[ \t]")))
  8142. (t (error "Bad refiling target description %s" desc)))
  8143. (dolist (f files)
  8144. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  8145. (or
  8146. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  8147. (progn
  8148. (when (bufferp f)
  8149. (setq f (buffer-file-name (buffer-base-buffer f))))
  8150. (setq f (and f (expand-file-name f)))
  8151. (when (eq org-refile-use-outline-path 'file)
  8152. (push (list (file-name-nondirectory f) f nil nil) tgs))
  8153. (when (eq org-refile-use-outline-path 'buffer-name)
  8154. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  8155. (when (eq org-refile-use-outline-path 'full-file-path)
  8156. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  8157. (org-with-wide-buffer
  8158. (goto-char (point-min))
  8159. (setq org-outline-path-cache nil)
  8160. (while (re-search-forward descre nil t)
  8161. (beginning-of-line)
  8162. (let ((case-fold-search nil))
  8163. (looking-at org-complex-heading-regexp))
  8164. (let ((begin (point))
  8165. (heading (match-string-no-properties 4)))
  8166. (unless (or (and
  8167. org-refile-target-verify-function
  8168. (not
  8169. (funcall org-refile-target-verify-function)))
  8170. (not heading))
  8171. (let ((re (format org-complex-heading-regexp-format
  8172. (regexp-quote heading)))
  8173. (target
  8174. (if (not org-refile-use-outline-path) heading
  8175. (mapconcat
  8176. #'identity
  8177. (append
  8178. (pcase org-refile-use-outline-path
  8179. (`file (list (file-name-nondirectory
  8180. (buffer-file-name
  8181. (buffer-base-buffer)))))
  8182. (`full-file-path
  8183. (list (buffer-file-name
  8184. (buffer-base-buffer))))
  8185. (`buffer-name
  8186. (list (buffer-name
  8187. (buffer-base-buffer))))
  8188. (_ nil))
  8189. (mapcar (lambda (s) (replace-regexp-in-string
  8190. "/" "\\/" s nil t))
  8191. (org-get-outline-path t t)))
  8192. "/"))))
  8193. (push (list target f re (org-refile-marker (point)))
  8194. tgs)))
  8195. (when (= (point) begin)
  8196. ;; Verification function has not moved point.
  8197. (end-of-line)))))))
  8198. (when org-refile-use-cache
  8199. (org-refile-cache-put tgs (buffer-file-name) descre))
  8200. (setq targets (append tgs targets))))))
  8201. (message "Getting targets...done")
  8202. (delete-dups (nreverse targets))))
  8203. (defun org--get-outline-path-1 (&optional use-cache)
  8204. "Return outline path to current headline.
  8205. Outline path is a list of strings, in reverse order. When
  8206. optional argument USE-CACHE is non-nil, make use of a cache. See
  8207. `org-get-outline-path' for details.
  8208. Assume buffer is widened and point is on a headline."
  8209. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  8210. (let ((p (point))
  8211. (heading (let ((case-fold-search nil))
  8212. (looking-at org-complex-heading-regexp)
  8213. (if (not (match-end 4)) ""
  8214. ;; Remove statistics cookies.
  8215. (org-trim
  8216. (org-link-display-format
  8217. (replace-regexp-in-string
  8218. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  8219. (match-string-no-properties 4))))))))
  8220. (if (org-up-heading-safe)
  8221. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  8222. (when use-cache
  8223. (push (cons p path) org-outline-path-cache))
  8224. path)
  8225. ;; This is a new root node. Since we assume we are moving
  8226. ;; forward, we can drop previous cache so as to limit number
  8227. ;; of associations there.
  8228. (let ((path (list heading)))
  8229. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  8230. path)))))
  8231. (defun org-get-outline-path (&optional with-self use-cache)
  8232. "Return the outline path to the current entry.
  8233. An outline path is a list of ancestors for current headline, as
  8234. a list of strings. Statistics cookies are removed and links are
  8235. replaced with their description, if any, or their path otherwise.
  8236. When optional argument WITH-SELF is non-nil, the path also
  8237. includes the current headline.
  8238. When optional argument USE-CACHE is non-nil, cache outline paths
  8239. between calls to this function so as to avoid backtracking. This
  8240. argument is useful when planning to find more than one outline
  8241. path in the same document. In that case, there are two
  8242. conditions to satisfy:
  8243. - `org-outline-path-cache' is set to nil before starting the
  8244. process;
  8245. - outline paths are computed by increasing buffer positions."
  8246. (org-with-wide-buffer
  8247. (and (or (and with-self (org-back-to-heading t))
  8248. (org-up-heading-safe))
  8249. (reverse (org--get-outline-path-1 use-cache)))))
  8250. (defun org-format-outline-path (path &optional width prefix separator)
  8251. "Format the outline path PATH for display.
  8252. WIDTH is the maximum number of characters that is available.
  8253. PREFIX is a prefix to be included in the returned string,
  8254. such as the file name.
  8255. SEPARATOR is inserted between the different parts of the path,
  8256. the default is \"/\"."
  8257. (setq width (or width 79))
  8258. (setq path (delq nil path))
  8259. (unless (> width 0)
  8260. (user-error "Argument `width' must be positive"))
  8261. (setq separator (or separator "/"))
  8262. (let* ((org-odd-levels-only nil)
  8263. (fpath (concat
  8264. prefix (and prefix path separator)
  8265. (mapconcat
  8266. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  8267. (cl-loop for head in path
  8268. for n from 0
  8269. collect (org-add-props
  8270. head nil 'face
  8271. (nth (% n org-n-level-faces) org-level-faces)))
  8272. separator))))
  8273. (when (> (length fpath) width)
  8274. (if (< width 7)
  8275. ;; It's unlikely that `width' will be this small, but don't
  8276. ;; waste characters by adding ".." if it is.
  8277. (setq fpath (substring fpath 0 width))
  8278. (setf (substring fpath (- width 2)) "..")))
  8279. fpath))
  8280. (defun org-display-outline-path (&optional file current separator just-return-string)
  8281. "Display the current outline path in the echo area.
  8282. If FILE is non-nil, prepend the output with the file name.
  8283. If CURRENT is non-nil, append the current heading to the output.
  8284. SEPARATOR is passed through to `org-format-outline-path'. It separates
  8285. the different parts of the path and defaults to \"/\".
  8286. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  8287. (interactive "P")
  8288. (let* (case-fold-search
  8289. (bfn (buffer-file-name (buffer-base-buffer)))
  8290. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  8291. res)
  8292. (when current (setq path (append path
  8293. (save-excursion
  8294. (org-back-to-heading t)
  8295. (when (looking-at org-complex-heading-regexp)
  8296. (list (match-string 4)))))))
  8297. (setq res
  8298. (org-format-outline-path
  8299. path
  8300. (1- (frame-width))
  8301. (and file bfn (concat (file-name-nondirectory bfn) separator))
  8302. separator))
  8303. (if just-return-string
  8304. (org-no-properties res)
  8305. (org-unlogged-message "%s" res))))
  8306. (defvar org-refile-history nil
  8307. "History for refiling operations.")
  8308. (defvar org-after-refile-insert-hook nil
  8309. "Hook run after `org-refile' has inserted its stuff at the new location.
  8310. Note that this is still *before* the stuff will be removed from
  8311. the *old* location.")
  8312. (defvar org-capture-last-stored-marker)
  8313. (defvar org-refile-keep nil
  8314. "Non-nil means `org-refile' will copy instead of refile.")
  8315. (defun org-copy ()
  8316. "Like `org-refile', but copy."
  8317. (interactive)
  8318. (let ((org-refile-keep t))
  8319. (org-refile nil nil nil "Copy")))
  8320. (defun org-refile (&optional arg default-buffer rfloc msg)
  8321. "Move the entry or entries at point to another heading.
  8322. The list of target headings is compiled using the information in
  8323. `org-refile-targets', which see.
  8324. At the target location, the entry is filed as a subitem of the
  8325. target heading. Depending on `org-reverse-note-order', the new
  8326. subitem will either be the first or the last subitem.
  8327. If there is an active region, all entries in that region will be
  8328. refiled. However, the region must fulfill the requirement that
  8329. the first heading sets the top-level of the moved text.
  8330. With a `\\[universal-argument]' ARG, the command will only visit the target \
  8331. location
  8332. and not actually move anything.
  8333. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  8334. location where the last
  8335. refiling operation has put the subtree.
  8336. With a numeric prefix argument of `2', refile to the running clock.
  8337. With a numeric prefix argument of `3', emulate `org-refile-keep'
  8338. being set to t and copy to the target location, don't move it.
  8339. Beware that keeping refiled entries may result in duplicated ID
  8340. properties.
  8341. RFLOC can be a refile location obtained in a different way.
  8342. MSG is a string to replace \"Refile\" in the default prompt with
  8343. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  8344. See also `org-refile-use-outline-path'.
  8345. If you are using target caching (see `org-refile-use-cache'), you
  8346. have to clear the target cache in order to find new targets.
  8347. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  8348. prefix argument (`C-u C-u C-u C-c C-w')."
  8349. (interactive "P")
  8350. (if (member arg '(0 (64)))
  8351. (org-refile-cache-clear)
  8352. (let* ((actionmsg (cond (msg msg)
  8353. ((equal arg 3) "Refile (and keep)")
  8354. (t "Refile")))
  8355. (regionp (org-region-active-p))
  8356. (region-start (and regionp (region-beginning)))
  8357. (region-end (and regionp (region-end)))
  8358. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  8359. pos it nbuf file level reversed)
  8360. (setq last-command nil)
  8361. (when regionp
  8362. (goto-char region-start)
  8363. (beginning-of-line)
  8364. (setq region-start (point))
  8365. (unless (or (org-kill-is-subtree-p
  8366. (buffer-substring region-start region-end))
  8367. (prog1 org-refile-active-region-within-subtree
  8368. (let ((s (point-at-eol)))
  8369. (org-toggle-heading)
  8370. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  8371. (user-error "The region is not a (sequence of) subtree(s)")))
  8372. (if (equal arg '(16))
  8373. (org-refile-goto-last-stored)
  8374. (when (or
  8375. (and (equal arg 2)
  8376. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  8377. (prog1
  8378. (setq it (list (or org-clock-heading "running clock")
  8379. (buffer-file-name
  8380. (marker-buffer org-clock-hd-marker))
  8381. ""
  8382. (marker-position org-clock-hd-marker)))
  8383. (setq arg nil)))
  8384. (setq it
  8385. (or rfloc
  8386. (let (heading-text)
  8387. (save-excursion
  8388. (unless (and arg (listp arg))
  8389. (org-back-to-heading t)
  8390. (setq heading-text
  8391. (replace-regexp-in-string
  8392. org-link-bracket-re
  8393. "\\2"
  8394. (or (nth 4 (org-heading-components))
  8395. ""))))
  8396. (org-refile-get-location
  8397. (cond ((and arg (listp arg)) "Goto")
  8398. (regionp (concat actionmsg " region to"))
  8399. (t (concat actionmsg " subtree \""
  8400. heading-text "\" to")))
  8401. default-buffer
  8402. (and (not (equal '(4) arg))
  8403. org-refile-allow-creating-parent-nodes)))))))
  8404. (setq file (nth 1 it)
  8405. pos (nth 3 it))
  8406. (when (and (not arg)
  8407. pos
  8408. (equal (buffer-file-name) file)
  8409. (if regionp
  8410. (and (>= pos region-start)
  8411. (<= pos region-end))
  8412. (and (>= pos (point))
  8413. (< pos (save-excursion
  8414. (org-end-of-subtree t t))))))
  8415. (error "Cannot refile to position inside the tree or region"))
  8416. (setq nbuf (or (find-buffer-visiting file)
  8417. (find-file-noselect file)))
  8418. (if (and arg (not (equal arg 3)))
  8419. (progn
  8420. (pop-to-buffer-same-window nbuf)
  8421. (goto-char (cond (pos)
  8422. ((org-notes-order-reversed-p) (point-min))
  8423. (t (point-max))))
  8424. (org-show-context 'org-goto))
  8425. (if regionp
  8426. (progn
  8427. (org-kill-new (buffer-substring region-start region-end))
  8428. (org-save-markers-in-region region-start region-end))
  8429. (org-copy-subtree 1 nil t))
  8430. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  8431. (find-file-noselect file)))
  8432. (setq reversed (org-notes-order-reversed-p))
  8433. (org-with-wide-buffer
  8434. (if pos
  8435. (progn
  8436. (goto-char pos)
  8437. (setq level (org-get-valid-level (funcall outline-level) 1))
  8438. (goto-char
  8439. (if reversed
  8440. (or (outline-next-heading) (point-max))
  8441. (or (save-excursion (org-get-next-sibling))
  8442. (org-end-of-subtree t t)
  8443. (point-max)))))
  8444. (setq level 1)
  8445. (if (not reversed)
  8446. (goto-char (point-max))
  8447. (goto-char (point-min))
  8448. (or (outline-next-heading) (goto-char (point-max)))))
  8449. (unless (bolp) (newline))
  8450. (org-paste-subtree level nil nil t)
  8451. ;; Record information, according to `org-log-refile'.
  8452. ;; Do not prompt for a note when refiling multiple
  8453. ;; headlines, however. Simply add a time stamp.
  8454. (cond
  8455. ((not org-log-refile))
  8456. (regionp
  8457. (org-map-region
  8458. (lambda () (org-add-log-setup 'refile nil nil 'time))
  8459. (point)
  8460. (+ (point) (- region-end region-start))))
  8461. (t
  8462. (org-add-log-setup 'refile nil nil org-log-refile)))
  8463. (and org-auto-align-tags
  8464. (let ((org-loop-over-headlines-in-active-region nil))
  8465. (org-align-tags)))
  8466. (let ((bookmark-name (plist-get org-bookmark-names-plist
  8467. :last-refile)))
  8468. (when bookmark-name
  8469. (with-demoted-errors
  8470. (bookmark-set bookmark-name))))
  8471. ;; If we are refiling for capture, make sure that the
  8472. ;; last-capture pointers point here
  8473. (when (bound-and-true-p org-capture-is-refiling)
  8474. (let ((bookmark-name (plist-get org-bookmark-names-plist
  8475. :last-capture-marker)))
  8476. (when bookmark-name
  8477. (with-demoted-errors
  8478. (bookmark-set bookmark-name))))
  8479. (move-marker org-capture-last-stored-marker (point)))
  8480. (when (fboundp 'deactivate-mark) (deactivate-mark))
  8481. (run-hooks 'org-after-refile-insert-hook)))
  8482. (unless org-refile-keep
  8483. (if regionp
  8484. (delete-region (point) (+ (point) (- region-end region-start)))
  8485. (org-preserve-local-variables
  8486. (delete-region
  8487. (and (org-back-to-heading t) (point))
  8488. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  8489. (when (featurep 'org-inlinetask)
  8490. (org-inlinetask-remove-END-maybe))
  8491. (setq org-markers-to-move nil)
  8492. (message "%s to \"%s\" in file %s: done" actionmsg
  8493. (car it) file)))))))
  8494. (defun org-refile-goto-last-stored ()
  8495. "Go to the location where the last refile was stored."
  8496. (interactive)
  8497. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  8498. (message "This is the location of the last refile"))
  8499. (defun org-refile--get-location (refloc tbl)
  8500. "When user refile to REFLOC, find the associated target in TBL.
  8501. Also check `org-refile-target-table'."
  8502. (car (delq
  8503. nil
  8504. (mapcar
  8505. (lambda (r) (or (assoc r tbl)
  8506. (assoc r org-refile-target-table)))
  8507. (list (replace-regexp-in-string "/$" "" refloc)
  8508. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  8509. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  8510. "Prompt the user for a refile location, using PROMPT.
  8511. PROMPT should not be suffixed with a colon and a space, because
  8512. this function appends the default value from
  8513. `org-refile-history' automatically, if that is not empty."
  8514. (let ((org-refile-targets org-refile-targets)
  8515. (org-refile-use-outline-path org-refile-use-outline-path))
  8516. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  8517. (unless org-refile-target-table
  8518. (user-error "No refile targets"))
  8519. (let* ((cbuf (current-buffer))
  8520. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  8521. (cfunc (if (and org-refile-use-outline-path
  8522. org-outline-path-complete-in-steps)
  8523. #'org-olpath-completing-read
  8524. #'completing-read))
  8525. (extra (if org-refile-use-outline-path "/" ""))
  8526. (cbnex (concat (buffer-name) extra))
  8527. (filename (and cfn (expand-file-name cfn)))
  8528. (tbl (mapcar
  8529. (lambda (x)
  8530. (if (and (not (member org-refile-use-outline-path
  8531. '(file full-file-path)))
  8532. (not (equal filename (nth 1 x))))
  8533. (cons (concat (car x) extra " ("
  8534. (file-name-nondirectory (nth 1 x)) ")")
  8535. (cdr x))
  8536. (cons (concat (car x) extra) (cdr x))))
  8537. org-refile-target-table))
  8538. (completion-ignore-case t)
  8539. cdef
  8540. (prompt (concat prompt
  8541. (or (and (car org-refile-history)
  8542. (concat " (default " (car org-refile-history) ")"))
  8543. (and (assoc cbnex tbl) (setq cdef cbnex)
  8544. (concat " (default " cbnex ")"))) ": "))
  8545. pa answ parent-target child parent old-hist)
  8546. (setq old-hist org-refile-history)
  8547. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  8548. nil 'org-refile-history (or cdef (car org-refile-history))))
  8549. (if (setq pa (org-refile--get-location answ tbl))
  8550. (progn
  8551. (org-refile-check-position pa)
  8552. (when (or (not org-refile-history)
  8553. (not (eq old-hist org-refile-history))
  8554. (not (equal (car pa) (car org-refile-history))))
  8555. (setq org-refile-history
  8556. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  8557. org-refile-history
  8558. (cdr org-refile-history))))
  8559. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  8560. (pop org-refile-history)))
  8561. pa)
  8562. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  8563. (progn
  8564. (setq parent (match-string 1 answ)
  8565. child (match-string 2 answ))
  8566. (setq parent-target (org-refile--get-location parent tbl))
  8567. (when (and parent-target
  8568. (or (eq new-nodes t)
  8569. (and (eq new-nodes 'confirm)
  8570. (y-or-n-p (format "Create new node \"%s\"? "
  8571. child)))))
  8572. (org-refile-new-child parent-target child)))
  8573. (user-error "Invalid target location")))))
  8574. (declare-function org-string-nw-p "org-macs" (s))
  8575. (defun org-refile-check-position (refile-pointer)
  8576. "Check if the refile pointer matches the headline to which it points."
  8577. (let* ((file (nth 1 refile-pointer))
  8578. (re (nth 2 refile-pointer))
  8579. (pos (nth 3 refile-pointer))
  8580. buffer)
  8581. (if (and (not (markerp pos)) (not file))
  8582. (user-error "Please indicate a target file in the refile path")
  8583. (when (org-string-nw-p re)
  8584. (setq buffer (if (markerp pos)
  8585. (marker-buffer pos)
  8586. (or (find-buffer-visiting file)
  8587. (find-file-noselect file))))
  8588. (with-current-buffer buffer
  8589. (org-with-wide-buffer
  8590. (goto-char pos)
  8591. (beginning-of-line 1)
  8592. (unless (looking-at-p re)
  8593. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  8594. (defun org-refile-new-child (parent-target child)
  8595. "Use refile target PARENT-TARGET to add new CHILD below it."
  8596. (unless parent-target
  8597. (error "Cannot find parent for new node"))
  8598. (let ((file (nth 1 parent-target))
  8599. (pos (nth 3 parent-target))
  8600. level)
  8601. (with-current-buffer (or (find-buffer-visiting file)
  8602. (find-file-noselect file))
  8603. (org-with-wide-buffer
  8604. (if pos
  8605. (goto-char pos)
  8606. (goto-char (point-max))
  8607. (unless (bolp) (newline)))
  8608. (when (looking-at org-outline-regexp)
  8609. (setq level (funcall outline-level))
  8610. (org-end-of-subtree t t))
  8611. (org-back-over-empty-lines)
  8612. (insert "\n" (make-string
  8613. (if pos (org-get-valid-level level 1) 1) ?*)
  8614. " " child "\n")
  8615. (beginning-of-line 0)
  8616. (list (concat (car parent-target) "/" child) file "" (point))))))
  8617. (defun org-olpath-completing-read (prompt collection &rest args)
  8618. "Read an outline path like a file name."
  8619. (let ((thetable collection))
  8620. (apply #'completing-read
  8621. prompt
  8622. (lambda (string predicate &optional flag)
  8623. (cond
  8624. ((eq flag nil) (try-completion string thetable))
  8625. ((eq flag t)
  8626. (let ((l (length string)))
  8627. (mapcar (lambda (x)
  8628. (let ((r (substring x l))
  8629. (f (if (string-match " ([^)]*)$" x)
  8630. (match-string 0 x)
  8631. "")))
  8632. (if (string-match "/" r)
  8633. (concat string (substring r 0 (match-end 0)) f)
  8634. x)))
  8635. (all-completions string thetable predicate))))
  8636. ;; Exact match?
  8637. ((eq flag 'lambda) (assoc string thetable))))
  8638. args)))
  8639. ;;;; Dynamic blocks
  8640. (defun org-find-dblock (name)
  8641. "Find the first dynamic block with name NAME in the buffer.
  8642. If not found, stay at current position and return nil."
  8643. (let ((case-fold-search t) pos)
  8644. (save-excursion
  8645. (goto-char (point-min))
  8646. (setq pos (and (re-search-forward
  8647. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8648. (match-beginning 0))))
  8649. (when pos (goto-char pos))
  8650. pos))
  8651. (defun org-create-dblock (plist)
  8652. "Create a dynamic block section, with parameters taken from PLIST.
  8653. PLIST must contain a :name entry which is used as the name of the block."
  8654. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8655. (end-of-line 1)
  8656. (newline))
  8657. (let ((col (current-column))
  8658. (name (plist-get plist :name)))
  8659. (insert "#+BEGIN: " name)
  8660. (while plist
  8661. (if (eq (car plist) :name)
  8662. (setq plist (cddr plist))
  8663. (insert " " (prin1-to-string (pop plist)))))
  8664. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8665. (beginning-of-line -2)))
  8666. (defun org-prepare-dblock ()
  8667. "Prepare dynamic block for refresh.
  8668. This empties the block, puts the cursor at the insert position and returns
  8669. the property list including an extra property :name with the block name."
  8670. (unless (looking-at org-dblock-start-re)
  8671. (user-error "Not at a dynamic block"))
  8672. (let* ((begdel (1+ (match-end 0)))
  8673. (name (org-no-properties (match-string 1)))
  8674. (params (append (list :name name)
  8675. (read (concat "(" (match-string 3) ")")))))
  8676. (save-excursion
  8677. (beginning-of-line 1)
  8678. (skip-chars-forward " \t")
  8679. (setq params (plist-put params :indentation-column (current-column))))
  8680. (unless (re-search-forward org-dblock-end-re nil t)
  8681. (error "Dynamic block not terminated"))
  8682. (setq params
  8683. (append params
  8684. (list :content (buffer-substring
  8685. begdel (match-beginning 0)))))
  8686. (delete-region begdel (match-beginning 0))
  8687. (goto-char begdel)
  8688. (open-line 1)
  8689. params))
  8690. (defun org-map-dblocks (&optional command)
  8691. "Apply COMMAND to all dynamic blocks in the current buffer.
  8692. If COMMAND is not given, use `org-update-dblock'."
  8693. (let ((cmd (or command 'org-update-dblock)))
  8694. (save-excursion
  8695. (goto-char (point-min))
  8696. (while (re-search-forward org-dblock-start-re nil t)
  8697. (goto-char (match-beginning 0))
  8698. (save-excursion
  8699. (condition-case nil
  8700. (funcall cmd)
  8701. (error (message "Error during update of dynamic block"))))
  8702. (unless (re-search-forward org-dblock-end-re nil t)
  8703. (error "Dynamic block not terminated"))))))
  8704. (defvar org-dynamic-block-alist nil
  8705. "Alist defining all the Org dynamic blocks.
  8706. The key is the dynamic block type name, as a string. The value
  8707. is the function used to insert the dynamic block.
  8708. Use `org-dynamic-block-define' to populate it.")
  8709. (defun org-dynamic-block-function (type)
  8710. "Return function associated to a given dynamic block type.
  8711. TYPE is the dynamic block type, as a string."
  8712. (cdr (assoc type org-dynamic-block-alist)))
  8713. (defun org-dynamic-block-types ()
  8714. "List all defined dynamic block types."
  8715. (mapcar #'car org-dynamic-block-alist))
  8716. (defun org-dynamic-block-define (type func)
  8717. "Define dynamic block TYPE with FUNC.
  8718. TYPE is a string. FUNC is the function creating the dynamic
  8719. block of such type."
  8720. (pcase (assoc type org-dynamic-block-alist)
  8721. (`nil (push (cons type func) org-dynamic-block-alist))
  8722. (def (setcdr def func))))
  8723. (defun org-dynamic-block-insert-dblock (type)
  8724. "Insert a dynamic block of type TYPE.
  8725. When used interactively, select the dynamic block types among
  8726. defined types, per `org-dynamic-block-define'."
  8727. (interactive (list (completing-read "Dynamic block: "
  8728. (org-dynamic-block-types))))
  8729. (pcase (org-dynamic-block-function type)
  8730. (`nil (error "No such dynamic block: %S" type))
  8731. ((and f (pred functionp)) (funcall f))
  8732. (_ (error "Invalid function for dynamic block %S" type))))
  8733. (defun org-dblock-update (&optional arg)
  8734. "User command for updating dynamic blocks.
  8735. Update the dynamic block at point. With prefix ARG, update all dynamic
  8736. blocks in the buffer."
  8737. (interactive "P")
  8738. (if arg
  8739. (org-update-all-dblocks)
  8740. (or (looking-at org-dblock-start-re)
  8741. (org-beginning-of-dblock))
  8742. (org-update-dblock)))
  8743. (defun org-update-dblock ()
  8744. "Update the dynamic block at point.
  8745. This means to empty the block, parse for parameters and then call
  8746. the correct writing function."
  8747. (interactive)
  8748. (save-excursion
  8749. (let* ((win (selected-window))
  8750. (pos (point))
  8751. (line (org-current-line))
  8752. (params (org-prepare-dblock))
  8753. (name (plist-get params :name))
  8754. (indent (plist-get params :indentation-column))
  8755. (cmd (intern (concat "org-dblock-write:" name))))
  8756. (message "Updating dynamic block `%s' at line %d..." name line)
  8757. (funcall cmd params)
  8758. (message "Updating dynamic block `%s' at line %d...done" name line)
  8759. (goto-char pos)
  8760. (when (and indent (> indent 0))
  8761. (setq indent (make-string indent ?\ ))
  8762. (save-excursion
  8763. (select-window win)
  8764. (org-beginning-of-dblock)
  8765. (forward-line 1)
  8766. (while (not (looking-at org-dblock-end-re))
  8767. (insert indent)
  8768. (beginning-of-line 2))
  8769. (when (looking-at org-dblock-end-re)
  8770. (and (looking-at "[ \t]+")
  8771. (replace-match ""))
  8772. (insert indent)))))))
  8773. (defun org-beginning-of-dblock ()
  8774. "Find the beginning of the dynamic block at point.
  8775. Error if there is no such block at point."
  8776. (let ((pos (point))
  8777. beg)
  8778. (end-of-line 1)
  8779. (if (and (re-search-backward org-dblock-start-re nil t)
  8780. (setq beg (match-beginning 0))
  8781. (re-search-forward org-dblock-end-re nil t)
  8782. (> (match-end 0) pos))
  8783. (goto-char beg)
  8784. (goto-char pos)
  8785. (error "Not in a dynamic block"))))
  8786. (defun org-update-all-dblocks ()
  8787. "Update all dynamic blocks in the buffer.
  8788. This function can be used in a hook."
  8789. (interactive)
  8790. (when (derived-mode-p 'org-mode)
  8791. (org-map-dblocks 'org-update-dblock)))
  8792. ;;;; Completion
  8793. (declare-function org-export-backend-options "ox" (cl-x) t)
  8794. (defun org-get-export-keywords ()
  8795. "Return a list of all currently understood export keywords.
  8796. Export keywords include options, block names, attributes and
  8797. keywords relative to each registered export back-end."
  8798. (let (keywords)
  8799. (dolist (backend
  8800. (bound-and-true-p org-export-registered-backends)
  8801. (delq nil keywords))
  8802. ;; Back-end name (for keywords, like #+LATEX:)
  8803. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8804. (dolist (option-entry (org-export-backend-options backend))
  8805. ;; Back-end options.
  8806. (push (nth 1 option-entry) keywords)))))
  8807. (defconst org-options-keywords
  8808. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8809. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8810. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8811. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8812. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8813. (defcustom org-structure-template-alist
  8814. '(("a" . "export ascii")
  8815. ("c" . "center")
  8816. ("C" . "comment")
  8817. ("e" . "example")
  8818. ("E" . "export")
  8819. ("h" . "export html")
  8820. ("l" . "export latex")
  8821. ("q" . "quote")
  8822. ("s" . "src")
  8823. ("v" . "verse"))
  8824. "An alist of keys and block types.
  8825. `org-insert-structure-template' will display a menu with this
  8826. list of templates to choose from. The block type is inserted,
  8827. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8828. The menu keys are defined by the car of each entry in this alist.
  8829. If two entries have the keys \"a\" and \"aa\" respectively, the
  8830. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8831. latter will be inserted by typing \"aa\". If an entry with the
  8832. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8833. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8834. block can be inserted by pressing TAB after the string \"<KEY\"."
  8835. :group 'org-edit-structure
  8836. :type '(repeat
  8837. (cons (string :tag "Key")
  8838. (string :tag "Template")))
  8839. :package-version '(Org . "9.2"))
  8840. (defun org--check-org-structure-template-alist (&optional checklist)
  8841. "Check whether `org-structure-template-alist' is set up correctly.
  8842. In particular, check if the Org 9.2 format is used as opposed to
  8843. previous format.
  8844. "
  8845. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8846. (or (eval checklist)
  8847. org-structure-template-alist))))
  8848. (when elm
  8849. (org-display-warning
  8850. (format "
  8851. Please update the entries of `%s'.
  8852. In Org 9.2 the format was changed from something like
  8853. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8854. to something like
  8855. (\"s\" . \"src\")
  8856. Please refer to the documentation of `org-structure-template-alist'.
  8857. The following entries must be updated:
  8858. %s"
  8859. (or checklist 'org-structure-template-alist)
  8860. (pp-to-string elm))))))
  8861. (defun org--insert-structure-template-mks ()
  8862. "Present `org-structure-template-alist' with `org-mks'.
  8863. Menus are added if keys require more than one keystroke. Tabs
  8864. are added to single key entries when more than one stroke is
  8865. needed. Keys longer than two characters are reduced to two
  8866. characters."
  8867. (org--check-org-structure-template-alist)
  8868. (let* (case-fold-search
  8869. (templates (append org-structure-template-alist
  8870. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8871. (keys (mapcar #'car templates))
  8872. (start-letters
  8873. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8874. ;; Sort each element of `org-structure-template-alist' into
  8875. ;; sublists according to the first letter.
  8876. (superlist
  8877. (mapcar (lambda (letter)
  8878. (list letter
  8879. (cl-remove-if-not
  8880. (apply-partially #'string-match-p (concat "^" letter))
  8881. templates :key #'car)))
  8882. start-letters)))
  8883. (org-mks
  8884. (apply #'append
  8885. ;; Make an `org-mks' table. If only one element is
  8886. ;; present in a sublist, make it part of the top-menu,
  8887. ;; otherwise make a submenu according to the starting
  8888. ;; letter and populate it.
  8889. (mapcar (lambda (sublist)
  8890. (if (eq 1 (length (cadr sublist)))
  8891. (mapcar (lambda (elm)
  8892. (list (substring (car elm) 0 1)
  8893. (cdr elm) ""))
  8894. (cadr sublist))
  8895. ;; Create submenu.
  8896. (let* ((topkey (car sublist))
  8897. (elms (cadr sublist))
  8898. (keys (mapcar #'car elms))
  8899. (long (> (length elms) 3)))
  8900. (append
  8901. (list
  8902. ;; Make a description of the submenu.
  8903. (list topkey
  8904. (concat
  8905. (mapconcat #'cdr
  8906. (cl-subseq elms 0 (if long 3 (length elms)))
  8907. ", ")
  8908. (when long ", ..."))))
  8909. ;; List of entries in submenu.
  8910. (cl-mapcar #'list
  8911. (org--insert-structure-template-unique-keys keys)
  8912. (mapcar #'cdr elms)
  8913. (make-list (length elms) ""))))))
  8914. superlist))
  8915. "Select a key\n============"
  8916. "Key: ")))
  8917. (defun org--insert-structure-template-unique-keys (keys)
  8918. "Make a list of unique, two characters long elements from KEYS.
  8919. Elements of length one have a tab appended. Elements of length
  8920. two are kept as is. Longer elements are truncated to length two.
  8921. If an element cannot be made unique, an error is raised."
  8922. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8923. menu-keys)
  8924. (dolist (key ordered-keys)
  8925. (let ((potential-key
  8926. (cl-case (length key)
  8927. (1 (concat key "\t"))
  8928. (2 key)
  8929. (otherwise
  8930. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8931. (mapcar (apply-partially #'concat (substring key 0 1))
  8932. (split-string (substring key 1) "" t)))))))
  8933. (if (or (not potential-key) (assoc potential-key menu-keys))
  8934. (user-error "Could not make unique key for %s." key)
  8935. (push (cons potential-key key) menu-keys))))
  8936. (mapcar #'car
  8937. (cl-sort menu-keys #'<
  8938. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8939. (defun org-insert-structure-template (type)
  8940. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8941. Select a block from `org-structure-template-alist' then type
  8942. either RET, TAB or SPC to write the block type. With an active
  8943. region, wrap the region in the block. Otherwise, insert an empty
  8944. block."
  8945. (interactive
  8946. (list (pcase (org--insert-structure-template-mks)
  8947. (`("\t" . ,_) (read-string "Structure type: "))
  8948. (`(,_ ,choice . ,_) choice))))
  8949. (let* ((region? (use-region-p))
  8950. (region-start (and region? (region-beginning)))
  8951. (region-end (and region? (copy-marker (region-end))))
  8952. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8953. (verbatim? (string-match-p
  8954. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8955. type)))
  8956. (when region? (goto-char region-start))
  8957. (let ((column (current-indentation)))
  8958. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8959. (beginning-of-line)
  8960. (insert "\n"))
  8961. (save-excursion
  8962. (indent-to column)
  8963. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8964. (when region?
  8965. (when verbatim? (org-escape-code-in-region (point) region-end))
  8966. (goto-char region-end)
  8967. ;; Ignore empty lines at the end of the region.
  8968. (skip-chars-backward " \r\t\n")
  8969. (end-of-line))
  8970. (unless (bolp) (insert "\n"))
  8971. (indent-to column)
  8972. (insert (format "#+end_%s" (car (split-string type))))
  8973. (if (looking-at "[ \t]*$") (replace-match "")
  8974. (insert "\n"))
  8975. (when (and (eobp) (not (bolp))) (insert "\n")))
  8976. (if extended? (end-of-line)
  8977. (forward-line)
  8978. (skip-chars-forward " \t")))))
  8979. ;;;; TODO, DEADLINE, Comments
  8980. (defun org-toggle-comment ()
  8981. "Change the COMMENT state of an entry."
  8982. (interactive)
  8983. (save-excursion
  8984. (org-back-to-heading)
  8985. (let ((case-fold-search nil))
  8986. (looking-at org-complex-heading-regexp))
  8987. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8988. (skip-chars-forward " \t")
  8989. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8990. (if (org-in-commented-heading-p t)
  8991. (delete-region (point)
  8992. (progn (search-forward " " (line-end-position) 'move)
  8993. (skip-chars-forward " \t")
  8994. (point)))
  8995. (insert org-comment-string)
  8996. (unless (eolp) (insert " ")))))
  8997. (defvar org-last-todo-state-is-todo nil
  8998. "This is non-nil when the last TODO state change led to a TODO state.
  8999. If the last change removed the TODO tag or switched to DONE, then
  9000. this is nil.")
  9001. (defvar org-todo-setup-filter-hook nil
  9002. "Hook for functions that pre-filter todo specs.
  9003. Each function takes a todo spec and returns either nil or the spec
  9004. transformed into canonical form." )
  9005. (defvar org-todo-get-default-hook nil
  9006. "Hook for functions that get a default item for todo.
  9007. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  9008. nil or a string to be used for the todo mark." )
  9009. (defvar org-agenda-headline-snapshot-before-repeat)
  9010. (defun org-current-effective-time ()
  9011. "Return current time adjusted for `org-extend-today-until' variable."
  9012. (let* ((ct (org-current-time))
  9013. (dct (decode-time ct))
  9014. (ct1
  9015. (cond
  9016. (org-use-last-clock-out-time-as-effective-time
  9017. (or (org-clock-get-last-clock-out-time) ct))
  9018. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  9019. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  9020. (t ct))))
  9021. ct1))
  9022. (defun org-todo-yesterday (&optional arg)
  9023. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  9024. (interactive "P")
  9025. (if (eq major-mode 'org-agenda-mode)
  9026. (apply 'org-agenda-todo-yesterday arg)
  9027. (let* ((org-use-effective-time t)
  9028. (hour (nth 2 (decode-time (org-current-time))))
  9029. (org-extend-today-until (1+ hour)))
  9030. (org-todo arg))))
  9031. (defvar org-block-entry-blocking ""
  9032. "First entry preventing the TODO state change.")
  9033. (defun org-cancel-repeater ()
  9034. "Cancel a repeater by setting its numeric value to zero."
  9035. (interactive)
  9036. (save-excursion
  9037. (org-back-to-heading t)
  9038. (let ((bound1 (point))
  9039. (bound0 (save-excursion (outline-next-heading) (point))))
  9040. (when (and (re-search-forward
  9041. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  9042. org-deadline-time-regexp "\\)\\|\\("
  9043. org-ts-regexp "\\)")
  9044. bound0 t)
  9045. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  9046. bound1 t))
  9047. (replace-match "0" t nil nil 1)))))
  9048. (defvar org-state)
  9049. (defvar org-blocked-by-checkboxes)
  9050. (defun org-todo (&optional arg)
  9051. "Change the TODO state of an item.
  9052. The state of an item is given by a keyword at the start of the heading,
  9053. like
  9054. *** TODO Write paper
  9055. *** DONE Call mom
  9056. The different keywords are specified in the variable `org-todo-keywords'.
  9057. By default the available states are \"TODO\" and \"DONE\". So, for this
  9058. example: when the item starts with TODO, it is changed to DONE.
  9059. When it starts with DONE, the DONE is removed. And when neither TODO nor
  9060. DONE are present, add TODO at the beginning of the heading.
  9061. You can set up single-character keys to fast-select the new state. See the
  9062. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  9063. With `\\[universal-argument]' prefix ARG, force logging the state change \
  9064. and take a
  9065. logging note.
  9066. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  9067. next set of TODO \
  9068. keywords (nextset).
  9069. Another way to achieve this is `S-C-<right>'.
  9070. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9071. prefix, circumvent any state blocking.
  9072. With numeric prefix arg, switch to the Nth state.
  9073. With a numeric prefix arg of 0, inhibit note taking for the change.
  9074. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  9075. When called through ELisp, arg is also interpreted in the following way:
  9076. `none' -> empty state
  9077. \"\" -> switch to empty state
  9078. `done' -> switch to DONE
  9079. `nextset' -> switch to the next set of keywords
  9080. `previousset' -> switch to the previous set of keywords
  9081. \"WAITING\" -> switch to the specified keyword, but only if it
  9082. really is a member of `org-todo-keywords'."
  9083. (interactive "P")
  9084. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9085. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9086. 'region-start-level 'region))
  9087. org-loop-over-headlines-in-active-region)
  9088. (org-map-entries
  9089. `(org-todo ,arg)
  9090. org-loop-over-headlines-in-active-region
  9091. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  9092. (when (equal arg '(16)) (setq arg 'nextset))
  9093. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  9094. (let ((org-blocker-hook org-blocker-hook)
  9095. commentp
  9096. case-fold-search)
  9097. (when (equal arg '(64))
  9098. (setq arg nil org-blocker-hook nil))
  9099. (when (and org-blocker-hook
  9100. (or org-inhibit-blocking
  9101. (org-entry-get nil "NOBLOCKING")))
  9102. (setq org-blocker-hook nil))
  9103. (save-excursion
  9104. (catch 'exit
  9105. (org-back-to-heading t)
  9106. (when (org-in-commented-heading-p t)
  9107. (org-toggle-comment)
  9108. (setq commentp t))
  9109. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  9110. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  9111. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  9112. (let* ((match-data (match-data))
  9113. (startpos (copy-marker (line-beginning-position)))
  9114. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  9115. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  9116. (org-log-done org-log-done)
  9117. (org-log-repeat org-log-repeat)
  9118. (org-todo-log-states org-todo-log-states)
  9119. (org-inhibit-logging
  9120. (if (equal arg 0)
  9121. (progn (setq arg nil) 'note) org-inhibit-logging))
  9122. (this (match-string 1))
  9123. (hl-pos (match-beginning 0))
  9124. (head (org-get-todo-sequence-head this))
  9125. (ass (assoc head org-todo-kwd-alist))
  9126. (interpret (nth 1 ass))
  9127. (done-word (nth 3 ass))
  9128. (final-done-word (nth 4 ass))
  9129. (org-last-state (or this ""))
  9130. (completion-ignore-case t)
  9131. (member (member this org-todo-keywords-1))
  9132. (tail (cdr member))
  9133. (org-state (cond
  9134. ((eq arg 'right)
  9135. ;; Next state
  9136. (if this
  9137. (if tail (car tail) nil)
  9138. (car org-todo-keywords-1)))
  9139. ((eq arg 'left)
  9140. ;; Previous state
  9141. (unless (equal member org-todo-keywords-1)
  9142. (if this
  9143. (nth (- (length org-todo-keywords-1)
  9144. (length tail) 2)
  9145. org-todo-keywords-1)
  9146. (org-last org-todo-keywords-1))))
  9147. (arg
  9148. ;; User or caller requests a specific state.
  9149. (cond
  9150. ((equal arg "") nil)
  9151. ((eq arg 'none) nil)
  9152. ((eq arg 'done) (or done-word (car org-done-keywords)))
  9153. ((eq arg 'nextset)
  9154. (or (car (cdr (member head org-todo-heads)))
  9155. (car org-todo-heads)))
  9156. ((eq arg 'previousset)
  9157. (let ((org-todo-heads (reverse org-todo-heads)))
  9158. (or (car (cdr (member head org-todo-heads)))
  9159. (car org-todo-heads))))
  9160. ((car (member arg org-todo-keywords-1)))
  9161. ((stringp arg)
  9162. (user-error "State `%s' not valid in this file" arg))
  9163. ((nth (1- (prefix-numeric-value arg))
  9164. org-todo-keywords-1))))
  9165. ((and org-todo-key-trigger org-use-fast-todo-selection)
  9166. ;; Use fast selection.
  9167. (org-fast-todo-selection this))
  9168. ((null member) (or head (car org-todo-keywords-1)))
  9169. ((equal this final-done-word) nil) ;-> make empty
  9170. ((null tail) nil) ;-> first entry
  9171. ((memq interpret '(type priority))
  9172. (if (eq this-command last-command)
  9173. (car tail)
  9174. (if (> (length tail) 0)
  9175. (or done-word (car org-done-keywords))
  9176. nil)))
  9177. (t
  9178. (car tail))))
  9179. (org-state (or
  9180. (run-hook-with-args-until-success
  9181. 'org-todo-get-default-hook org-state org-last-state)
  9182. org-state))
  9183. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  9184. (change-plist (list :type 'todo-state-change :from this :to org-state
  9185. :position startpos))
  9186. dolog now-done-p)
  9187. (when org-blocker-hook
  9188. (let (org-blocked-by-checkboxes block-reason)
  9189. (setq org-last-todo-state-is-todo
  9190. (not (member this org-done-keywords)))
  9191. (unless (save-excursion
  9192. (save-match-data
  9193. (org-with-wide-buffer
  9194. (run-hook-with-args-until-failure
  9195. 'org-blocker-hook change-plist))))
  9196. (setq block-reason (if org-blocked-by-checkboxes
  9197. "contained checkboxes"
  9198. (format "\"%s\"" org-block-entry-blocking)))
  9199. (if (called-interactively-p 'interactive)
  9200. (user-error "TODO state change from %s to %s blocked (by %s)"
  9201. this org-state block-reason)
  9202. ;; Fail silently.
  9203. (message "TODO state change from %s to %s blocked (by %s)"
  9204. this org-state block-reason)
  9205. (throw 'exit nil)))))
  9206. (store-match-data match-data)
  9207. (replace-match next t t)
  9208. (cond ((and org-state (equal this org-state))
  9209. (message "TODO state was already %s" (org-trim next)))
  9210. ((not (pos-visible-in-window-p hl-pos))
  9211. (message "TODO state changed to %s" (org-trim next))))
  9212. (unless head
  9213. (setq head (org-get-todo-sequence-head org-state)
  9214. ass (assoc head org-todo-kwd-alist)
  9215. interpret (nth 1 ass)
  9216. done-word (nth 3 ass)
  9217. final-done-word (nth 4 ass)))
  9218. (when (memq arg '(nextset previousset))
  9219. (message "Keyword-Set %d/%d: %s"
  9220. (- (length org-todo-sets) -1
  9221. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  9222. (length org-todo-sets)
  9223. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  9224. (setq org-last-todo-state-is-todo
  9225. (not (member org-state org-done-keywords)))
  9226. (setq now-done-p (and (member org-state org-done-keywords)
  9227. (not (member this org-done-keywords))))
  9228. (and logging (org-local-logging logging))
  9229. (when (or (and (or org-todo-log-states org-log-done)
  9230. (not (eq org-inhibit-logging t))
  9231. (not (memq arg '(nextset previousset))))
  9232. force-log)
  9233. ;; We need to look at recording a time and note.
  9234. (setq dolog (or (if force-log 'note)
  9235. (nth 1 (assoc org-state org-todo-log-states))
  9236. (nth 2 (assoc this org-todo-log-states))))
  9237. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  9238. (setq dolog 'time))
  9239. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  9240. (and org-state
  9241. (member org-state org-not-done-keywords)
  9242. (not (member this org-not-done-keywords))))
  9243. ;; This is now a todo state and was not one before
  9244. ;; If there was a CLOSED time stamp, get rid of it.
  9245. (org-add-planning-info nil nil 'closed))
  9246. (when (and now-done-p org-log-done)
  9247. ;; It is now done, and it was not done before.
  9248. (org-add-planning-info 'closed (org-current-effective-time))
  9249. (when (and (not dolog) (eq 'note org-log-done))
  9250. (org-add-log-setup 'done org-state this 'note)))
  9251. (when (and org-state dolog)
  9252. ;; This is a non-nil state, and we need to log it.
  9253. (org-add-log-setup 'state org-state this dolog)))
  9254. ;; Fixup tag positioning.
  9255. (org-todo-trigger-tag-changes org-state)
  9256. (when org-auto-align-tags (org-align-tags))
  9257. (when org-provide-todo-statistics
  9258. (org-update-parent-todo-statistics))
  9259. (when (bound-and-true-p org-clock-out-when-done)
  9260. (org-clock-out-if-current))
  9261. (run-hooks 'org-after-todo-state-change-hook)
  9262. (when (and arg (not (member org-state org-done-keywords)))
  9263. (setq head (org-get-todo-sequence-head org-state)))
  9264. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  9265. ;; Do we need to trigger a repeat?
  9266. (when now-done-p
  9267. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  9268. ;; This is for the agenda, take a snapshot of the headline.
  9269. (save-match-data
  9270. (setq org-agenda-headline-snapshot-before-repeat
  9271. (org-get-heading))))
  9272. (org-auto-repeat-maybe org-state))
  9273. ;; Fixup cursor location if close to the keyword.
  9274. (when (and (outline-on-heading-p)
  9275. (not (bolp))
  9276. (save-excursion (beginning-of-line 1)
  9277. (looking-at org-todo-line-regexp))
  9278. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  9279. (goto-char (or (match-end 2) (match-end 1)))
  9280. (and (looking-at " ")
  9281. (not (looking-at " *:"))
  9282. (just-one-space)))
  9283. (when org-trigger-hook
  9284. (save-excursion
  9285. (run-hook-with-args 'org-trigger-hook change-plist)))
  9286. (when commentp (org-toggle-comment))))))))
  9287. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  9288. "Block turning an entry into a TODO, using the hierarchy.
  9289. This checks whether the current task should be blocked from state
  9290. changes. Such blocking occurs when:
  9291. 1. The task has children which are not all in a completed state.
  9292. 2. A task has a parent with the property :ORDERED:, and there
  9293. are siblings prior to the current task with incomplete
  9294. status.
  9295. 3. The parent of the task is blocked because it has siblings that should
  9296. be done first, or is child of a block grandparent TODO entry."
  9297. (if (not org-enforce-todo-dependencies)
  9298. t ; if locally turned off don't block
  9299. (catch 'dont-block
  9300. ;; If this is not a todo state change, or if this entry is already DONE,
  9301. ;; do not block
  9302. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9303. (member (plist-get change-plist :from)
  9304. (cons 'done org-done-keywords))
  9305. (member (plist-get change-plist :to)
  9306. (cons 'todo org-not-done-keywords))
  9307. (not (plist-get change-plist :to)))
  9308. (throw 'dont-block t))
  9309. ;; If this task has children, and any are undone, it's blocked
  9310. (save-excursion
  9311. (org-back-to-heading t)
  9312. (let ((this-level (funcall outline-level)))
  9313. (outline-next-heading)
  9314. (let ((child-level (funcall outline-level)))
  9315. (while (and (not (eobp))
  9316. (> child-level this-level))
  9317. ;; this todo has children, check whether they are all
  9318. ;; completed
  9319. (when (and (not (org-entry-is-done-p))
  9320. (org-entry-is-todo-p))
  9321. (setq org-block-entry-blocking (org-get-heading))
  9322. (throw 'dont-block nil))
  9323. (outline-next-heading)
  9324. (setq child-level (funcall outline-level))))))
  9325. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  9326. ;; any previous siblings are undone, it's blocked
  9327. (save-excursion
  9328. (org-back-to-heading t)
  9329. (let* ((pos (point))
  9330. (parent-pos (and (org-up-heading-safe) (point)))
  9331. (case-fold-search nil))
  9332. (unless parent-pos (throw 'dont-block t)) ; no parent
  9333. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9334. (forward-line 1)
  9335. (re-search-forward org-not-done-heading-regexp pos t))
  9336. (setq org-block-entry-blocking (match-string 0))
  9337. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  9338. ;; Search further up the hierarchy, to see if an ancestor is blocked
  9339. (while t
  9340. (goto-char parent-pos)
  9341. (unless (looking-at org-not-done-heading-regexp)
  9342. (throw 'dont-block t)) ; do not block, parent is not a TODO
  9343. (setq pos (point))
  9344. (setq parent-pos (and (org-up-heading-safe) (point)))
  9345. (unless parent-pos (throw 'dont-block t)) ; no parent
  9346. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9347. (forward-line 1)
  9348. (re-search-forward org-not-done-heading-regexp pos t)
  9349. (setq org-block-entry-blocking (org-get-heading)))
  9350. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  9351. (defcustom org-track-ordered-property-with-tag nil
  9352. "Should the ORDERED property also be shown as a tag?
  9353. The ORDERED property decides if an entry should require subtasks to be
  9354. completed in sequence. Since a property is not very visible, setting
  9355. this option means that toggling the ORDERED property with the command
  9356. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  9357. not relevant for the behavior, but it makes things more visible.
  9358. Note that toggling the tag with tags commands will not change the property
  9359. and therefore not influence behavior!
  9360. This can be t, meaning the tag ORDERED should be used. It can also be a
  9361. string to select a different tag for this task."
  9362. :group 'org-todo
  9363. :type '(choice
  9364. (const :tag "No tracking" nil)
  9365. (const :tag "Track with ORDERED tag" t)
  9366. (string :tag "Use other tag")))
  9367. (defun org-toggle-ordered-property ()
  9368. "Toggle the ORDERED property of the current entry.
  9369. For better visibility, you can track the value of this property with a tag.
  9370. See variable `org-track-ordered-property-with-tag'."
  9371. (interactive)
  9372. (let* ((t1 org-track-ordered-property-with-tag)
  9373. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  9374. (save-excursion
  9375. (org-back-to-heading)
  9376. (if (org-entry-get nil "ORDERED")
  9377. (progn
  9378. (org-delete-property "ORDERED")
  9379. (and tag (org-toggle-tag tag 'off))
  9380. (message "Subtasks can be completed in arbitrary order"))
  9381. (org-entry-put nil "ORDERED" "t")
  9382. (and tag (org-toggle-tag tag 'on))
  9383. (message "Subtasks must be completed in sequence")))))
  9384. (defun org-block-todo-from-checkboxes (change-plist)
  9385. "Block turning an entry into a TODO, using checkboxes.
  9386. This checks whether the current task should be blocked from state
  9387. changes because there are unchecked boxes in this entry."
  9388. (if (not org-enforce-todo-checkbox-dependencies)
  9389. t ; if locally turned off don't block
  9390. (catch 'dont-block
  9391. ;; If this is not a todo state change, or if this entry is already DONE,
  9392. ;; do not block
  9393. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9394. (member (plist-get change-plist :from)
  9395. (cons 'done org-done-keywords))
  9396. (member (plist-get change-plist :to)
  9397. (cons 'todo org-not-done-keywords))
  9398. (not (plist-get change-plist :to)))
  9399. (throw 'dont-block t))
  9400. ;; If this task has checkboxes that are not checked, it's blocked
  9401. (save-excursion
  9402. (org-back-to-heading t)
  9403. (let ((beg (point)) end)
  9404. (outline-next-heading)
  9405. (setq end (point))
  9406. (goto-char beg)
  9407. (when (org-list-search-forward
  9408. (concat (org-item-beginning-re)
  9409. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  9410. "\\[[- ]\\]")
  9411. end t)
  9412. (when (boundp 'org-blocked-by-checkboxes)
  9413. (setq org-blocked-by-checkboxes t))
  9414. (throw 'dont-block nil))))
  9415. t))) ; do not block
  9416. (defun org-entry-blocked-p ()
  9417. "Non-nil if entry at point is blocked."
  9418. (and (not (org-entry-get nil "NOBLOCKING"))
  9419. (member (org-entry-get nil "TODO") org-not-done-keywords)
  9420. (not (run-hook-with-args-until-failure
  9421. 'org-blocker-hook
  9422. (list :type 'todo-state-change
  9423. :position (point)
  9424. :from 'todo
  9425. :to 'done)))))
  9426. (defun org-update-statistics-cookies (all)
  9427. "Update the statistics cookie, either from TODO or from checkboxes.
  9428. This should be called with the cursor in a line with a statistics
  9429. cookie. When called with a \\[universal-argument] prefix, update
  9430. all statistics cookies in the buffer."
  9431. (interactive "P")
  9432. (if all
  9433. (progn
  9434. (org-update-checkbox-count 'all)
  9435. (org-map-entries 'org-update-parent-todo-statistics))
  9436. (if (not (org-at-heading-p))
  9437. (org-update-checkbox-count)
  9438. (let ((pos (point-marker))
  9439. end l1 l2)
  9440. (ignore-errors (org-back-to-heading t))
  9441. (if (not (org-at-heading-p))
  9442. (org-update-checkbox-count)
  9443. (setq l1 (org-outline-level))
  9444. (setq end (save-excursion
  9445. (outline-next-heading)
  9446. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  9447. (point)))
  9448. (if (and (save-excursion
  9449. (re-search-forward
  9450. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  9451. (not (save-excursion (re-search-forward
  9452. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  9453. (org-update-checkbox-count)
  9454. (if (and l2 (> l2 l1))
  9455. (progn
  9456. (goto-char end)
  9457. (org-update-parent-todo-statistics))
  9458. (goto-char pos)
  9459. (beginning-of-line 1)
  9460. (while (re-search-forward
  9461. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  9462. (point-at-eol) t)
  9463. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  9464. (goto-char pos)
  9465. (move-marker pos nil)))))
  9466. (defvar org-entry-property-inherited-from) ;; defined below
  9467. (defun org-update-parent-todo-statistics ()
  9468. "Update any statistics cookie in the parent of the current headline.
  9469. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  9470. the entire subtree and this will travel up the hierarchy and update
  9471. statistics everywhere."
  9472. (let* ((prop (save-excursion (org-up-heading-safe)
  9473. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  9474. (recursive (or (not org-hierarchical-todo-statistics)
  9475. (and prop (string-match "\\<recursive\\>" prop))))
  9476. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  9477. 0))
  9478. (first t)
  9479. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  9480. level ltoggle l1 new ndel
  9481. (cnt-all 0) (cnt-done 0) is-percent kwd
  9482. checkbox-beg cookie-present)
  9483. (catch 'exit
  9484. (save-excursion
  9485. (beginning-of-line 1)
  9486. (setq ltoggle (funcall outline-level))
  9487. ;; Three situations are to consider:
  9488. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  9489. ;; to the top-level ancestor on the headline;
  9490. ;; 2. If parent has "recursive" property, repeat up to the
  9491. ;; headline setting that property, taking inheritance into
  9492. ;; account;
  9493. ;; 3. Else, move up to direct parent and proceed only once.
  9494. (while (and (setq level (org-up-heading-safe))
  9495. (or recursive first)
  9496. (>= (point) lim))
  9497. (setq first nil cookie-present nil)
  9498. (unless (and level
  9499. (not (string-match
  9500. "\\<checkbox\\>"
  9501. (downcase (or (org-entry-get nil "COOKIE_DATA")
  9502. "")))))
  9503. (throw 'exit nil))
  9504. (while (re-search-forward box-re (point-at-eol) t)
  9505. (setq cnt-all 0 cnt-done 0 cookie-present t)
  9506. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  9507. (save-match-data
  9508. (unless (outline-next-heading) (throw 'exit nil))
  9509. (while (and (looking-at org-complex-heading-regexp)
  9510. (> (setq l1 (length (match-string 1))) level))
  9511. (setq kwd (and (or recursive (= l1 ltoggle))
  9512. (match-string 2)))
  9513. (if (or (eq org-provide-todo-statistics 'all-headlines)
  9514. (and (eq org-provide-todo-statistics t)
  9515. (or (member kwd org-done-keywords)))
  9516. (and (listp org-provide-todo-statistics)
  9517. (stringp (car org-provide-todo-statistics))
  9518. (or (member kwd org-provide-todo-statistics)
  9519. (member kwd org-done-keywords)))
  9520. (and (listp org-provide-todo-statistics)
  9521. (listp (car org-provide-todo-statistics))
  9522. (or (member kwd (car org-provide-todo-statistics))
  9523. (and (member kwd org-done-keywords)
  9524. (member kwd (cadr org-provide-todo-statistics))))))
  9525. (setq cnt-all (1+ cnt-all))
  9526. (and (eq org-provide-todo-statistics t)
  9527. kwd
  9528. (setq cnt-all (1+ cnt-all))))
  9529. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  9530. (member kwd org-done-keywords))
  9531. (and (listp org-provide-todo-statistics)
  9532. (listp (car org-provide-todo-statistics))
  9533. (member kwd org-done-keywords)
  9534. (member kwd (cadr org-provide-todo-statistics)))
  9535. (and (listp org-provide-todo-statistics)
  9536. (stringp (car org-provide-todo-statistics))
  9537. (member kwd org-done-keywords)))
  9538. (setq cnt-done (1+ cnt-done)))
  9539. (outline-next-heading)))
  9540. (setq new
  9541. (if is-percent
  9542. (format "[%d%%]" (floor (* 100.0 cnt-done)
  9543. (max 1 cnt-all)))
  9544. (format "[%d/%d]" cnt-done cnt-all))
  9545. ndel (- (match-end 0) checkbox-beg))
  9546. (goto-char checkbox-beg)
  9547. (insert new)
  9548. (delete-region (point) (+ (point) ndel))
  9549. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  9550. (when cookie-present
  9551. (run-hook-with-args 'org-after-todo-statistics-hook
  9552. cnt-done (- cnt-all cnt-done))))))
  9553. (run-hooks 'org-todo-statistics-hook)))
  9554. (defvar org-after-todo-statistics-hook nil
  9555. "Hook that is called after a TODO statistics cookie has been updated.
  9556. Each function is called with two arguments: the number of not-done entries
  9557. and the number of done entries.
  9558. For example, the following function, when added to this hook, will switch
  9559. an entry to DONE when all children are done, and back to TODO when new
  9560. entries are set to a TODO status. Note that this hook is only called
  9561. when there is a statistics cookie in the headline!
  9562. (defun org-summary-todo (n-done n-not-done)
  9563. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9564. (let (org-log-done org-log-states) ; turn off logging
  9565. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  9566. ")
  9567. (defvar org-todo-statistics-hook nil
  9568. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9569. This hook runs even if there is no statistics cookie present, in which case
  9570. `org-after-todo-statistics-hook' would not run.")
  9571. (defun org-todo-trigger-tag-changes (state)
  9572. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9573. (let ((l org-todo-state-tags-triggers)
  9574. changes)
  9575. (when (or (not state) (equal state ""))
  9576. (setq changes (append changes (cdr (assoc "" l)))))
  9577. (when (and (stringp state) (> (length state) 0))
  9578. (setq changes (append changes (cdr (assoc state l)))))
  9579. (when (member state org-not-done-keywords)
  9580. (setq changes (append changes (cdr (assq 'todo l)))))
  9581. (when (member state org-done-keywords)
  9582. (setq changes (append changes (cdr (assq 'done l)))))
  9583. (dolist (c changes)
  9584. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9585. (defun org-local-logging (value)
  9586. "Get logging settings from a property VALUE."
  9587. ;; Directly set the variables, they are already local.
  9588. (setq org-log-done nil
  9589. org-log-repeat nil
  9590. org-todo-log-states nil)
  9591. (dolist (w (split-string value))
  9592. (let (a)
  9593. (cond
  9594. ((setq a (assoc w org-startup-options))
  9595. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9596. (set (nth 1 a) (nth 2 a))))
  9597. ((setq a (org-extract-log-state-settings w))
  9598. (and (member (car a) org-todo-keywords-1)
  9599. (push a org-todo-log-states)))))))
  9600. (defun org-get-todo-sequence-head (kwd)
  9601. "Return the head of the TODO sequence to which KWD belongs.
  9602. If KWD is not set, check if there is a text property remembering the
  9603. right sequence."
  9604. (let (p)
  9605. (cond
  9606. ((not kwd)
  9607. (or (get-text-property (point-at-bol) 'org-todo-head)
  9608. (progn
  9609. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9610. nil (point-at-eol)))
  9611. (get-text-property p 'org-todo-head))))
  9612. ((not (member kwd org-todo-keywords-1))
  9613. (car org-todo-keywords-1))
  9614. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9615. (defun org-fast-todo-selection (&optional current-state)
  9616. "Fast TODO keyword selection with single keys.
  9617. Returns the new TODO keyword, or nil if no state change should occur.
  9618. When CURRENT-STATE is given and selection letters are not unique globally,
  9619. prefer a state in the current sequence over on in another sequence."
  9620. (let* ((fulltable org-todo-key-alist)
  9621. (head (org-get-todo-sequence-head current-state))
  9622. (done-keywords org-done-keywords) ;; needed for the faces.
  9623. (maxlen (apply 'max (mapcar
  9624. (lambda (x)
  9625. (if (stringp (car x)) (string-width (car x)) 0))
  9626. fulltable)))
  9627. (expert (equal org-use-fast-todo-selection 'expert))
  9628. (prompt "")
  9629. (fwidth (+ maxlen 3 1 3))
  9630. (ncol (/ (- (window-width) 4) fwidth))
  9631. tg cnt e c tbl subtable
  9632. groups ingroup in-current-sequence)
  9633. (save-excursion
  9634. (save-window-excursion
  9635. (if expert
  9636. (set-buffer (get-buffer-create " *Org todo*"))
  9637. (delete-other-windows)
  9638. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9639. (org-switch-to-buffer-other-window " *Org todo*"))
  9640. (erase-buffer)
  9641. (setq-local org-done-keywords done-keywords)
  9642. (setq tbl fulltable cnt 0)
  9643. (while (setq e (pop tbl))
  9644. (cond
  9645. ((equal e '(:startgroup))
  9646. (push '() groups) (setq ingroup t)
  9647. (unless (= cnt 0)
  9648. (setq cnt 0)
  9649. (insert "\n"))
  9650. (setq prompt (concat prompt "{"))
  9651. (insert "{ "))
  9652. ((equal e '(:endgroup))
  9653. (setq ingroup nil cnt 0 in-current-sequence nil)
  9654. (setq prompt (concat prompt "}"))
  9655. (insert "}\n"))
  9656. ((equal e '(:newline))
  9657. (unless (= cnt 0)
  9658. (setq cnt 0)
  9659. (insert "\n")
  9660. (setq e (car tbl))
  9661. (while (equal (car tbl) '(:newline))
  9662. (insert "\n")
  9663. (setq tbl (cdr tbl)))))
  9664. (t
  9665. (setq tg (car e) c (cdr e))
  9666. (if (equal tg head) (setq in-current-sequence t))
  9667. (when ingroup (push tg (car groups)))
  9668. (when in-current-sequence (push e subtable))
  9669. (setq tg (org-add-props tg nil 'face
  9670. (org-get-todo-face tg)))
  9671. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9672. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9673. (insert "[" c "] " tg (make-string
  9674. (- fwidth 4 (length tg)) ?\ ))
  9675. (when (and (= (setq cnt (1+ cnt)) ncol)
  9676. ;; Avoid lines with just a closing delimiter.
  9677. (not (equal (car tbl) '(:endgroup))))
  9678. (insert "\n")
  9679. (when ingroup (insert " "))
  9680. (setq cnt 0)))))
  9681. (insert "\n")
  9682. (goto-char (point-min))
  9683. (unless expert (org-fit-window-to-buffer))
  9684. (message (concat "[a-z..]:Set [SPC]:clear"
  9685. (if expert (concat "\n" prompt) "")))
  9686. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9687. (setq subtable (nreverse subtable))
  9688. (cond
  9689. ((or (= c ?\C-g)
  9690. (and (= c ?q) (not (rassoc c fulltable))))
  9691. (setq quit-flag t))
  9692. ((= c ?\ ) nil)
  9693. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9694. tg (car e))
  9695. tg)
  9696. (t (setq quit-flag t)))))))
  9697. (defun org-entry-is-todo-p ()
  9698. (member (org-get-todo-state) org-not-done-keywords))
  9699. (defun org-entry-is-done-p ()
  9700. (member (org-get-todo-state) org-done-keywords))
  9701. (defun org-get-todo-state ()
  9702. "Return the TODO keyword of the current subtree."
  9703. (save-excursion
  9704. (org-back-to-heading t)
  9705. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9706. (match-end 2)
  9707. (match-string 2))))
  9708. (defun org-at-date-range-p (&optional inactive-ok)
  9709. "Non-nil if point is inside a date range.
  9710. When optional argument INACTIVE-OK is non-nil, also consider
  9711. inactive time ranges.
  9712. When this function returns a non-nil value, match data is set
  9713. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9714. on INACTIVE-OK."
  9715. (interactive)
  9716. (save-excursion
  9717. (catch 'exit
  9718. (let ((pos (point)))
  9719. (skip-chars-backward "^[<\r\n")
  9720. (skip-chars-backward "<[")
  9721. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9722. (>= (match-end 0) pos)
  9723. (throw 'exit t))
  9724. (skip-chars-backward "^<[\r\n")
  9725. (skip-chars-backward "<[")
  9726. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9727. (>= (match-end 0) pos)
  9728. (throw 'exit t)))
  9729. nil)))
  9730. (defun org-get-repeat (&optional timestamp)
  9731. "Check if there is a time-stamp with repeater in this entry.
  9732. Return the repeater, as a string, or nil. Also return nil when
  9733. this function is called before first heading.
  9734. When optional argument TIMESTAMP is a string, extract the
  9735. repeater from there instead."
  9736. (save-match-data
  9737. (cond (timestamp
  9738. (and (string-match org-repeat-re timestamp)
  9739. (match-string-no-properties 1 timestamp)))
  9740. ((org-before-first-heading-p) nil)
  9741. (t
  9742. (save-excursion
  9743. (org-back-to-heading t)
  9744. (let ((end (org-entry-end-position)))
  9745. (catch :repeat
  9746. (while (re-search-forward org-repeat-re end t)
  9747. (when (save-match-data (org-at-timestamp-p 'agenda))
  9748. (throw :repeat (match-string-no-properties 1)))))))))))
  9749. (defvar org-last-changed-timestamp)
  9750. (defvar org-last-inserted-timestamp)
  9751. (defvar org-log-post-message)
  9752. (defvar org-log-note-purpose)
  9753. (defvar org-log-note-how nil)
  9754. (defvar org-log-note-extra)
  9755. (defun org-auto-repeat-maybe (done-word)
  9756. "Check if the current headline contains a repeated time-stamp.
  9757. If yes, set TODO state back to what it was and change the base date
  9758. of repeating deadline/scheduled time stamps to new date.
  9759. This function is run automatically after each state change to a DONE state."
  9760. (let* ((repeat (org-get-repeat))
  9761. (aa (assoc org-last-state org-todo-kwd-alist))
  9762. (interpret (nth 1 aa))
  9763. (head (nth 2 aa))
  9764. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9765. (msg "Entry repeats: ")
  9766. (org-log-done nil)
  9767. (org-todo-log-states nil)
  9768. (end (copy-marker (org-entry-end-position))))
  9769. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9770. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9771. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9772. (and (stringp org-todo-repeat-to-state)
  9773. org-todo-repeat-to-state)
  9774. (and org-todo-repeat-to-state org-last-state))))
  9775. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9776. to-state)
  9777. ((eq interpret 'type) org-last-state)
  9778. (head)
  9779. (t 'none))))
  9780. (org-back-to-heading t)
  9781. (org-add-planning-info nil nil 'closed)
  9782. ;; When `org-log-repeat' is non-nil or entry contains
  9783. ;; a clock, set LAST_REPEAT property.
  9784. (when (or org-log-repeat
  9785. (catch :clock
  9786. (save-excursion
  9787. (while (re-search-forward org-clock-line-re end t)
  9788. (when (org-at-clock-log-p) (throw :clock t))))))
  9789. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9790. (org-time-stamp-format t t))))
  9791. (when org-log-repeat
  9792. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  9793. (memq 'org-add-log-note post-command-hook))
  9794. ;; We are already setup for some record.
  9795. (when (eq org-log-repeat 'note)
  9796. ;; Make sure we take a note, not only a time stamp.
  9797. (setq org-log-note-how 'note))
  9798. ;; Set up for taking a record.
  9799. (org-add-log-setup 'state
  9800. (or done-word (car org-done-keywords))
  9801. org-last-state
  9802. org-log-repeat)))
  9803. ;; Time-stamps without a repeater are usually skipped. However,
  9804. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9805. ;; longer relevant.
  9806. (save-excursion
  9807. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9808. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9809. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9810. ;; Update every time-stamp with a repeater in the entry.
  9811. (let ((planning-re (regexp-opt
  9812. (list org-scheduled-string org-deadline-string))))
  9813. (while (re-search-forward org-repeat-re end t)
  9814. (let* ((ts (match-string 0))
  9815. (type (if (not (org-at-planning-p)) "Plain:"
  9816. (save-excursion
  9817. (re-search-backward
  9818. planning-re (line-beginning-position) t)
  9819. (match-string 0)))))
  9820. (when (and (org-at-timestamp-p 'agenda)
  9821. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9822. (let ((n (string-to-number (match-string 2 ts)))
  9823. (what (match-string 3 ts)))
  9824. (when (equal what "w") (setq n (* n 7) what "d"))
  9825. (when (and (equal what "h")
  9826. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9827. ts)))
  9828. (user-error
  9829. "Cannot repeat in %d hour(s) because no hour has been set"
  9830. n))
  9831. ;; Preparation, see if we need to modify the start
  9832. ;; date for the change.
  9833. (when (match-end 1)
  9834. (let ((time (save-match-data (org-time-string-to-time ts)))
  9835. (repeater-type (match-string 1 ts)))
  9836. (cond
  9837. ((equal "." repeater-type)
  9838. ;; Shift starting date to today.
  9839. (org-timestamp-change (- (org-today) (time-to-days time))
  9840. 'day))
  9841. ((equal "+" repeater-type)
  9842. (let ((nshiftmax 10)
  9843. (nshift 0))
  9844. (while (or (= nshift 0)
  9845. (not (org-time-less-p nil time)))
  9846. (when (= nshiftmax (cl-incf nshift))
  9847. (or (y-or-n-p
  9848. (format "%d repeater intervals were not \
  9849. enough to shift date past today. Continue? "
  9850. nshift))
  9851. (user-error "Abort")))
  9852. (org-timestamp-change n (cdr (assoc what whata)))
  9853. (org-in-regexp org-ts-regexp3)
  9854. (setq ts (match-string 1))
  9855. (setq time
  9856. (save-match-data
  9857. (org-time-string-to-time ts)))))
  9858. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9859. ;; Rematch, so that we have everything in place
  9860. ;; for the real shift.
  9861. (org-in-regexp org-ts-regexp3)
  9862. (setq ts (match-string 1))
  9863. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9864. ts)))))
  9865. (save-excursion
  9866. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9867. (setq msg
  9868. (concat msg type " " org-last-changed-timestamp " ")))))))
  9869. (run-hooks 'org-todo-repeat-hook)
  9870. (setq org-log-post-message msg)
  9871. (message msg))))
  9872. (defun org-show-todo-tree (arg)
  9873. "Make a compact tree which shows all headlines marked with TODO.
  9874. The tree will show the lines where the regexp matches, and all higher
  9875. headlines above the match.
  9876. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9877. With a numeric prefix N, construct a sparse tree for the Nth element
  9878. of `org-todo-keywords-1'."
  9879. (interactive "P")
  9880. (let ((case-fold-search nil)
  9881. (kwd-re
  9882. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9883. ((equal arg '(4))
  9884. (let ((kwd
  9885. (completing-read "Keyword (or KWD1|KWD2|...): "
  9886. (mapcar #'list org-todo-keywords-1))))
  9887. (concat "\\("
  9888. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9889. "\\)\\>")))
  9890. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9891. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9892. org-todo-keywords-1)))
  9893. (t (user-error "Invalid prefix argument: %s" arg)))))
  9894. (message "%d TODO entries found"
  9895. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9896. (defun org--deadline-or-schedule (arg type time)
  9897. "Insert DEADLINE or SCHEDULE information in current entry.
  9898. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9899. `org-schedule' for information about ARG and TIME arguments."
  9900. (let* ((deadline? (eq type 'deadline))
  9901. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9902. (log (if deadline? org-log-redeadline org-log-reschedule))
  9903. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9904. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9905. ;; Save repeater cookie from either TIME or current scheduled
  9906. ;; time stamp. We are going to insert it back at the end of
  9907. ;; the process.
  9908. (repeater (or (and (org-string-nw-p time)
  9909. ;; We use `org-repeat-re' because we need
  9910. ;; to tell the difference between a real
  9911. ;; repeater and a time delta, e.g. "+2d".
  9912. (string-match org-repeat-re time)
  9913. (match-string 1 time))
  9914. (and (org-string-nw-p old-date)
  9915. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9916. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9917. old-date)
  9918. (match-string 1 old-date)))))
  9919. (pcase arg
  9920. (`(4)
  9921. (if (not old-date)
  9922. (message (if deadline? "Entry had no deadline to remove"
  9923. "Entry was not scheduled"))
  9924. (when (and old-date log)
  9925. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9926. nil old-date log))
  9927. (org-remove-timestamp-with-keyword keyword)
  9928. (message (if deadline? "Entry no longer has a deadline."
  9929. "Entry is no longer scheduled."))))
  9930. (`(16)
  9931. (save-excursion
  9932. (org-back-to-heading t)
  9933. (let ((regexp (if deadline? org-deadline-time-regexp
  9934. org-scheduled-time-regexp)))
  9935. (if (not (re-search-forward regexp (line-end-position 2) t))
  9936. (user-error (if deadline? "No deadline information to update"
  9937. "No scheduled information to update"))
  9938. (let* ((rpl0 (match-string 1))
  9939. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9940. (msg (if deadline? "Warn starting from" "Delay until")))
  9941. (replace-match
  9942. (concat keyword
  9943. " <" rpl
  9944. (format " -%dd"
  9945. (abs (- (time-to-days
  9946. (save-match-data
  9947. (org-read-date
  9948. nil t nil msg old-date-time)))
  9949. (time-to-days old-date-time))))
  9950. ">") t t))))))
  9951. (_
  9952. (org-add-planning-info type time 'closed)
  9953. (when (and old-date
  9954. log
  9955. (not (equal old-date org-last-inserted-timestamp)))
  9956. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9957. org-last-inserted-timestamp
  9958. old-date
  9959. log))
  9960. (when repeater
  9961. (save-excursion
  9962. (org-back-to-heading t)
  9963. (when (re-search-forward
  9964. (concat keyword " " org-last-inserted-timestamp)
  9965. (line-end-position 2)
  9966. t)
  9967. (goto-char (1- (match-end 0)))
  9968. (insert " " repeater)
  9969. (setq org-last-inserted-timestamp
  9970. (concat (substring org-last-inserted-timestamp 0 -1)
  9971. " " repeater
  9972. (substring org-last-inserted-timestamp -1))))))
  9973. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9974. org-last-inserted-timestamp)))))
  9975. (defun org-deadline (arg &optional time)
  9976. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  9977. With one universal prefix argument, remove any deadline from the item.
  9978. With two universal prefix arguments, prompt for a warning delay.
  9979. With argument TIME, set the deadline at the corresponding date. TIME
  9980. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9981. (interactive "P")
  9982. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9983. (org-map-entries
  9984. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9985. nil
  9986. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9987. 'region-start-level
  9988. 'region)
  9989. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9990. (org--deadline-or-schedule arg 'deadline time)))
  9991. (defun org-schedule (arg &optional time)
  9992. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  9993. With one universal prefix argument, remove any scheduling date from the item.
  9994. With two universal prefix arguments, prompt for a delay cookie.
  9995. With argument TIME, scheduled at the corresponding date. TIME can
  9996. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9997. (interactive "P")
  9998. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9999. (org-map-entries
  10000. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  10001. nil
  10002. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10003. 'region-start-level
  10004. 'region)
  10005. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  10006. (org--deadline-or-schedule arg 'scheduled time)))
  10007. (defun org-get-scheduled-time (pom &optional inherit)
  10008. "Get the scheduled time as a time tuple, of a format suitable
  10009. for calling org-schedule with, or if there is no scheduling,
  10010. returns nil."
  10011. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  10012. (when time
  10013. (org-time-string-to-time time))))
  10014. (defun org-get-deadline-time (pom &optional inherit)
  10015. "Get the deadline as a time tuple, of a format suitable for
  10016. calling org-deadline with, or if there is no scheduling, returns
  10017. nil."
  10018. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  10019. (when time
  10020. (org-time-string-to-time time))))
  10021. (defun org-remove-timestamp-with-keyword (keyword)
  10022. "Remove all time stamps with KEYWORD in the current entry."
  10023. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  10024. beg)
  10025. (save-excursion
  10026. (org-back-to-heading t)
  10027. (setq beg (point))
  10028. (outline-next-heading)
  10029. (while (re-search-backward re beg t)
  10030. (replace-match "")
  10031. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  10032. (equal (char-before) ?\ ))
  10033. (backward-delete-char 1)
  10034. (when (string-match "^[ \t]*$" (buffer-substring
  10035. (point-at-bol) (point-at-eol)))
  10036. (delete-region (point-at-bol)
  10037. (min (point-max) (1+ (point-at-eol))))))))))
  10038. (defvar org-time-was-given) ; dynamically scoped parameter
  10039. (defvar org-end-time-was-given) ; dynamically scoped parameter
  10040. (defun org-at-planning-p ()
  10041. "Non-nil when point is on a planning info line."
  10042. ;; This is as accurate and faster than `org-element-at-point' since
  10043. ;; planning info location is fixed in the section.
  10044. (org-with-wide-buffer
  10045. (beginning-of-line)
  10046. (and (looking-at-p org-planning-line-re)
  10047. (eq (point)
  10048. (ignore-errors
  10049. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  10050. (org-back-to-heading t)
  10051. (org-with-limited-levels (org-back-to-heading t)))
  10052. (line-beginning-position 2))))))
  10053. (defun org-add-planning-info (what &optional time &rest remove)
  10054. "Insert new timestamp with keyword in the planning line.
  10055. WHAT indicates what kind of time stamp to add. It is a symbol
  10056. among `closed', `deadline', `scheduled' and nil. TIME indicates
  10057. the time to use. If none is given, the user is prompted for
  10058. a date. REMOVE indicates what kind of entries to remove. An old
  10059. WHAT entry will also be removed."
  10060. (let (org-time-was-given org-end-time-was-given default-time default-input)
  10061. (catch 'exit
  10062. (when (and (memq what '(scheduled deadline))
  10063. (or (not time)
  10064. (and (stringp time)
  10065. (string-match "^[-+]+[0-9]" time))))
  10066. ;; Try to get a default date/time from existing timestamp
  10067. (save-excursion
  10068. (org-back-to-heading t)
  10069. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  10070. (when (re-search-forward (if (eq what 'scheduled)
  10071. org-scheduled-time-regexp
  10072. org-deadline-time-regexp)
  10073. end t)
  10074. (setq ts (match-string 1)
  10075. default-time (org-time-string-to-time ts)
  10076. default-input (and ts (org-get-compact-tod ts)))))))
  10077. (when what
  10078. (setq time
  10079. (if (stringp time)
  10080. ;; This is a string (relative or absolute), set
  10081. ;; proper date.
  10082. (apply #'encode-time
  10083. (org-read-date-analyze
  10084. time default-time (decode-time default-time)))
  10085. ;; If necessary, get the time from the user
  10086. (or time (org-read-date nil 'to-time nil
  10087. (cl-case what
  10088. (deadline "DEADLINE")
  10089. (scheduled "SCHEDULED")
  10090. (otherwise nil))
  10091. default-time default-input)))))
  10092. (org-with-wide-buffer
  10093. (org-back-to-heading t)
  10094. (forward-line)
  10095. (unless (bolp) (insert "\n"))
  10096. (cond ((looking-at-p org-planning-line-re)
  10097. ;; Move to current indentation.
  10098. (skip-chars-forward " \t")
  10099. ;; Check if we have to remove something.
  10100. (dolist (type (if what (cons what remove) remove))
  10101. (save-excursion
  10102. (when (re-search-forward
  10103. (cl-case type
  10104. (closed org-closed-time-regexp)
  10105. (deadline org-deadline-time-regexp)
  10106. (scheduled org-scheduled-time-regexp)
  10107. (otherwise
  10108. (error "Invalid planning type: %s" type)))
  10109. (line-end-position) t)
  10110. ;; Delete until next keyword or end of line.
  10111. (delete-region
  10112. (match-beginning 0)
  10113. (if (re-search-forward org-keyword-time-not-clock-regexp
  10114. (line-end-position)
  10115. t)
  10116. (match-beginning 0)
  10117. (line-end-position))))))
  10118. ;; If there is nothing more to add and no more keyword
  10119. ;; is left, remove the line completely.
  10120. (if (and (looking-at-p "[ \t]*$") (not what))
  10121. (delete-region (line-beginning-position)
  10122. (line-beginning-position 2))
  10123. ;; If we removed last keyword, do not leave trailing
  10124. ;; white space at the end of line.
  10125. (let ((p (point)))
  10126. (save-excursion
  10127. (end-of-line)
  10128. (unless (= (skip-chars-backward " \t" p) 0)
  10129. (delete-region (point) (line-end-position)))))))
  10130. ((not what) (throw 'exit nil)) ; Nothing to do.
  10131. (t (insert-before-markers "\n")
  10132. (backward-char 1)
  10133. (when org-adapt-indentation
  10134. (indent-to-column (1+ (org-outline-level))))))
  10135. (when what
  10136. ;; Insert planning keyword.
  10137. (insert (cl-case what
  10138. (closed org-closed-string)
  10139. (deadline org-deadline-string)
  10140. (scheduled org-scheduled-string)
  10141. (otherwise (error "Invalid planning type: %s" what)))
  10142. " ")
  10143. ;; Insert associated timestamp.
  10144. (let ((ts (org-insert-time-stamp
  10145. time
  10146. (or org-time-was-given
  10147. (and (eq what 'closed) org-log-done-with-time))
  10148. (eq what 'closed)
  10149. nil nil (list org-end-time-was-given))))
  10150. (unless (eolp) (insert " "))
  10151. ts))))))
  10152. (defvar org-log-note-marker (make-marker)
  10153. "Marker pointing at the entry where the note is to be inserted.")
  10154. (defvar org-log-note-purpose nil)
  10155. (defvar org-log-note-state nil)
  10156. (defvar org-log-note-previous-state nil)
  10157. (defvar org-log-note-extra nil)
  10158. (defvar org-log-note-window-configuration nil)
  10159. (defvar org-log-note-return-to (make-marker))
  10160. (defvar org-log-note-effective-time nil
  10161. "Remembered current time so that dynamically scoped
  10162. `org-extend-today-until' affects timestamps in state change log")
  10163. (defvar org-log-post-message nil
  10164. "Message to be displayed after a log note has been stored.
  10165. The auto-repeater uses this.")
  10166. (defun org-add-note ()
  10167. "Add a note to the current entry.
  10168. This is done in the same way as adding a state change note."
  10169. (interactive)
  10170. (org-add-log-setup 'note))
  10171. (defun org-log-beginning (&optional create)
  10172. "Return expected start of log notes in current entry.
  10173. When optional argument CREATE is non-nil, the function creates
  10174. a drawer to store notes, if necessary. Returned position ignores
  10175. narrowing."
  10176. (org-with-wide-buffer
  10177. (let ((drawer (org-log-into-drawer)))
  10178. (cond
  10179. (drawer
  10180. (org-end-of-meta-data)
  10181. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  10182. (end (if (org-at-heading-p) (point)
  10183. (save-excursion (outline-next-heading) (point))))
  10184. (case-fold-search t))
  10185. (catch 'exit
  10186. ;; Try to find existing drawer.
  10187. (while (re-search-forward regexp end t)
  10188. (let ((element (org-element-at-point)))
  10189. (when (eq (org-element-type element) 'drawer)
  10190. (let ((cend (org-element-property :contents-end element)))
  10191. (when (and (not org-log-states-order-reversed) cend)
  10192. (goto-char cend)))
  10193. (throw 'exit nil))))
  10194. ;; No drawer found. Create one, if permitted.
  10195. (when create
  10196. (unless (bolp) (insert "\n"))
  10197. (let ((beg (point)))
  10198. (insert ":" drawer ":\n:END:\n")
  10199. (org-indent-region beg (point))
  10200. (org-flag-region
  10201. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  10202. (end-of-line -1)))))
  10203. (t
  10204. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  10205. (skip-chars-forward " \t\n")
  10206. (beginning-of-line)
  10207. (unless org-log-states-order-reversed
  10208. (org-skip-over-state-notes)
  10209. (skip-chars-backward " \t\n")
  10210. (forward-line)))))
  10211. (if (bolp) (point) (line-beginning-position 2))))
  10212. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  10213. "Set up the post command hook to take a note.
  10214. If this is about to TODO state change, the new state is expected in STATE.
  10215. HOW is an indicator what kind of note should be created.
  10216. EXTRA is additional text that will be inserted into the notes buffer."
  10217. (move-marker org-log-note-marker (point))
  10218. (setq org-log-note-purpose purpose
  10219. org-log-note-state state
  10220. org-log-note-previous-state prev-state
  10221. org-log-note-how how
  10222. org-log-note-extra extra
  10223. org-log-note-effective-time (org-current-effective-time))
  10224. (add-hook 'post-command-hook 'org-add-log-note 'append))
  10225. (defun org-skip-over-state-notes ()
  10226. "Skip past the list of State notes in an entry."
  10227. (when (ignore-errors (goto-char (org-in-item-p)))
  10228. (let* ((struct (org-list-struct))
  10229. (prevs (org-list-prevs-alist struct))
  10230. (regexp
  10231. (concat "[ \t]*- +"
  10232. (replace-regexp-in-string
  10233. " +" " +"
  10234. (org-replace-escapes
  10235. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  10236. `(("%d" . ,org-ts-regexp-inactive)
  10237. ("%D" . ,org-ts-regexp)
  10238. ("%s" . "\\(?:\"\\S-+\"\\)?")
  10239. ("%S" . "\\(?:\"\\S-+\"\\)?")
  10240. ("%t" . ,org-ts-regexp-inactive)
  10241. ("%T" . ,org-ts-regexp)
  10242. ("%u" . ".*?")
  10243. ("%U" . ".*?")))))))
  10244. (while (looking-at-p regexp)
  10245. (goto-char (or (org-list-get-next-item (point) struct prevs)
  10246. (org-list-get-item-end (point) struct)))))))
  10247. (defun org-add-log-note (&optional _purpose)
  10248. "Pop up a window for taking a note, and add this note later."
  10249. (remove-hook 'post-command-hook 'org-add-log-note)
  10250. (setq org-log-note-window-configuration (current-window-configuration))
  10251. (delete-other-windows)
  10252. (move-marker org-log-note-return-to (point))
  10253. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  10254. (goto-char org-log-note-marker)
  10255. (org-switch-to-buffer-other-window "*Org Note*")
  10256. (erase-buffer)
  10257. (if (memq org-log-note-how '(time state))
  10258. (org-store-log-note)
  10259. (let ((org-inhibit-startup t)) (org-mode))
  10260. (insert (format "# Insert note for %s.
  10261. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  10262. (cl-case org-log-note-purpose
  10263. (clock-out "stopped clock")
  10264. (done "closed todo item")
  10265. (reschedule "rescheduling")
  10266. (delschedule "no longer scheduled")
  10267. (redeadline "changing deadline")
  10268. (deldeadline "removing deadline")
  10269. (refile "refiling")
  10270. (note "this entry")
  10271. (state
  10272. (format "state change from \"%s\" to \"%s\""
  10273. (or org-log-note-previous-state "")
  10274. (or org-log-note-state "")))
  10275. (t (error "This should not happen")))))
  10276. (when org-log-note-extra (insert org-log-note-extra))
  10277. (setq-local org-finish-function 'org-store-log-note)
  10278. (run-hooks 'org-log-buffer-setup-hook)))
  10279. (defvar org-note-abort nil) ; dynamically scoped
  10280. (defun org-store-log-note ()
  10281. "Finish taking a log note, and insert it to where it belongs."
  10282. (let ((txt (prog1 (buffer-string)
  10283. (kill-buffer)))
  10284. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  10285. lines)
  10286. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  10287. (setq txt (replace-match "" t t txt)))
  10288. (when (string-match "\\s-+\\'" txt)
  10289. (setq txt (replace-match "" t t txt)))
  10290. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  10291. (when (org-string-nw-p note)
  10292. (setq note
  10293. (org-replace-escapes
  10294. note
  10295. (list (cons "%u" (user-login-name))
  10296. (cons "%U" user-full-name)
  10297. (cons "%t" (format-time-string
  10298. (org-time-stamp-format 'long 'inactive)
  10299. org-log-note-effective-time))
  10300. (cons "%T" (format-time-string
  10301. (org-time-stamp-format 'long nil)
  10302. org-log-note-effective-time))
  10303. (cons "%d" (format-time-string
  10304. (org-time-stamp-format nil 'inactive)
  10305. org-log-note-effective-time))
  10306. (cons "%D" (format-time-string
  10307. (org-time-stamp-format nil nil)
  10308. org-log-note-effective-time))
  10309. (cons "%s" (cond
  10310. ((not org-log-note-state) "")
  10311. ((string-match-p org-ts-regexp
  10312. org-log-note-state)
  10313. (format "\"[%s]\""
  10314. (substring org-log-note-state 1 -1)))
  10315. (t (format "\"%s\"" org-log-note-state))))
  10316. (cons "%S"
  10317. (cond
  10318. ((not org-log-note-previous-state) "")
  10319. ((string-match-p org-ts-regexp
  10320. org-log-note-previous-state)
  10321. (format "\"[%s]\""
  10322. (substring
  10323. org-log-note-previous-state 1 -1)))
  10324. (t (format "\"%s\""
  10325. org-log-note-previous-state)))))))
  10326. (when lines (setq note (concat note " \\\\")))
  10327. (push note lines))
  10328. (when (and lines (not org-note-abort))
  10329. (with-current-buffer (marker-buffer org-log-note-marker)
  10330. (org-with-wide-buffer
  10331. ;; Find location for the new note.
  10332. (goto-char org-log-note-marker)
  10333. (set-marker org-log-note-marker nil)
  10334. ;; Note associated to a clock is to be located right after
  10335. ;; the clock. Do not move point.
  10336. (unless (eq org-log-note-purpose 'clock-out)
  10337. (goto-char (org-log-beginning t)))
  10338. ;; Make sure point is at the beginning of an empty line.
  10339. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  10340. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  10341. ;; In an existing list, add a new item at the top level.
  10342. ;; Otherwise, indent line like a regular one.
  10343. (let ((itemp (org-in-item-p)))
  10344. (if itemp
  10345. (indent-line-to
  10346. (let ((struct (save-excursion
  10347. (goto-char itemp) (org-list-struct))))
  10348. (org-list-get-ind (org-list-get-top-point struct) struct)))
  10349. (org-indent-line)))
  10350. (insert (org-list-bullet-string "-") (pop lines))
  10351. (let ((ind (org-list-item-body-column (line-beginning-position))))
  10352. (dolist (line lines)
  10353. (insert "\n")
  10354. (indent-line-to ind)
  10355. (insert line)))
  10356. (message "Note stored")
  10357. (org-back-to-heading t))
  10358. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  10359. ;; from within `org-add-log-note' because `buffer-undo-list'
  10360. ;; is then modified outside of `org-with-remote-undo'.
  10361. (when (eq this-command 'org-agenda-todo)
  10362. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  10363. ;; Don't add undo information when called from `org-agenda-todo'.
  10364. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  10365. (set-window-configuration org-log-note-window-configuration)
  10366. (with-current-buffer (marker-buffer org-log-note-return-to)
  10367. (goto-char org-log-note-return-to))
  10368. (move-marker org-log-note-return-to nil)
  10369. (when org-log-post-message (message "%s" org-log-post-message))))
  10370. (defun org-remove-empty-drawer-at (pos)
  10371. "Remove an empty drawer at position POS.
  10372. POS may also be a marker."
  10373. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  10374. (org-with-wide-buffer
  10375. (goto-char pos)
  10376. (let ((drawer (org-element-at-point)))
  10377. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  10378. (not (org-element-property :contents-begin drawer)))
  10379. (delete-region (org-element-property :begin drawer)
  10380. (progn (goto-char (org-element-property :end drawer))
  10381. (skip-chars-backward " \r\t\n")
  10382. (forward-line)
  10383. (point))))))))
  10384. (defvar org-ts-type nil)
  10385. (defun org-sparse-tree (&optional arg type)
  10386. "Create a sparse tree, prompt for the details.
  10387. This command can create sparse trees. You first need to select the type
  10388. of match used to create the tree:
  10389. t Show all TODO entries.
  10390. T Show entries with a specific TODO keyword.
  10391. m Show entries selected by a tags/property match.
  10392. p Enter a property name and its value (both with completion on existing
  10393. names/values) and show entries with that property.
  10394. r Show entries matching a regular expression (`/' can be used as well).
  10395. b Show deadlines and scheduled items before a date.
  10396. a Show deadlines and scheduled items after a date.
  10397. d Show deadlines due within `org-deadline-warning-days'.
  10398. D Show deadlines and scheduled items between a date range."
  10399. (interactive "P")
  10400. (setq type (or type org-sparse-tree-default-date-type))
  10401. (setq org-ts-type type)
  10402. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  10403. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  10404. \[c]ycle through date types: %s"
  10405. (cl-case type
  10406. (all "all timestamps")
  10407. (scheduled "only scheduled")
  10408. (deadline "only deadline")
  10409. (active "only active timestamps")
  10410. (inactive "only inactive timestamps")
  10411. (closed "with a closed time-stamp")
  10412. (otherwise "scheduled/deadline")))
  10413. (let ((answer (read-char-exclusive)))
  10414. (cl-case answer
  10415. (?c
  10416. (org-sparse-tree
  10417. arg
  10418. (cadr
  10419. (memq type '(nil all scheduled deadline active inactive closed)))))
  10420. (?d (call-interactively 'org-check-deadlines))
  10421. (?b (call-interactively 'org-check-before-date))
  10422. (?a (call-interactively 'org-check-after-date))
  10423. (?D (call-interactively 'org-check-dates-range))
  10424. (?t (call-interactively 'org-show-todo-tree))
  10425. (?T (org-show-todo-tree '(4)))
  10426. (?m (call-interactively 'org-match-sparse-tree))
  10427. ((?p ?P)
  10428. (let* ((kwd (completing-read
  10429. "Property: " (mapcar #'list (org-buffer-property-keys))))
  10430. (value (completing-read
  10431. "Value: " (mapcar #'list (org-property-values kwd)))))
  10432. (unless (string-match "\\`{.*}\\'" value)
  10433. (setq value (concat "\"" value "\"")))
  10434. (org-match-sparse-tree arg (concat kwd "=" value))))
  10435. ((?r ?R ?/) (call-interactively 'org-occur))
  10436. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  10437. (defvar-local org-occur-highlights nil
  10438. "List of overlays used for occur matches.")
  10439. (defvar-local org-occur-parameters nil
  10440. "Parameters of the active org-occur calls.
  10441. This is a list, each call to org-occur pushes as cons cell,
  10442. containing the regular expression and the callback, onto the list.
  10443. The list can contain several entries if `org-occur' has been called
  10444. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  10445. will only contain one set of parameters. When the highlights are
  10446. removed (for example with `C-c C-c', or with the next edit (depending
  10447. on `org-remove-highlights-with-change'), this variable is emptied
  10448. as well.")
  10449. (defun org-occur (regexp &optional keep-previous callback)
  10450. "Make a compact tree which shows all matches of REGEXP.
  10451. The tree will show the lines where the regexp matches, and any other context
  10452. defined in `org-show-context-detail', which see.
  10453. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  10454. done by a previous call to `org-occur' will be kept, to allow stacking of
  10455. calls to this command.
  10456. Optional argument CALLBACK can be a function of no argument. In this case,
  10457. it is called with point at the end of the match, match data being set
  10458. accordingly. Current match is shown only if the return value is non-nil.
  10459. The function must neither move point nor alter narrowing."
  10460. (interactive "sRegexp: \nP")
  10461. (when (equal regexp "")
  10462. (user-error "Regexp cannot be empty"))
  10463. (unless keep-previous
  10464. (org-remove-occur-highlights nil nil t))
  10465. (push (cons regexp callback) org-occur-parameters)
  10466. (let ((cnt 0))
  10467. (save-excursion
  10468. (goto-char (point-min))
  10469. (when (or (not keep-previous) ; do not want to keep
  10470. (not org-occur-highlights)) ; no previous matches
  10471. ;; hide everything
  10472. (org-overview))
  10473. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  10474. (isearch-no-upper-case-p regexp t)
  10475. org-occur-case-fold-search)))
  10476. (while (re-search-forward regexp nil t)
  10477. (when (or (not callback)
  10478. (save-match-data (funcall callback)))
  10479. (setq cnt (1+ cnt))
  10480. (when org-highlight-sparse-tree-matches
  10481. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  10482. (org-show-context 'occur-tree)))))
  10483. (when org-remove-highlights-with-change
  10484. (add-hook 'before-change-functions 'org-remove-occur-highlights
  10485. nil 'local))
  10486. (unless org-sparse-tree-open-archived-trees
  10487. (org-hide-archived-subtrees (point-min) (point-max)))
  10488. (run-hooks 'org-occur-hook)
  10489. (when (called-interactively-p 'interactive)
  10490. (message "%d match(es) for regexp %s" cnt regexp))
  10491. cnt))
  10492. (defun org-occur-next-match (&optional n _reset)
  10493. "Function for `next-error-function' to find sparse tree matches.
  10494. N is the number of matches to move, when negative move backwards.
  10495. This function always goes back to the starting point when no
  10496. match is found."
  10497. (let* ((limit (if (< n 0) (point-min) (point-max)))
  10498. (search-func (if (< n 0)
  10499. 'previous-single-char-property-change
  10500. 'next-single-char-property-change))
  10501. (n (abs n))
  10502. (pos (point))
  10503. p1)
  10504. (catch 'exit
  10505. (while (setq p1 (funcall search-func (point) 'org-type))
  10506. (when (equal p1 limit)
  10507. (goto-char pos)
  10508. (user-error "No more matches"))
  10509. (when (equal (get-char-property p1 'org-type) 'org-occur)
  10510. (setq n (1- n))
  10511. (when (= n 0)
  10512. (goto-char p1)
  10513. (throw 'exit (point))))
  10514. (goto-char p1))
  10515. (goto-char p1)
  10516. (user-error "No more matches"))))
  10517. (defun org-highlight-new-match (beg end)
  10518. "Highlight from BEG to END and mark the highlight is an occur headline."
  10519. (let ((ov (make-overlay beg end)))
  10520. (overlay-put ov 'face 'secondary-selection)
  10521. (overlay-put ov 'org-type 'org-occur)
  10522. (push ov org-occur-highlights)))
  10523. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10524. "Remove the occur highlights from the buffer.
  10525. BEG and END are ignored. If NOREMOVE is nil, remove this function
  10526. from the `before-change-functions' in the current buffer."
  10527. (interactive)
  10528. (unless org-inhibit-highlight-removal
  10529. (mapc #'delete-overlay org-occur-highlights)
  10530. (setq org-occur-highlights nil)
  10531. (setq org-occur-parameters nil)
  10532. (unless noremove
  10533. (remove-hook 'before-change-functions
  10534. 'org-remove-occur-highlights 'local))))
  10535. ;;;; Priorities
  10536. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  10537. "Regular expression matching the priority indicator.
  10538. A priority indicator can be e.g. [#A] or [#1].
  10539. This regular expression matches these groups:
  10540. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  10541. 1 : the priority cookie, e.g. \"[#A]\"
  10542. 2 : the value of the priority cookie, e.g. \"A\".")
  10543. (defun org-priority-up ()
  10544. "Increase the priority of the current item."
  10545. (interactive)
  10546. (org-priority 'up))
  10547. (defun org-priority-down ()
  10548. "Decrease the priority of the current item."
  10549. (interactive)
  10550. (org-priority 'down))
  10551. (defun org-priority (&optional action show)
  10552. "Change the priority of an item.
  10553. When called interactively with a `\\[universal-argument]' prefix,
  10554. show the priority in the minibuffer instead of changing it.
  10555. When called programmatically, ACTION can be `set', `up', `down',
  10556. or a character."
  10557. (interactive "P")
  10558. (when show
  10559. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10560. ;; passed the SHOW argument should be removed.
  10561. (warn "`org-priority' called with deprecated SHOW argument"))
  10562. (if (equal action '(4))
  10563. (org-priority-show)
  10564. (unless org-priority-enable-commands
  10565. (user-error "Priority commands are disabled"))
  10566. (setq action (or action 'set))
  10567. (let ((nump (< org-priority-lowest 65))
  10568. current new news have remove)
  10569. (save-excursion
  10570. (org-back-to-heading t)
  10571. (when (looking-at org-priority-regexp)
  10572. (let ((ms (match-string 2)))
  10573. (setq current (org-priority-to-value ms)
  10574. have t)))
  10575. (cond
  10576. ((eq action 'remove)
  10577. (setq remove t new ?\ ))
  10578. ((or (eq action 'set)
  10579. (integerp action))
  10580. (if (not (eq action 'set))
  10581. (setq new action)
  10582. (setq
  10583. new
  10584. (if nump
  10585. (string-to-number
  10586. (read-string (format "Priority %s-%s, SPC to remove: "
  10587. (number-to-string org-priority-highest)
  10588. (number-to-string org-priority-lowest))))
  10589. (progn (message "Priority %c-%c, SPC to remove: "
  10590. org-priority-highest org-priority-lowest)
  10591. (save-match-data
  10592. (setq new (read-char-exclusive)))))))
  10593. (when (and (= (upcase org-priority-highest) org-priority-highest)
  10594. (= (upcase org-priority-lowest) org-priority-lowest))
  10595. (setq new (upcase new)))
  10596. (cond ((equal new ?\s) (setq remove t))
  10597. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  10598. (user-error
  10599. (if nump
  10600. "Priority must be between `%s' and `%s'"
  10601. "Priority must be between `%c' and `%c'")
  10602. org-priority-highest org-priority-lowest))))
  10603. ((eq action 'up)
  10604. (setq new (if have
  10605. (1- current) ; normal cycling
  10606. ;; last priority was empty
  10607. (if (eq last-command this-command)
  10608. org-priority-lowest ; wrap around empty to lowest
  10609. ;; default
  10610. (if org-priority-start-cycle-with-default
  10611. org-priority-default
  10612. (1- org-priority-default))))))
  10613. ((eq action 'down)
  10614. (setq new (if have
  10615. (1+ current) ; normal cycling
  10616. ;; last priority was empty
  10617. (if (eq last-command this-command)
  10618. org-priority-highest ; wrap around empty to highest
  10619. ;; default
  10620. (if org-priority-start-cycle-with-default
  10621. org-priority-default
  10622. (1+ org-priority-default))))))
  10623. (t (user-error "Invalid action")))
  10624. (when (or (< (upcase new) org-priority-highest)
  10625. (> (upcase new) org-priority-lowest))
  10626. (if (and (memq action '(up down))
  10627. (not have) (not (eq last-command this-command)))
  10628. ;; `new' is from default priority
  10629. (error
  10630. "The default can not be set, see `org-priority-default' why")
  10631. ;; normal cycling: `new' is beyond highest/lowest priority
  10632. ;; and is wrapped around to the empty priority
  10633. (setq remove t)))
  10634. ;; Numerical priorities are limited to 64, beyond that number,
  10635. ;; assume the priority cookie is a character.
  10636. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  10637. (if have
  10638. (if remove
  10639. (replace-match "" t t nil 1)
  10640. (replace-match news t t nil 2))
  10641. (if remove
  10642. (user-error "No priority cookie found in line")
  10643. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10644. (if (match-end 2)
  10645. (progn
  10646. (goto-char (match-end 2))
  10647. (insert " [#" news "]"))
  10648. (goto-char (match-beginning 3))
  10649. (insert "[#" news "] "))))
  10650. (org-align-tags))
  10651. (if remove
  10652. (message "Priority removed")
  10653. (message "Priority of current item set to %s" news)))))
  10654. (defalias 'org-show-priority 'org-priority-show)
  10655. (defun org-priority-show ()
  10656. "Show the priority of the current item.
  10657. This priority is composed of the main priority given with the [#A] cookies,
  10658. and by additional input from the age of a schedules or deadline entry."
  10659. (interactive)
  10660. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10661. (org-get-at-bol 'priority)
  10662. (save-excursion
  10663. (save-match-data
  10664. (beginning-of-line)
  10665. (and (looking-at org-heading-regexp)
  10666. (org-get-priority (match-string 0))))))))
  10667. (message "Priority is %d" (if pri pri -1000))))
  10668. (defun org-get-priority (s)
  10669. "Find priority cookie and return priority.
  10670. S is a string against which you can match `org-priority-regexp'.
  10671. If `org-priority-get-priority-function' is set to a custom
  10672. function, use it. Otherwise process S and output the priority
  10673. value, an integer."
  10674. (save-match-data
  10675. (if (functionp org-priority-get-priority-function)
  10676. (funcall org-priority-get-priority-function s)
  10677. (if (not (string-match org-priority-regexp s))
  10678. (* 1000 (- org-priority-lowest org-priority-default))
  10679. (* 1000 (- org-priority-lowest
  10680. (org-priority-to-value (match-string 2 s))))))))
  10681. ;;;; Tags
  10682. (defvar org-agenda-archives-mode)
  10683. (defvar org-map-continue-from nil
  10684. "Position from where mapping should continue.
  10685. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10686. (defvar org-scanner-tags nil
  10687. "The current tag list while the tags scanner is running.")
  10688. (defvar org-trust-scanner-tags nil
  10689. "Should `org-get-tags' use the tags for the scanner.
  10690. This is for internal dynamical scoping only.
  10691. When this is non-nil, the function `org-get-tags' will return the value
  10692. of `org-scanner-tags' instead of building the list by itself. This
  10693. can lead to large speed-ups when the tags scanner is used in a file with
  10694. many entries, and when the list of tags is retrieved, for example to
  10695. obtain a list of properties. Building the tags list for each entry in such
  10696. a file becomes an N^2 operation - but with this variable set, it scales
  10697. as N.")
  10698. (defvar org--matcher-tags-todo-only nil)
  10699. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10700. "Scan headline tags with inheritance and produce output ACTION.
  10701. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10702. or `agenda' to produce an entry list for an agenda view. It can also be
  10703. a Lisp form or a function that should be called at each matched headline, in
  10704. this case the return value is a list of all return values from these calls.
  10705. MATCHER is a function accepting three arguments, returning
  10706. a non-nil value whenever a given set of tags qualifies a headline
  10707. for inclusion. See `org-make-tags-matcher' for more information.
  10708. As a special case, it can also be set to t (respectively nil) in
  10709. order to match all (respectively none) headline.
  10710. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10711. included in the output.
  10712. START-LEVEL can be a string with asterisks, reducing the scope to
  10713. headlines matching this string."
  10714. (require 'org-agenda)
  10715. (let* ((re (concat "^"
  10716. (if start-level
  10717. ;; Get the correct level to match
  10718. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10719. org-outline-regexp)
  10720. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10721. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10722. (props (list 'face 'default
  10723. 'done-face 'org-agenda-done
  10724. 'undone-face 'default
  10725. 'mouse-face 'highlight
  10726. 'org-not-done-regexp org-not-done-regexp
  10727. 'org-todo-regexp org-todo-regexp
  10728. 'org-complex-heading-regexp org-complex-heading-regexp
  10729. 'help-echo
  10730. (format "mouse-2 or RET jump to Org file %S"
  10731. (abbreviate-file-name
  10732. (or (buffer-file-name (buffer-base-buffer))
  10733. (buffer-name (buffer-base-buffer)))))))
  10734. (org-map-continue-from nil)
  10735. lspos tags tags-list
  10736. (tags-alist (list (cons 0 org-file-tags)))
  10737. (llast 0) rtn rtn1 level category i txt
  10738. todo marker entry priority
  10739. ts-date ts-date-type ts-date-pair)
  10740. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10741. (setq action (list 'lambda nil action)))
  10742. (save-excursion
  10743. (goto-char (point-min))
  10744. (when (eq action 'sparse-tree)
  10745. (org-overview)
  10746. (org-remove-occur-highlights))
  10747. (while (let (case-fold-search)
  10748. (re-search-forward re nil t))
  10749. (setq org-map-continue-from nil)
  10750. (catch :skip
  10751. ;; Ignore closing parts of inline tasks.
  10752. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10753. (throw :skip t))
  10754. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10755. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10756. (goto-char (setq lspos (match-beginning 0)))
  10757. (setq level (org-reduced-level (org-outline-level))
  10758. category (org-get-category))
  10759. (when (eq action 'agenda)
  10760. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10761. ts-date (car ts-date-pair)
  10762. ts-date-type (cdr ts-date-pair)))
  10763. (setq i llast llast level)
  10764. ;; remove tag lists from same and sublevels
  10765. (while (>= i level)
  10766. (when (setq entry (assoc i tags-alist))
  10767. (setq tags-alist (delete entry tags-alist)))
  10768. (setq i (1- i)))
  10769. ;; add the next tags
  10770. (when tags
  10771. (setq tags (org-split-string tags ":")
  10772. tags-alist
  10773. (cons (cons level tags) tags-alist)))
  10774. ;; compile tags for current headline
  10775. (setq tags-list
  10776. (if org-use-tag-inheritance
  10777. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10778. tags)
  10779. org-scanner-tags tags-list)
  10780. (when org-use-tag-inheritance
  10781. (setcdr (car tags-alist)
  10782. (mapcar (lambda (x)
  10783. (setq x (copy-sequence x))
  10784. (org-add-prop-inherited x))
  10785. (cdar tags-alist))))
  10786. (when (and tags org-use-tag-inheritance
  10787. (or (not (eq t org-use-tag-inheritance))
  10788. org-tags-exclude-from-inheritance))
  10789. ;; Selective inheritance, remove uninherited ones.
  10790. (setcdr (car tags-alist)
  10791. (org-remove-uninherited-tags (cdar tags-alist))))
  10792. (when (and
  10793. ;; eval matcher only when the todo condition is OK
  10794. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10795. (if (functionp matcher)
  10796. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10797. (funcall matcher todo tags-list level))
  10798. matcher))
  10799. ;; Call the skipper, but return t if it does not
  10800. ;; skip, so that the `and' form continues evaluating.
  10801. (progn
  10802. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10803. t)
  10804. ;; Check if timestamps are deselecting this entry
  10805. (or (not todo-only)
  10806. (and (member todo org-todo-keywords-1)
  10807. (or (not org-agenda-tags-todo-honor-ignore-options)
  10808. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10809. ;; select this headline
  10810. (cond
  10811. ((eq action 'sparse-tree)
  10812. (and org-highlight-sparse-tree-matches
  10813. (org-get-heading) (match-end 0)
  10814. (org-highlight-new-match
  10815. (match-beginning 1) (match-end 1)))
  10816. (org-show-context 'tags-tree))
  10817. ((eq action 'agenda)
  10818. (setq txt (org-agenda-format-item
  10819. ""
  10820. (concat
  10821. (if (eq org-tags-match-list-sublevels 'indented)
  10822. (make-string (1- level) ?.) "")
  10823. (org-get-heading))
  10824. (make-string level ?\s)
  10825. category
  10826. tags-list)
  10827. priority (org-get-priority txt))
  10828. (goto-char lspos)
  10829. (setq marker (org-agenda-new-marker))
  10830. (org-add-props txt props
  10831. 'org-marker marker 'org-hd-marker marker 'org-category category
  10832. 'todo-state todo
  10833. 'ts-date ts-date
  10834. 'priority priority
  10835. 'type (concat "tagsmatch" ts-date-type))
  10836. (push txt rtn))
  10837. ((functionp action)
  10838. (setq org-map-continue-from nil)
  10839. (save-excursion
  10840. (setq rtn1 (funcall action))
  10841. (push rtn1 rtn)))
  10842. (t (user-error "Invalid action")))
  10843. ;; if we are to skip sublevels, jump to end of subtree
  10844. (unless org-tags-match-list-sublevels
  10845. (org-end-of-subtree t)
  10846. (backward-char 1))))
  10847. ;; Get the correct position from where to continue
  10848. (if org-map-continue-from
  10849. (goto-char org-map-continue-from)
  10850. (and (= (point) lspos) (end-of-line 1)))))
  10851. (when (and (eq action 'sparse-tree)
  10852. (not org-sparse-tree-open-archived-trees))
  10853. (org-hide-archived-subtrees (point-min) (point-max)))
  10854. (nreverse rtn)))
  10855. (defun org-remove-uninherited-tags (tags)
  10856. "Remove all tags that are not inherited from the list TAGS."
  10857. (cond
  10858. ((eq org-use-tag-inheritance t)
  10859. (if org-tags-exclude-from-inheritance
  10860. (org-delete-all org-tags-exclude-from-inheritance tags)
  10861. tags))
  10862. ((not org-use-tag-inheritance) nil)
  10863. ((stringp org-use-tag-inheritance)
  10864. (delq nil (mapcar
  10865. (lambda (x)
  10866. (if (and (string-match org-use-tag-inheritance x)
  10867. (not (member x org-tags-exclude-from-inheritance)))
  10868. x nil))
  10869. tags)))
  10870. ((listp org-use-tag-inheritance)
  10871. (delq nil (mapcar
  10872. (lambda (x)
  10873. (if (member x org-use-tag-inheritance) x nil))
  10874. tags)))))
  10875. (defun org-match-sparse-tree (&optional todo-only match)
  10876. "Create a sparse tree according to tags string MATCH.
  10877. MATCH is a string with match syntax. It can contain a selection
  10878. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10879. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10880. those. See the manual for details.
  10881. If optional argument TODO-ONLY is non-nil, only select lines that
  10882. are also TODO tasks."
  10883. (interactive "P")
  10884. (org-agenda-prepare-buffers (list (current-buffer)))
  10885. (let ((org--matcher-tags-todo-only todo-only))
  10886. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  10887. org--matcher-tags-todo-only)))
  10888. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10889. (defvar org-cached-props nil)
  10890. (defun org-cached-entry-get (pom property)
  10891. (if (or (eq t org-use-property-inheritance)
  10892. (and (stringp org-use-property-inheritance)
  10893. (let ((case-fold-search t))
  10894. (string-match-p org-use-property-inheritance property)))
  10895. (and (listp org-use-property-inheritance)
  10896. (member-ignore-case property org-use-property-inheritance)))
  10897. ;; Caching is not possible, check it directly.
  10898. (org-entry-get pom property 'inherit)
  10899. ;; Get all properties, so we can do complicated checks easily.
  10900. (cdr (assoc-string property
  10901. (or org-cached-props
  10902. (setq org-cached-props (org-entry-properties pom)))
  10903. t))))
  10904. (defun org-global-tags-completion-table (&optional files)
  10905. "Return the list of all tags in all agenda buffer/files.
  10906. Optional FILES argument is a list of files which can be used
  10907. instead of the agenda files."
  10908. (save-excursion
  10909. (org-uniquify
  10910. (delq nil
  10911. (apply #'append
  10912. (mapcar
  10913. (lambda (file)
  10914. (set-buffer (find-file-noselect file))
  10915. (org--tag-add-to-alist
  10916. (org-get-buffer-tags)
  10917. (mapcar (lambda (x)
  10918. (and (stringp (car-safe x))
  10919. (list (car-safe x))))
  10920. org-current-tag-alist)))
  10921. (if (car-safe files) files
  10922. (org-agenda-files))))))))
  10923. (defun org-make-tags-matcher (match)
  10924. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10925. Returns a cons of the selection string MATCH and a function
  10926. implementing the matcher.
  10927. The matcher is to be called at an Org entry, with point on the
  10928. headline, and returns non-nil if the entry matches the selection
  10929. string MATCH. It must be called with three arguments: the TODO
  10930. keyword at the entry (or nil if none), the list of all tags at
  10931. the entry including inherited ones and the reduced level of the
  10932. headline. Additionally, the category of the entry, if any, must
  10933. be specified as the text property `org-category' on the headline.
  10934. This function sets the variable `org--matcher-tags-todo-only' to
  10935. a non-nil value if the matcher restricts matching to TODO
  10936. entries, otherwise it is not touched.
  10937. See also `org-scan-tags'."
  10938. (unless match
  10939. ;; Get a new match request, with completion against the global
  10940. ;; tags table and the local tags in current buffer.
  10941. (let ((org-last-tags-completion-table
  10942. (org--tag-add-to-alist
  10943. (org-get-buffer-tags)
  10944. (org-global-tags-completion-table))))
  10945. (setq match
  10946. (completing-read
  10947. "Match: "
  10948. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10949. (let ((match0 match)
  10950. (re (concat
  10951. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10952. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10953. "\\([<>=]\\{1,2\\}\\)"
  10954. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10955. "\\|" org-tag-re "\\)"))
  10956. (start 0)
  10957. tagsmatch todomatch tagsmatcher todomatcher)
  10958. ;; Expand group tags.
  10959. (setq match (org-tags-expand match))
  10960. ;; Check if there is a TODO part of this match, which would be the
  10961. ;; part after a "/". To make sure that this slash is not part of
  10962. ;; a property value to be matched against, we also check that
  10963. ;; there is no / after that slash. First, find the last slash.
  10964. (let ((s 0))
  10965. (while (string-match "/+" match s)
  10966. (setq start (match-beginning 0))
  10967. (setq s (match-end 0))))
  10968. (if (and (string-match "/+" match start)
  10969. (not (string-match-p "\"" match start)))
  10970. ;; Match contains also a TODO-matching request.
  10971. (progn
  10972. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10973. (setq todomatch (substring match (match-end 0)))
  10974. (when (string-prefix-p "!" todomatch)
  10975. (setq org--matcher-tags-todo-only t)
  10976. (setq todomatch (substring todomatch 1)))
  10977. (when (string-match "\\`\\s-*\\'" todomatch)
  10978. (setq todomatch nil)))
  10979. ;; Only matching tags.
  10980. (setq tagsmatch match)
  10981. (setq todomatch nil))
  10982. ;; Make the tags matcher.
  10983. (when (org-string-nw-p tagsmatch)
  10984. (let ((orlist nil)
  10985. (orterms (org-split-string tagsmatch "|"))
  10986. term)
  10987. (while (setq term (pop orterms))
  10988. (while (and (equal (substring term -1) "\\") orterms)
  10989. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10990. (while (string-match re term)
  10991. (let* ((rest (substring term (match-end 0)))
  10992. (minus (and (match-end 1)
  10993. (equal (match-string 1 term) "-")))
  10994. (tag (save-match-data
  10995. (replace-regexp-in-string
  10996. "\\\\-" "-" (match-string 2 term))))
  10997. (regexp (eq (string-to-char tag) ?{))
  10998. (levelp (match-end 4))
  10999. (propp (match-end 5))
  11000. (mm
  11001. (cond
  11002. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  11003. (levelp
  11004. `(,(org-op-to-function (match-string 3 term))
  11005. level
  11006. ,(string-to-number (match-string 4 term))))
  11007. (propp
  11008. (let* ((gv (pcase (upcase (match-string 5 term))
  11009. ("CATEGORY"
  11010. '(get-text-property (point) 'org-category))
  11011. ("TODO" 'todo)
  11012. (p `(org-cached-entry-get nil ,p))))
  11013. (pv (match-string 7 term))
  11014. (regexp (eq (string-to-char pv) ?{))
  11015. (strp (eq (string-to-char pv) ?\"))
  11016. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  11017. (po (org-op-to-function (match-string 6 term)
  11018. (if timep 'time strp))))
  11019. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  11020. (when timep (setq pv (org-matcher-time pv)))
  11021. (cond ((and regexp (eq po '/=))
  11022. `(not (string-match ,pv (or ,gv ""))))
  11023. (regexp `(string-match ,pv (or ,gv "")))
  11024. (strp `(,po (or ,gv "") ,pv))
  11025. (t
  11026. `(,po
  11027. (string-to-number (or ,gv ""))
  11028. ,(string-to-number pv))))))
  11029. (t `(member ,tag tags-list)))))
  11030. (push (if minus `(not ,mm) mm) tagsmatcher)
  11031. (setq term rest)))
  11032. (push `(and ,@tagsmatcher) orlist)
  11033. (setq tagsmatcher nil))
  11034. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  11035. ;; Make the TODO matcher.
  11036. (when (org-string-nw-p todomatch)
  11037. (let ((orlist nil))
  11038. (dolist (term (org-split-string todomatch "|"))
  11039. (while (string-match re term)
  11040. (let* ((minus (and (match-end 1)
  11041. (equal (match-string 1 term) "-")))
  11042. (kwd (match-string 2 term))
  11043. (regexp (eq (string-to-char kwd) ?{))
  11044. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  11045. `(equal todo ,kwd))))
  11046. (push (if minus `(not ,mm) mm) todomatcher))
  11047. (setq term (substring term (match-end 0))))
  11048. (push (if (> (length todomatcher) 1)
  11049. (cons 'and todomatcher)
  11050. (car todomatcher))
  11051. orlist)
  11052. (setq todomatcher nil))
  11053. (setq todomatcher (cons 'or orlist))))
  11054. ;; Return the string and function of the matcher. If no
  11055. ;; tags-specific or todo-specific matcher exists, match
  11056. ;; everything.
  11057. (let ((matcher (if (and tagsmatcher todomatcher)
  11058. `(and ,tagsmatcher ,todomatcher)
  11059. (or tagsmatcher todomatcher t))))
  11060. (when org--matcher-tags-todo-only
  11061. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  11062. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  11063. (defun org--tags-expand-group (group tag-groups expanded)
  11064. "Recursively Expand all tags in GROUP, according to TAG-GROUPS.
  11065. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  11066. an accumulator used in recursive calls."
  11067. (dolist (tag group)
  11068. (unless (member tag expanded)
  11069. (let ((group (assoc tag tag-groups)))
  11070. (push tag expanded)
  11071. (when group
  11072. (setq expanded
  11073. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  11074. expanded)
  11075. (defun org-tags-expand (match &optional single-as-list downcased)
  11076. "Expand group tags in MATCH.
  11077. This replaces every group tag in MATCH with a regexp tag search.
  11078. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  11079. will be replaced like this:
  11080. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  11081. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  11082. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  11083. Replacing by a regexp preserves the structure of the match.
  11084. E.g., this expansion
  11085. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  11086. will match anything tagged with \"Lab\" and \"Home\", or tagged
  11087. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  11088. A group tag in MATCH can contain regular expressions of its own.
  11089. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  11090. will be replaced like this:
  11091. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  11092. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  11093. assumed to be a single group tag, and the function will return
  11094. the list of tags in this group.
  11095. When DOWNCASED is non-nil, expand downcased TAGS."
  11096. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  11097. (let ((tag-groups
  11098. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  11099. (if (not downcased) g
  11100. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  11101. (cond
  11102. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  11103. (org-group-tags
  11104. (let* ((case-fold-search t)
  11105. (tag-syntax org-mode-syntax-table)
  11106. (group-keys (mapcar #'car tag-groups))
  11107. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  11108. (return-match (if downcased (downcase match) match)))
  11109. ;; Mark regexp-expressions in the match-expression so that we
  11110. ;; do not replace them later on.
  11111. (let ((s 0))
  11112. (while (string-match "{.+?}" return-match s)
  11113. (setq s (match-end 0))
  11114. (add-text-properties
  11115. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  11116. ;; @ and _ are allowed as word-components in tags.
  11117. (modify-syntax-entry ?@ "w" tag-syntax)
  11118. (modify-syntax-entry ?_ "w" tag-syntax)
  11119. ;; For each tag token found in MATCH, compute a regexp and it
  11120. (with-syntax-table tag-syntax
  11121. (replace-regexp-in-string
  11122. key-regexp
  11123. (lambda (m)
  11124. (if (get-text-property (match-beginning 2) 'regexp m)
  11125. m ;regexp tag: ignore
  11126. (let* ((operator (match-string 1 m))
  11127. (tag-token (let ((tag (match-string 2 m)))
  11128. (list (if downcased (downcase tag) tag))))
  11129. regexp-tags regular-tags)
  11130. ;; Partition tags between regexp and regular tags.
  11131. ;; Remove curly bracket syntax from regexp tags.
  11132. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  11133. (save-match-data
  11134. (if (string-match "{\\(.+?\\)}" tag)
  11135. (push (match-string 1 tag) regexp-tags)
  11136. (push tag regular-tags))))
  11137. ;; Replace tag token by the appropriate regexp.
  11138. ;; Regular tags need to be regexp-quoted, whereas
  11139. ;; regexp-tags are inserted as-is.
  11140. (let ((regular (regexp-opt regular-tags))
  11141. (regexp (mapconcat #'identity regexp-tags "\\|")))
  11142. (concat operator
  11143. (cond
  11144. ((null regular-tags) (format "{%s}" regexp))
  11145. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  11146. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  11147. return-match
  11148. t t))))
  11149. (t match))))
  11150. (defun org-op-to-function (op &optional stringp)
  11151. "Turn an operator into the appropriate function."
  11152. (setq op
  11153. (cond
  11154. ((equal op "<" ) '(< org-string< org-time<))
  11155. ((equal op ">" ) '(> org-string> org-time>))
  11156. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  11157. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  11158. ((member op '("=" "==")) '(= string= org-time=))
  11159. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  11160. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  11161. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  11162. (defvar org-tags-overlay (make-overlay 1 1))
  11163. (delete-overlay org-tags-overlay)
  11164. (defun org-add-prop-inherited (s)
  11165. (add-text-properties 0 (length s) '(inherited t) s)
  11166. s)
  11167. (defun org-toggle-tag (tag &optional onoff)
  11168. "Toggle the tag TAG for the current line.
  11169. If ONOFF is `on' or `off', don't toggle but set to this state."
  11170. (save-excursion
  11171. (org-back-to-heading t)
  11172. (let ((current
  11173. ;; Reverse the tags list so any new tag is appended to the
  11174. ;; current list of tags.
  11175. (nreverse (org-get-tags nil t)))
  11176. res)
  11177. (pcase onoff
  11178. (`off (setq current (delete tag current)))
  11179. ((or `on (guard (not (member tag current))))
  11180. (setq res t)
  11181. (cl-pushnew tag current :test #'equal))
  11182. (_ (setq current (delete tag current))))
  11183. (org-set-tags (nreverse current))
  11184. res)))
  11185. (defun org--align-tags-here (to-col)
  11186. "Align tags on the current headline to TO-COL.
  11187. Assume point is on a headline. Preserve point when aligning
  11188. tags."
  11189. (when (org-match-line org-tag-line-re)
  11190. (let* ((tags-start (match-beginning 1))
  11191. (blank-start (save-excursion
  11192. (goto-char tags-start)
  11193. (skip-chars-backward " \t")
  11194. (point)))
  11195. (new (max (if (>= to-col 0) to-col
  11196. (- (abs to-col) (string-width (match-string 1))))
  11197. ;; Introduce at least one space after the heading
  11198. ;; or the stars.
  11199. (save-excursion
  11200. (goto-char blank-start)
  11201. (1+ (current-column)))))
  11202. (current
  11203. (save-excursion (goto-char tags-start) (current-column)))
  11204. (origin (point-marker))
  11205. (column (current-column))
  11206. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  11207. (when (/= new current)
  11208. (delete-region blank-start tags-start)
  11209. (goto-char blank-start)
  11210. (let ((indent-tabs-mode nil)) (indent-to new))
  11211. ;; Try to move back to original position. If point was in the
  11212. ;; blanks before the tags, ORIGIN marker is of no use because
  11213. ;; it now points to BLANK-START. Use COLUMN instead.
  11214. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  11215. (defun org-set-tags-command (&optional arg)
  11216. "Set the tags for the current visible entry.
  11217. When called with `\\[universal-argument]' prefix argument ARG, \
  11218. realign all tags
  11219. in the current buffer.
  11220. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  11221. unconditionally do not
  11222. offer the fast tag selection interface.
  11223. If a region is active, set tags in the region according to the
  11224. setting of `org-loop-over-headlines-in-active-region'.
  11225. This function is for interactive use only;
  11226. in Lisp code use `org-set-tags' instead."
  11227. (interactive "P")
  11228. (let ((org-use-fast-tag-selection
  11229. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  11230. (cond
  11231. ((equal '(4) arg) (org-align-tags t))
  11232. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11233. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  11234. (org-map-entries
  11235. #'org-set-tags-command
  11236. nil
  11237. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11238. 'region-start-level
  11239. 'region)
  11240. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  11241. (t
  11242. (save-excursion
  11243. (org-back-to-heading)
  11244. (let* ((all-tags (org-get-tags))
  11245. (table (setq org-last-tags-completion-table
  11246. (org--tag-add-to-alist
  11247. (and org-complete-tags-always-offer-all-agenda-tags
  11248. (org-global-tags-completion-table
  11249. (org-agenda-files)))
  11250. (or org-current-tag-alist (org-get-buffer-tags)))))
  11251. (current-tags
  11252. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  11253. all-tags))
  11254. (inherited-tags
  11255. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  11256. all-tags))
  11257. (tags
  11258. (replace-regexp-in-string
  11259. ;; Ignore all forbidden characters in tags.
  11260. "[^[:alnum:]_@#%]+" ":"
  11261. (if (or (eq t org-use-fast-tag-selection)
  11262. (and org-use-fast-tag-selection
  11263. (delq nil (mapcar #'cdr table))))
  11264. (org-fast-tag-selection
  11265. current-tags
  11266. inherited-tags
  11267. table
  11268. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  11269. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  11270. (org-trim (completing-read
  11271. "Tags: "
  11272. #'org-tags-completion-function
  11273. nil nil (org-make-tag-string current-tags)
  11274. 'org-tags-history)))))))
  11275. (org-set-tags tags)))))))
  11276. (defun org-align-tags (&optional all)
  11277. "Align tags in current entry.
  11278. When optional argument ALL is non-nil, align all tags in the
  11279. visible part of the buffer."
  11280. (let ((get-indent-column
  11281. (lambda ()
  11282. (let ((offset (if (bound-and-true-p org-indent-mode)
  11283. (* (1- org-indent-indentation-per-level)
  11284. (1- (org-current-level)))
  11285. 0)))
  11286. (+ org-tags-column
  11287. (if (> org-tags-column 0) (- offset) offset))))))
  11288. (if (and (not all) (org-at-heading-p))
  11289. (org--align-tags-here (funcall get-indent-column))
  11290. (save-excursion
  11291. (if all
  11292. (progn
  11293. (goto-char (point-min))
  11294. (while (re-search-forward org-tag-line-re nil t)
  11295. (org--align-tags-here (funcall get-indent-column))))
  11296. (org-back-to-heading t)
  11297. (org--align-tags-here (funcall get-indent-column)))))))
  11298. (defun org-set-tags (tags)
  11299. "Set the tags of the current entry to TAGS, replacing current tags.
  11300. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  11301. If TAGS is nil or the empty string, all tags are removed.
  11302. This function assumes point is on a headline."
  11303. (org-with-wide-buffer
  11304. (let ((tags (pcase tags
  11305. ((pred listp) tags)
  11306. ((pred stringp) (split-string (org-trim tags) ":" t))
  11307. (_ (error "Invalid tag specification: %S" tags))))
  11308. (old-tags (org-get-tags nil t))
  11309. (tags-change? nil))
  11310. (when (functionp org-tags-sort-function)
  11311. (setq tags (sort tags org-tags-sort-function)))
  11312. (setq tags-change? (not (equal tags old-tags)))
  11313. (when tags-change?
  11314. ;; Delete previous tags and any trailing white space.
  11315. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  11316. (line-end-position)))
  11317. (skip-chars-backward " \t")
  11318. (delete-region (point) (line-end-position))
  11319. ;; Deleting white spaces may break an otherwise empty headline.
  11320. ;; Re-introduce one space in this case.
  11321. (unless (org-at-heading-p) (insert " "))
  11322. (when tags
  11323. (save-excursion (insert " " (org-make-tag-string tags)))
  11324. ;; When text is being inserted on an invisible region
  11325. ;; boundary, it can be inadvertently sucked into
  11326. ;; invisibility.
  11327. (unless (org-invisible-p (line-beginning-position))
  11328. (org-flag-region (point) (line-end-position) nil 'outline))))
  11329. ;; Align tags, if any.
  11330. (when tags (org-align-tags))
  11331. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  11332. (defun org-change-tag-in-region (beg end tag off)
  11333. "Add or remove TAG for each entry in the region.
  11334. This works in the agenda, and also in an Org buffer."
  11335. (interactive
  11336. (list (region-beginning) (region-end)
  11337. (let ((org-last-tags-completion-table
  11338. (if (derived-mode-p 'org-mode)
  11339. (org--tag-add-to-alist
  11340. (org-get-buffer-tags)
  11341. (org-global-tags-completion-table))
  11342. (org-global-tags-completion-table))))
  11343. (completing-read
  11344. "Tag: " 'org-tags-completion-function nil nil nil
  11345. 'org-tags-history))
  11346. (progn
  11347. (message "[s]et or [r]emove? ")
  11348. (equal (read-char-exclusive) ?r))))
  11349. (when (fboundp 'deactivate-mark) (deactivate-mark))
  11350. (let ((agendap (equal major-mode 'org-agenda-mode))
  11351. l1 l2 m buf pos newhead (cnt 0))
  11352. (goto-char end)
  11353. (setq l2 (1- (org-current-line)))
  11354. (goto-char beg)
  11355. (setq l1 (org-current-line))
  11356. (cl-loop for l from l1 to l2 do
  11357. (org-goto-line l)
  11358. (setq m (get-text-property (point) 'org-hd-marker))
  11359. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  11360. (and agendap m))
  11361. (setq buf (if agendap (marker-buffer m) (current-buffer))
  11362. pos (if agendap m (point)))
  11363. (with-current-buffer buf
  11364. (save-excursion
  11365. (save-restriction
  11366. (goto-char pos)
  11367. (setq cnt (1+ cnt))
  11368. (org-toggle-tag tag (if off 'off 'on))
  11369. (setq newhead (org-get-heading)))))
  11370. (and agendap (org-agenda-change-all-lines newhead m))))
  11371. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  11372. (defun org-tags-completion-function (string _predicate &optional flag)
  11373. "Complete tag STRING.
  11374. FLAG specifies the type of completion operation to perform. This
  11375. function is passed as a collection function to `completing-read',
  11376. which see."
  11377. (let ((completion-ignore-case nil) ;tags are case-sensitive
  11378. (confirm (lambda (x) (stringp (car x))))
  11379. (prefix ""))
  11380. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  11381. (setq prefix (match-string 1 string))
  11382. (setq string (match-string 2 string)))
  11383. (pcase flag
  11384. (`t (all-completions string org-last-tags-completion-table confirm))
  11385. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  11386. (`nil
  11387. (pcase (try-completion string org-last-tags-completion-table confirm)
  11388. ((and completion (pred stringp))
  11389. (concat prefix
  11390. completion
  11391. (if (and org-add-colon-after-tag-completion
  11392. (assoc completion org-last-tags-completion-table))
  11393. ":"
  11394. "")))
  11395. (completion completion)))
  11396. (_ nil))))
  11397. (defun org-fast-tag-insert (kwd tags face &optional end)
  11398. "Insert KWD, and the TAGS, the latter with face FACE.
  11399. Also insert END."
  11400. (insert (format "%-12s" (concat kwd ":"))
  11401. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  11402. (or end "")))
  11403. (defun org-fast-tag-show-exit (flag)
  11404. (save-excursion
  11405. (org-goto-line 3)
  11406. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  11407. (replace-match ""))
  11408. (when flag
  11409. (end-of-line 1)
  11410. (org-move-to-column (- (window-width) 19) t)
  11411. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  11412. (defun org-set-current-tags-overlay (current prefix)
  11413. "Add an overlay to CURRENT tag with PREFIX."
  11414. (let ((s (org-make-tag-string current)))
  11415. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  11416. (org-overlay-display org-tags-overlay (concat prefix s))))
  11417. (defvar org-last-tag-selection-key nil)
  11418. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  11419. "Fast tag selection with single keys.
  11420. CURRENT is the current list of tags in the headline, INHERITED is the
  11421. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  11422. possibly with grouping information. TODO-TABLE is a similar table with
  11423. TODO keywords, should these have keys assigned to them.
  11424. If the keys are nil, a-z are automatically assigned.
  11425. Returns the new tags string, or nil to not change the current settings."
  11426. (let* ((fulltable (append table todo-table))
  11427. (maxlen (if (null fulltable) 0
  11428. (apply #'max
  11429. (mapcar (lambda (x)
  11430. (if (stringp (car x)) (string-width (car x))
  11431. 0))
  11432. fulltable))))
  11433. (buf (current-buffer))
  11434. (expert (eq org-fast-tag-selection-single-key 'expert))
  11435. (buffer-tags nil)
  11436. (fwidth (+ maxlen 3 1 3))
  11437. (ncol (/ (- (window-width) 4) fwidth))
  11438. (i-face 'org-done)
  11439. (c-face 'org-todo)
  11440. tg cnt e c char c1 c2 ntable tbl rtn
  11441. ov-start ov-end ov-prefix
  11442. (exit-after-next org-fast-tag-selection-single-key)
  11443. (done-keywords org-done-keywords)
  11444. groups ingroup intaggroup)
  11445. (save-excursion
  11446. (beginning-of-line)
  11447. (if (looking-at org-tag-line-re)
  11448. (setq ov-start (match-beginning 1)
  11449. ov-end (match-end 1)
  11450. ov-prefix "")
  11451. (setq ov-start (1- (point-at-eol))
  11452. ov-end (1+ ov-start))
  11453. (skip-chars-forward "^\n\r")
  11454. (setq ov-prefix
  11455. (concat
  11456. (buffer-substring (1- (point)) (point))
  11457. (if (> (current-column) org-tags-column)
  11458. " "
  11459. (make-string (- org-tags-column (current-column)) ?\ ))))))
  11460. (move-overlay org-tags-overlay ov-start ov-end)
  11461. (save-excursion
  11462. (save-window-excursion
  11463. (if expert
  11464. (set-buffer (get-buffer-create " *Org tags*"))
  11465. (delete-other-windows)
  11466. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  11467. (org-switch-to-buffer-other-window " *Org tags*"))
  11468. (erase-buffer)
  11469. (setq-local org-done-keywords done-keywords)
  11470. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  11471. (org-fast-tag-insert "Current" current c-face "\n\n")
  11472. (org-fast-tag-show-exit exit-after-next)
  11473. (org-set-current-tags-overlay current ov-prefix)
  11474. (setq tbl fulltable char ?a cnt 0)
  11475. (while (setq e (pop tbl))
  11476. (cond
  11477. ((eq (car e) :startgroup)
  11478. (push '() groups) (setq ingroup t)
  11479. (unless (zerop cnt)
  11480. (setq cnt 0)
  11481. (insert "\n"))
  11482. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11483. ((eq (car e) :endgroup)
  11484. (setq ingroup nil cnt 0)
  11485. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11486. ((eq (car e) :startgrouptag)
  11487. (setq intaggroup t)
  11488. (unless (zerop cnt)
  11489. (setq cnt 0)
  11490. (insert "\n"))
  11491. (insert "[ "))
  11492. ((eq (car e) :endgrouptag)
  11493. (setq intaggroup nil cnt 0)
  11494. (insert "]\n"))
  11495. ((equal e '(:newline))
  11496. (unless (zerop cnt)
  11497. (setq cnt 0)
  11498. (insert "\n")
  11499. (setq e (car tbl))
  11500. (while (equal (car tbl) '(:newline))
  11501. (insert "\n")
  11502. (setq tbl (cdr tbl)))))
  11503. ((equal e '(:grouptags)) (insert " : "))
  11504. (t
  11505. (setq tg (copy-sequence (car e)) c2 nil)
  11506. (if (cdr e)
  11507. (setq c (cdr e))
  11508. ;; automatically assign a character.
  11509. (setq c1 (string-to-char
  11510. (downcase (substring
  11511. tg (if (= (string-to-char tg) ?@) 1 0)))))
  11512. (if (or (rassoc c1 ntable) (rassoc c1 table))
  11513. (while (or (rassoc char ntable) (rassoc char table))
  11514. (setq char (1+ char)))
  11515. (setq c2 c1))
  11516. (setq c (or c2 char)))
  11517. (when ingroup (push tg (car groups)))
  11518. (setq tg (org-add-props tg nil 'face
  11519. (cond
  11520. ((not (assoc tg table))
  11521. (org-get-todo-face tg))
  11522. ((member tg current) c-face)
  11523. ((member tg inherited) i-face))))
  11524. (when (equal (caar tbl) :grouptags)
  11525. (org-add-props tg nil 'face 'org-tag-group))
  11526. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  11527. (insert "[" c "] " tg (make-string
  11528. (- fwidth 4 (length tg)) ?\ ))
  11529. (push (cons tg c) ntable)
  11530. (when (= (cl-incf cnt) ncol)
  11531. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11532. (insert "\n")
  11533. (when (or ingroup intaggroup) (insert " ")))
  11534. (setq cnt 0)))))
  11535. (setq ntable (nreverse ntable))
  11536. (insert "\n")
  11537. (goto-char (point-min))
  11538. (unless expert (org-fit-window-to-buffer))
  11539. (setq rtn
  11540. (catch 'exit
  11541. (while t
  11542. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11543. (if (not groups) "no " "")
  11544. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11545. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11546. (setq org-last-tag-selection-key c)
  11547. (cond
  11548. ((= c ?\r) (throw 'exit t))
  11549. ((= c ?!)
  11550. (setq groups (not groups))
  11551. (goto-char (point-min))
  11552. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11553. ((= c ?\C-c)
  11554. (if (not expert)
  11555. (org-fast-tag-show-exit
  11556. (setq exit-after-next (not exit-after-next)))
  11557. (setq expert nil)
  11558. (delete-other-windows)
  11559. (set-window-buffer (split-window-vertically) " *Org tags*")
  11560. (org-switch-to-buffer-other-window " *Org tags*")
  11561. (org-fit-window-to-buffer)))
  11562. ((or (= c ?\C-g)
  11563. (and (= c ?q) (not (rassoc c ntable))))
  11564. (delete-overlay org-tags-overlay)
  11565. (setq quit-flag t))
  11566. ((= c ?\ )
  11567. (setq current nil)
  11568. (when exit-after-next (setq exit-after-next 'now)))
  11569. ((= c ?\t)
  11570. (condition-case nil
  11571. (setq tg (completing-read
  11572. "Tag: "
  11573. (or buffer-tags
  11574. (with-current-buffer buf
  11575. (setq buffer-tags
  11576. (org-get-buffer-tags))))))
  11577. (quit (setq tg "")))
  11578. (when (string-match "\\S-" tg)
  11579. (cl-pushnew (list tg) buffer-tags :test #'equal)
  11580. (if (member tg current)
  11581. (setq current (delete tg current))
  11582. (push tg current)))
  11583. (when exit-after-next (setq exit-after-next 'now)))
  11584. ((setq e (rassoc c todo-table) tg (car e))
  11585. (with-current-buffer buf
  11586. (save-excursion (org-todo tg)))
  11587. (when exit-after-next (setq exit-after-next 'now)))
  11588. ((setq e (rassoc c ntable) tg (car e))
  11589. (if (member tg current)
  11590. (setq current (delete tg current))
  11591. (cl-loop for g in groups do
  11592. (when (member tg g)
  11593. (dolist (x g) (setq current (delete x current)))))
  11594. (push tg current))
  11595. (when exit-after-next (setq exit-after-next 'now))))
  11596. ;; Create a sorted list
  11597. (setq current
  11598. (sort current
  11599. (lambda (a b)
  11600. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11601. (when (eq exit-after-next 'now) (throw 'exit t))
  11602. (goto-char (point-min))
  11603. (beginning-of-line 2)
  11604. (delete-region (point) (point-at-eol))
  11605. (org-fast-tag-insert "Current" current c-face)
  11606. (org-set-current-tags-overlay current ov-prefix)
  11607. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11608. (while (re-search-forward tag-re nil t)
  11609. (let ((tag (match-string 1)))
  11610. (add-text-properties
  11611. (match-beginning 1) (match-end 1)
  11612. (list 'face
  11613. (cond
  11614. ((member tag current) c-face)
  11615. ((member tag inherited) i-face)
  11616. (t (get-text-property (match-beginning 1) '
  11617. face))))))))
  11618. (goto-char (point-min)))))
  11619. (delete-overlay org-tags-overlay)
  11620. (if rtn
  11621. (mapconcat 'identity current ":")
  11622. nil)))))
  11623. (defun org-make-tag-string (tags)
  11624. "Return string associated to TAGS.
  11625. TAGS is a list of strings."
  11626. (if (null tags) ""
  11627. (format ":%s:" (mapconcat #'identity tags ":"))))
  11628. (defun org--get-local-tags ()
  11629. "Return list of tags for the current headline.
  11630. Assume point is at the beginning of the headline."
  11631. (and (looking-at org-tag-line-re)
  11632. (split-string (match-string-no-properties 2) ":" t)))
  11633. (defun org-get-tags (&optional pos local)
  11634. "Get the list of tags specified in the current headline.
  11635. When argument POS is non-nil, retrieve tags for headline at POS.
  11636. According to `org-use-tag-inheritance', tags may be inherited
  11637. from parent headlines, and from the whole document, through
  11638. `org-file-tags'. In this case, the returned list of tags
  11639. contains tags in this order: file tags, tags inherited from
  11640. parent headlines, local tags.
  11641. However, when optional argument LOCAL is non-nil, only return
  11642. tags specified at the headline.
  11643. Inherited tags have the `inherited' text property."
  11644. (if (and org-trust-scanner-tags
  11645. (or (not pos) (eq pos (point)))
  11646. (not local))
  11647. org-scanner-tags
  11648. (org-with-point-at (or pos (point))
  11649. (unless (org-before-first-heading-p)
  11650. (org-back-to-heading t)
  11651. (let ((ltags (org--get-local-tags)) itags)
  11652. (if (or local (not org-use-tag-inheritance)) ltags
  11653. (while (org-up-heading-safe)
  11654. (setq itags (append (mapcar #'org-add-prop-inherited
  11655. (org--get-local-tags))
  11656. itags)))
  11657. (setq itags (append org-file-tags itags))
  11658. (delete-dups
  11659. (append (org-remove-uninherited-tags itags) ltags))))))))
  11660. (defun org-get-buffer-tags ()
  11661. "Get a table of all tags used in the buffer, for completion."
  11662. (org-with-point-at 1
  11663. (let (tags)
  11664. (while (re-search-forward org-tag-line-re nil t)
  11665. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11666. tags)))
  11667. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11668. ;;;; The mapping API
  11669. (defvar org-agenda-skip-comment-trees)
  11670. (defvar org-agenda-skip-function)
  11671. (defun org-map-entries (func &optional match scope &rest skip)
  11672. "Call FUNC at each headline selected by MATCH in SCOPE.
  11673. FUNC is a function or a lisp form. The function will be called without
  11674. arguments, with the cursor positioned at the beginning of the headline.
  11675. The return values of all calls to the function will be collected and
  11676. returned as a list.
  11677. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  11678. does not need to preserve point. After evaluation, the cursor will be
  11679. moved to the end of the line (presumably of the headline of the
  11680. processed entry) and search continues from there. Under some
  11681. circumstances, this may not produce the wanted results. For example,
  11682. if you have removed (e.g. archived) the current (sub)tree it could
  11683. mean that the next entry will be skipped entirely. In such cases, you
  11684. can specify the position from where search should continue by making
  11685. FUNC set the variable `org-map-continue-from' to the desired buffer
  11686. position.
  11687. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11688. Only headlines that are matched by this query will be considered during
  11689. the iteration. When MATCH is nil or t, all headlines will be
  11690. visited by the iteration.
  11691. SCOPE determines the scope of this command. It can be any of:
  11692. nil The current buffer, respecting the restriction if any
  11693. tree The subtree started with the entry at point
  11694. region The entries within the active region, if any
  11695. region-start-level
  11696. The entries within the active region, but only those at
  11697. the same level than the first one.
  11698. file The current buffer, without restriction
  11699. file-with-archives
  11700. The current buffer, and any archives associated with it
  11701. agenda All agenda files
  11702. agenda-with-archives
  11703. All agenda files with any archive files associated with them
  11704. \(file1 file2 ...)
  11705. If this is a list, all files in the list will be scanned
  11706. The remaining args are treated as settings for the skipping facilities of
  11707. the scanner. The following items can be given here:
  11708. archive skip trees with the archive tag
  11709. comment skip trees with the COMMENT keyword
  11710. function or Emacs Lisp form:
  11711. will be used as value for `org-agenda-skip-function', so
  11712. whenever the function returns a position, FUNC will not be
  11713. called for that entry and search will continue from the
  11714. position returned
  11715. If your function needs to retrieve the tags including inherited tags
  11716. at the *current* entry, you can use the value of the variable
  11717. `org-scanner-tags' which will be much faster than getting the value
  11718. with `org-get-tags'. If your function gets properties with
  11719. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11720. to t around the call to `org-entry-properties' to get the same speedup.
  11721. Note that if your function moves around to retrieve tags and properties at
  11722. a *different* entry, you cannot use these techniques."
  11723. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11724. (not (org-region-active-p)))
  11725. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11726. (org-agenda-skip-archived-trees (memq 'archive skip))
  11727. (org-agenda-skip-comment-trees (memq 'comment skip))
  11728. (org-agenda-skip-function
  11729. (car (org-delete-all '(comment archive) skip)))
  11730. (org-tags-match-list-sublevels t)
  11731. (start-level (eq scope 'region-start-level))
  11732. matcher res
  11733. org-todo-keywords-for-agenda
  11734. org-done-keywords-for-agenda
  11735. org-todo-keyword-alist-for-agenda
  11736. org-tag-alist-for-agenda
  11737. org--matcher-tags-todo-only)
  11738. (cond
  11739. ((eq match t) (setq matcher t))
  11740. ((eq match nil) (setq matcher t))
  11741. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11742. (save-excursion
  11743. (save-restriction
  11744. (cond ((eq scope 'tree)
  11745. (org-back-to-heading t)
  11746. (org-narrow-to-subtree)
  11747. (setq scope nil))
  11748. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11749. (org-region-active-p))
  11750. ;; If needed, set start-level to a string like "2"
  11751. (when start-level
  11752. (save-excursion
  11753. (goto-char (region-beginning))
  11754. (unless (org-at-heading-p) (outline-next-heading))
  11755. (setq start-level (org-current-level))))
  11756. (narrow-to-region (region-beginning)
  11757. (save-excursion
  11758. (goto-char (region-end))
  11759. (unless (and (bolp) (org-at-heading-p))
  11760. (outline-next-heading))
  11761. (point)))
  11762. (setq scope nil)))
  11763. (if (not scope)
  11764. (progn
  11765. (org-agenda-prepare-buffers
  11766. (and buffer-file-name (list buffer-file-name)))
  11767. (setq res
  11768. (org-scan-tags
  11769. func matcher org--matcher-tags-todo-only start-level)))
  11770. ;; Get the right scope
  11771. (cond
  11772. ((and scope (listp scope) (symbolp (car scope)))
  11773. (setq scope (eval scope)))
  11774. ((eq scope 'agenda)
  11775. (setq scope (org-agenda-files t)))
  11776. ((eq scope 'agenda-with-archives)
  11777. (setq scope (org-agenda-files t))
  11778. (setq scope (org-add-archive-files scope)))
  11779. ((eq scope 'file)
  11780. (setq scope (and buffer-file-name (list buffer-file-name))))
  11781. ((eq scope 'file-with-archives)
  11782. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11783. (org-agenda-prepare-buffers scope)
  11784. (dolist (file scope)
  11785. (with-current-buffer (org-find-base-buffer-visiting file)
  11786. (org-with-wide-buffer
  11787. (goto-char (point-min))
  11788. (setq res
  11789. (append
  11790. res
  11791. (org-scan-tags
  11792. func matcher org--matcher-tags-todo-only)))))))))
  11793. res)))
  11794. ;;; Properties API
  11795. (defconst org-special-properties
  11796. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11797. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11798. "The special properties valid in Org mode.
  11799. These are properties that are not defined in the property drawer,
  11800. but in some other way.")
  11801. (defconst org-default-properties
  11802. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11803. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11804. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11805. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11806. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11807. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11808. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11809. "Some properties that are used by Org mode for various purposes.
  11810. Being in this list makes sure that they are offered for completion.")
  11811. (defun org--valid-property-p (property)
  11812. "Non-nil when string PROPERTY is a valid property name."
  11813. (not
  11814. (or (equal property "")
  11815. (string-match-p "\\s-" property))))
  11816. (defun org--update-property-plist (key val props)
  11817. "Associate KEY to VAL in alist PROPS.
  11818. Modifications are made by side-effect. Return new alist."
  11819. (let* ((appending (string= (substring key -1) "+"))
  11820. (key (if appending (substring key 0 -1) key))
  11821. (old (assoc-string key props t)))
  11822. (if (not old) (cons (cons key val) props)
  11823. (setcdr old (if appending (concat (cdr old) " " val) val))
  11824. props)))
  11825. (defun org-get-property-block (&optional beg force)
  11826. "Return the (beg . end) range of the body of the property drawer.
  11827. BEG is the beginning of the current subtree or the beginning of
  11828. the document if before the first headline. If it is not given,
  11829. it will be found. If the drawer does not exist, create it if
  11830. FORCE is non-nil, or return nil."
  11831. (org-with-wide-buffer
  11832. (let ((beg (cond (beg (goto-char beg))
  11833. ((or (not (featurep 'org-inlinetask))
  11834. (org-inlinetask-in-task-p))
  11835. (org-back-to-heading-or-point-min t) (point))
  11836. (t (org-with-limited-levels
  11837. (org-back-to-heading-or-point-min t))
  11838. (point)))))
  11839. ;; Move point to its position according to its positional rules.
  11840. (cond ((org-before-first-heading-p)
  11841. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11842. (t (forward-line)
  11843. (when (looking-at-p org-planning-line-re) (forward-line))))
  11844. (cond ((looking-at org-property-drawer-re)
  11845. (forward-line)
  11846. (cons (point) (progn (goto-char (match-end 0))
  11847. (line-beginning-position))))
  11848. (force
  11849. (goto-char beg)
  11850. (org-insert-property-drawer)
  11851. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11852. (line-beginning-position))))
  11853. (cons pos pos)))))))
  11854. (defun org-at-property-block-p ()
  11855. "Return t when point is at the first line of a property drawer.
  11856. The property drawer is validated according to its positional
  11857. rules using `org-get-property-block'."
  11858. (save-excursion
  11859. (beginning-of-line)
  11860. (and (looking-at org-property-start-re)
  11861. (forward-line)
  11862. (let ((property-drawer (org-get-property-block)))
  11863. (and property-drawer
  11864. (= (point) (car property-drawer)))))))
  11865. (defun org-at-property-p ()
  11866. "Non-nil when point is inside a property drawer.
  11867. See `org-property-re' for match data, if applicable."
  11868. (save-excursion
  11869. (beginning-of-line)
  11870. (and (looking-at org-property-re)
  11871. (let ((property-drawer (save-match-data (org-get-property-block))))
  11872. (and property-drawer
  11873. (>= (point) (car property-drawer))
  11874. (< (point) (cdr property-drawer)))))))
  11875. (defun org-property-action ()
  11876. "Do an action on properties."
  11877. (interactive)
  11878. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11879. (let ((c (read-char-exclusive)))
  11880. (cl-case c
  11881. (?s (call-interactively #'org-set-property))
  11882. (?d (call-interactively #'org-delete-property))
  11883. (?D (call-interactively #'org-delete-property-globally))
  11884. (?c (call-interactively #'org-compute-property-at-point))
  11885. (otherwise (user-error "No such property action %c" c)))))
  11886. (defun org-inc-effort ()
  11887. "Increment the value of the effort property in the current entry."
  11888. (interactive)
  11889. (org-set-effort t))
  11890. (defvar org-clock-effort) ; Defined in org-clock.el.
  11891. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11892. (defun org-set-effort (&optional increment value)
  11893. "Set the effort property of the current entry.
  11894. If INCREMENT is non-nil, set the property to the next allowed
  11895. value. Otherwise, if optional argument VALUE is provided, use
  11896. it. Eventually, prompt for the new value if none of the previous
  11897. variables is set."
  11898. (interactive "P")
  11899. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11900. (current (org-entry-get nil org-effort-property))
  11901. (value
  11902. (cond
  11903. (increment
  11904. (unless allowed (user-error "Allowed effort values are not set"))
  11905. (or (cl-caadr (member (list current) allowed))
  11906. (user-error "Unknown value %S among allowed values" current)))
  11907. (value
  11908. (if (stringp value) value
  11909. (error "Invalid effort value: %S" value)))
  11910. (t
  11911. (let ((must-match
  11912. (and allowed
  11913. (not (get-text-property 0 'org-unrestricted
  11914. (caar allowed))))))
  11915. (completing-read "Effort: " allowed nil must-match))))))
  11916. (unless (equal current value)
  11917. (org-entry-put nil org-effort-property value))
  11918. (org-refresh-property '((effort . identity)
  11919. (effort-minutes . org-duration-to-minutes))
  11920. value)
  11921. (when (equal (org-get-heading t t t t)
  11922. (bound-and-true-p org-clock-current-task))
  11923. (setq org-clock-effort value)
  11924. (org-clock-update-mode-line))
  11925. (message "%s is now %s" org-effort-property value)))
  11926. (defun org-entry-properties (&optional pom which)
  11927. "Get all properties of the current entry.
  11928. When POM is a buffer position, get all properties from the entry
  11929. there instead.
  11930. This includes the TODO keyword, the tags, time strings for
  11931. deadline, scheduled, and clocking, and any additional properties
  11932. defined in the entry.
  11933. If WHICH is nil or `all', get all properties. If WHICH is
  11934. `special' or `standard', only get that subclass. If WHICH is
  11935. a string, only get that property.
  11936. Return value is an alist. Keys are properties, as upcased
  11937. strings."
  11938. (org-with-point-at pom
  11939. (when (and (derived-mode-p 'org-mode)
  11940. (org-back-to-heading-or-point-min t))
  11941. (catch 'exit
  11942. (let* ((beg (point))
  11943. (specific (and (stringp which) (upcase which)))
  11944. (which (cond ((not specific) which)
  11945. ((member specific org-special-properties) 'special)
  11946. (t 'standard)))
  11947. props)
  11948. ;; Get the special properties, like TODO and TAGS.
  11949. (when (memq which '(nil all special))
  11950. (when (or (not specific) (string= specific "CLOCKSUM"))
  11951. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11952. (when clocksum
  11953. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11954. props)))
  11955. (when specific (throw 'exit props)))
  11956. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11957. (let ((clocksumt (get-text-property (point)
  11958. :org-clock-minutes-today)))
  11959. (when clocksumt
  11960. (push (cons "CLOCKSUM_T"
  11961. (org-duration-from-minutes clocksumt))
  11962. props)))
  11963. (when specific (throw 'exit props)))
  11964. (when (or (not specific) (string= specific "ITEM"))
  11965. (let ((case-fold-search nil))
  11966. (when (looking-at org-complex-heading-regexp)
  11967. (push (cons "ITEM"
  11968. (let ((title (match-string-no-properties 4)))
  11969. (if (org-string-nw-p title)
  11970. (org-remove-tabs title)
  11971. "")))
  11972. props)))
  11973. (when specific (throw 'exit props)))
  11974. (when (or (not specific) (string= specific "TODO"))
  11975. (let ((case-fold-search nil))
  11976. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11977. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11978. (when specific (throw 'exit props)))
  11979. (when (or (not specific) (string= specific "PRIORITY"))
  11980. (push (cons "PRIORITY"
  11981. (if (looking-at org-priority-regexp)
  11982. (match-string-no-properties 2)
  11983. (char-to-string org-priority-default)))
  11984. props)
  11985. (when specific (throw 'exit props)))
  11986. (when (or (not specific) (string= specific "FILE"))
  11987. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11988. props)
  11989. (when specific (throw 'exit props)))
  11990. (when (or (not specific) (string= specific "TAGS"))
  11991. (let ((tags (org-get-tags nil t)))
  11992. (when tags
  11993. (push (cons "TAGS" (org-make-tag-string tags))
  11994. props)))
  11995. (when specific (throw 'exit props)))
  11996. (when (or (not specific) (string= specific "ALLTAGS"))
  11997. (let ((tags (org-get-tags)))
  11998. (when tags
  11999. (push (cons "ALLTAGS" (org-make-tag-string tags))
  12000. props)))
  12001. (when specific (throw 'exit props)))
  12002. (when (or (not specific) (string= specific "BLOCKED"))
  12003. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  12004. (when specific (throw 'exit props)))
  12005. (when (or (not specific)
  12006. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  12007. (forward-line)
  12008. (when (looking-at-p org-planning-line-re)
  12009. (end-of-line)
  12010. (let ((bol (line-beginning-position))
  12011. ;; Backward compatibility: time keywords used to
  12012. ;; be configurable (before 8.3). Make sure we
  12013. ;; get the correct keyword.
  12014. (key-assoc `(("CLOSED" . ,org-closed-string)
  12015. ("DEADLINE" . ,org-deadline-string)
  12016. ("SCHEDULED" . ,org-scheduled-string))))
  12017. (dolist (pair (if specific (list (assoc specific key-assoc))
  12018. key-assoc))
  12019. (save-excursion
  12020. (when (search-backward (cdr pair) bol t)
  12021. (goto-char (match-end 0))
  12022. (skip-chars-forward " \t")
  12023. (and (looking-at org-ts-regexp-both)
  12024. (push (cons (car pair)
  12025. (match-string-no-properties 0))
  12026. props)))))))
  12027. (when specific (throw 'exit props)))
  12028. (when (or (not specific)
  12029. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  12030. (let ((find-ts
  12031. (lambda (end ts)
  12032. ;; Fix next time-stamp before END. TS is the
  12033. ;; list of time-stamps found so far.
  12034. (let ((ts ts)
  12035. (regexp (cond
  12036. ((string= specific "TIMESTAMP")
  12037. org-ts-regexp)
  12038. ((string= specific "TIMESTAMP_IA")
  12039. org-ts-regexp-inactive)
  12040. ((assoc "TIMESTAMP_IA" ts)
  12041. org-ts-regexp)
  12042. ((assoc "TIMESTAMP" ts)
  12043. org-ts-regexp-inactive)
  12044. (t org-ts-regexp-both))))
  12045. (catch 'next
  12046. (while (re-search-forward regexp end t)
  12047. (backward-char)
  12048. (let ((object (org-element-context)))
  12049. ;; Accept to match timestamps in node
  12050. ;; properties, too.
  12051. (when (memq (org-element-type object)
  12052. '(node-property timestamp))
  12053. (let ((type
  12054. (org-element-property :type object)))
  12055. (cond
  12056. ((and (memq type '(active active-range))
  12057. (not (equal specific "TIMESTAMP_IA")))
  12058. (unless (assoc "TIMESTAMP" ts)
  12059. (push (cons "TIMESTAMP"
  12060. (org-element-property
  12061. :raw-value object))
  12062. ts)
  12063. (when specific (throw 'exit ts))))
  12064. ((and (memq type '(inactive inactive-range))
  12065. (not (string= specific "TIMESTAMP")))
  12066. (unless (assoc "TIMESTAMP_IA" ts)
  12067. (push (cons "TIMESTAMP_IA"
  12068. (org-element-property
  12069. :raw-value object))
  12070. ts)
  12071. (when specific (throw 'exit ts))))))
  12072. ;; Both timestamp types are found,
  12073. ;; move to next part.
  12074. (when (= (length ts) 2) (throw 'next ts)))))
  12075. ts)))))
  12076. (goto-char beg)
  12077. ;; First look for timestamps within headline.
  12078. (let ((ts (funcall find-ts (line-end-position) nil)))
  12079. (if (= (length ts) 2) (setq props (nconc ts props))
  12080. ;; Then find timestamps in the section, skipping
  12081. ;; planning line.
  12082. (let ((end (save-excursion (outline-next-heading))))
  12083. (forward-line)
  12084. (when (looking-at-p org-planning-line-re) (forward-line))
  12085. (setq props (nconc (funcall find-ts end ts) props))))))))
  12086. ;; Get the standard properties, like :PROP:.
  12087. (when (memq which '(nil all standard))
  12088. ;; If we are looking after a specific property, delegate
  12089. ;; to `org-entry-get', which is faster. However, make an
  12090. ;; exception for "CATEGORY", since it can be also set
  12091. ;; through keywords (i.e. #+CATEGORY).
  12092. (if (and specific (not (equal specific "CATEGORY")))
  12093. (let ((value (org-entry-get beg specific nil t)))
  12094. (throw 'exit (and value (list (cons specific value)))))
  12095. (let ((range (org-get-property-block beg)))
  12096. (when range
  12097. (let ((end (cdr range)) seen-base)
  12098. (goto-char (car range))
  12099. ;; Unlike to `org--update-property-plist', we
  12100. ;; handle the case where base values is found
  12101. ;; after its extension. We also forbid standard
  12102. ;; properties to be named as special properties.
  12103. (while (re-search-forward org-property-re end t)
  12104. (let* ((key (upcase (match-string-no-properties 2)))
  12105. (extendp (string-match-p "\\+\\'" key))
  12106. (key-base (if extendp (substring key 0 -1) key))
  12107. (value (match-string-no-properties 3)))
  12108. (cond
  12109. ((member-ignore-case key-base org-special-properties))
  12110. (extendp
  12111. (setq props
  12112. (org--update-property-plist key value props)))
  12113. ((member key seen-base))
  12114. (t (push key seen-base)
  12115. (let ((p (assoc-string key props t)))
  12116. (if p (setcdr p (concat value " " (cdr p)))
  12117. (push (cons key value) props))))))))))))
  12118. (unless (assoc "CATEGORY" props)
  12119. (push (cons "CATEGORY" (org-get-category beg)) props)
  12120. (when (string= specific "CATEGORY") (throw 'exit props)))
  12121. ;; Return value.
  12122. props)))))
  12123. (defun org--property-local-values (property literal-nil)
  12124. "Return value for PROPERTY in current entry.
  12125. Value is a list whose car is the base value for PROPERTY and cdr
  12126. a list of accumulated values. Return nil if neither is found in
  12127. the entry. Also return nil when PROPERTY is set to \"nil\",
  12128. unless LITERAL-NIL is non-nil."
  12129. (let ((range (org-get-property-block)))
  12130. (when range
  12131. (goto-char (car range))
  12132. (let* ((case-fold-search t)
  12133. (end (cdr range))
  12134. (value
  12135. ;; Base value.
  12136. (save-excursion
  12137. (let ((v (and (re-search-forward
  12138. (org-re-property property nil t) end t)
  12139. (match-string-no-properties 3))))
  12140. (list (if literal-nil v (org-not-nil v)))))))
  12141. ;; Find additional values.
  12142. (let* ((property+ (org-re-property (concat property "+") nil t)))
  12143. (while (re-search-forward property+ end t)
  12144. (push (match-string-no-properties 3) value)))
  12145. ;; Return final values.
  12146. (and (not (equal value '(nil))) (nreverse value))))))
  12147. (defun org--property-global-or-keyword-value (property literal-nil)
  12148. "Return value for PROPERTY as defined by global properties or by keyword.
  12149. Return value is a string. Return nil if property is not set
  12150. globally or by keyword. Also return nil when PROPERTY is set to
  12151. \"nil\", unless LITERAL-NIL is non-nil."
  12152. (let ((global
  12153. (cdr (or (assoc-string property org-keyword-properties t)
  12154. (assoc-string property org-global-properties t)
  12155. (assoc-string property org-global-properties-fixed t)))))
  12156. (if literal-nil global (org-not-nil global))))
  12157. (defun org-entry-get (pom property &optional inherit literal-nil)
  12158. "Get value of PROPERTY for entry or content at point-or-marker POM.
  12159. If INHERIT is non-nil and the entry does not have the property,
  12160. then also check higher levels of the hierarchy. If INHERIT is
  12161. the symbol `selective', use inheritance only if the setting in
  12162. `org-use-property-inheritance' selects PROPERTY for inheritance.
  12163. If the property is present but empty, the return value is the
  12164. empty string. If the property is not present at all, nil is
  12165. returned. In any other case, return the value as a string.
  12166. Search is case-insensitive.
  12167. If LITERAL-NIL is set, return the string value \"nil\" as
  12168. a string, do not interpret it as the list atom nil. This is used
  12169. for inheritance when a \"nil\" value can supersede a non-nil
  12170. value higher up the hierarchy."
  12171. (org-with-point-at pom
  12172. (cond
  12173. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  12174. ;; We need a special property. Use `org-entry-properties' to
  12175. ;; retrieve it, but specify the wanted property.
  12176. (cdr (assoc-string property (org-entry-properties nil property))))
  12177. ((and inherit
  12178. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  12179. (org-entry-get-with-inheritance property literal-nil))
  12180. (t
  12181. (let* ((local (org--property-local-values property literal-nil))
  12182. (value (and local (mapconcat #'identity (delq nil local) " "))))
  12183. (if literal-nil value (org-not-nil value)))))))
  12184. (defun org-property-or-variable-value (var &optional inherit)
  12185. "Check if there is a property fixing the value of VAR.
  12186. If yes, return this value. If not, return the current value of the variable."
  12187. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  12188. (if (and prop (stringp prop) (string-match "\\S-" prop))
  12189. (read prop)
  12190. (symbol-value var))))
  12191. (defun org-entry-delete (pom property)
  12192. "Delete PROPERTY from entry at point-or-marker POM.
  12193. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  12194. non-nil when a property was removed."
  12195. (org-with-point-at pom
  12196. (pcase (org-get-property-block)
  12197. (`(,begin . ,origin)
  12198. (let* ((end (copy-marker origin))
  12199. (re (org-re-property
  12200. (concat (regexp-quote property) "\\+?") t t)))
  12201. (goto-char begin)
  12202. (while (re-search-forward re end t)
  12203. (delete-region (match-beginning 0) (line-beginning-position 2)))
  12204. ;; If drawer is empty, remove it altogether.
  12205. (when (= begin end)
  12206. (delete-region (line-beginning-position 0)
  12207. (line-beginning-position 2)))
  12208. ;; Return non-nil if some property was removed.
  12209. (prog1 (/= end origin) (set-marker end nil))))
  12210. (_ nil))))
  12211. ;; Multi-values properties are properties that contain multiple values
  12212. ;; These values are assumed to be single words, separated by whitespace.
  12213. (defun org-entry-add-to-multivalued-property (pom property value)
  12214. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  12215. (let* ((old (org-entry-get pom property))
  12216. (values (and old (split-string old))))
  12217. (setq value (org-entry-protect-space value))
  12218. (unless (member value values)
  12219. (setq values (append values (list value)))
  12220. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12221. (defun org-entry-remove-from-multivalued-property (pom property value)
  12222. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  12223. (let* ((old (org-entry-get pom property))
  12224. (values (and old (split-string old))))
  12225. (setq value (org-entry-protect-space value))
  12226. (when (member value values)
  12227. (setq values (delete value values))
  12228. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12229. (defun org-entry-member-in-multivalued-property (pom property value)
  12230. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  12231. (let* ((old (org-entry-get pom property))
  12232. (values (and old (split-string old))))
  12233. (setq value (org-entry-protect-space value))
  12234. (member value values)))
  12235. (defun org-entry-get-multivalued-property (pom property)
  12236. "Return a list of values in a multivalued property."
  12237. (let* ((value (org-entry-get pom property))
  12238. (values (and value (split-string value))))
  12239. (mapcar #'org-entry-restore-space values)))
  12240. (defun org-entry-put-multivalued-property (pom property &rest values)
  12241. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  12242. VALUES should be a list of strings. Spaces will be protected."
  12243. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  12244. (let* ((value (org-entry-get pom property))
  12245. (values (and value (split-string value))))
  12246. (mapcar #'org-entry-restore-space values)))
  12247. (defun org-entry-protect-space (s)
  12248. "Protect spaces and newline in string S."
  12249. (while (string-match " " s)
  12250. (setq s (replace-match "%20" t t s)))
  12251. (while (string-match "\n" s)
  12252. (setq s (replace-match "%0A" t t s)))
  12253. s)
  12254. (defun org-entry-restore-space (s)
  12255. "Restore spaces and newline in string S."
  12256. (while (string-match "%20" s)
  12257. (setq s (replace-match " " t t s)))
  12258. (while (string-match "%0A" s)
  12259. (setq s (replace-match "\n" t t s)))
  12260. s)
  12261. (defvar org-entry-property-inherited-from (make-marker)
  12262. "Marker pointing to the entry from where a property was inherited.
  12263. Each call to `org-entry-get-with-inheritance' will set this marker to the
  12264. location of the entry where the inheritance search matched. If there was
  12265. no match, the marker will point nowhere.
  12266. Note that also `org-entry-get' calls this function, if the INHERIT flag
  12267. is set.")
  12268. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  12269. "Get PROPERTY of entry or content at point, search higher levels if needed.
  12270. The search will stop at the first ancestor which has the property defined.
  12271. If the value found is \"nil\", return nil to show that the property
  12272. should be considered as undefined (this is the meaning of nil here).
  12273. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  12274. (move-marker org-entry-property-inherited-from nil)
  12275. (org-with-wide-buffer
  12276. (let (value)
  12277. (catch 'exit
  12278. (while t
  12279. (let ((v (org--property-local-values property literal-nil)))
  12280. (when v
  12281. (setq value
  12282. (concat (mapconcat #'identity (delq nil v) " ")
  12283. (and value " ")
  12284. value)))
  12285. (cond
  12286. ((car v)
  12287. (org-back-to-heading-or-point-min t)
  12288. (move-marker org-entry-property-inherited-from (point))
  12289. (throw 'exit nil))
  12290. ((org-up-heading-or-point-min))
  12291. (t
  12292. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  12293. (cond ((not global))
  12294. (value (setq value (concat global " " value)))
  12295. (t (setq value global))))
  12296. (throw 'exit nil))))))
  12297. (if literal-nil value (org-not-nil value)))))
  12298. (defvar org-property-changed-functions nil
  12299. "Hook called when the value of a property has changed.
  12300. Each hook function should accept two arguments, the name of the property
  12301. and the new value.")
  12302. (defun org-entry-put (pom property value)
  12303. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  12304. If the value is nil, it is converted to the empty string. If it
  12305. is not a string, an error is raised. Also raise an error on
  12306. invalid property names.
  12307. PROPERTY can be any regular property (see
  12308. `org-special-properties'). It can also be \"TODO\",
  12309. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  12310. For the last two properties, VALUE may have any of the special
  12311. values \"earlier\" and \"later\". The function then increases or
  12312. decreases scheduled or deadline date by one day."
  12313. (cond ((null value) (setq value ""))
  12314. ((not (stringp value)) (error "Properties values should be strings"))
  12315. ((not (org--valid-property-p property))
  12316. (user-error "Invalid property name: \"%s\"" property)))
  12317. (org-with-point-at pom
  12318. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12319. (org-back-to-heading-or-point-min t)
  12320. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12321. (let ((beg (point)))
  12322. (cond
  12323. ((equal property "TODO")
  12324. (cond ((not (org-string-nw-p value)) (setq value 'none))
  12325. ((not (member value org-todo-keywords-1))
  12326. (user-error "\"%s\" is not a valid TODO state" value)))
  12327. (org-todo value)
  12328. (org-align-tags))
  12329. ((equal property "PRIORITY")
  12330. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  12331. (org-align-tags))
  12332. ((equal property "SCHEDULED")
  12333. (forward-line)
  12334. (if (and (looking-at-p org-planning-line-re)
  12335. (re-search-forward
  12336. org-scheduled-time-regexp (line-end-position) t))
  12337. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12338. ((string= value "later") (org-timestamp-change 1 'day))
  12339. ((string= value "") (org-schedule '(4)))
  12340. (t (org-schedule nil value)))
  12341. (if (member value '("earlier" "later" ""))
  12342. (call-interactively #'org-schedule)
  12343. (org-schedule nil value))))
  12344. ((equal property "DEADLINE")
  12345. (forward-line)
  12346. (if (and (looking-at-p org-planning-line-re)
  12347. (re-search-forward
  12348. org-deadline-time-regexp (line-end-position) t))
  12349. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12350. ((string= value "later") (org-timestamp-change 1 'day))
  12351. ((string= value "") (org-deadline '(4)))
  12352. (t (org-deadline nil value)))
  12353. (if (member value '("earlier" "later" ""))
  12354. (call-interactively #'org-deadline)
  12355. (org-deadline nil value))))
  12356. ((member property org-special-properties)
  12357. (error "The %s property cannot be set with `org-entry-put'" property))
  12358. (t
  12359. (let* ((range (org-get-property-block beg 'force))
  12360. (end (cdr range))
  12361. (case-fold-search t))
  12362. (goto-char (car range))
  12363. (if (re-search-forward (org-re-property property nil t) end t)
  12364. (progn (delete-region (match-beginning 0) (match-end 0))
  12365. (goto-char (match-beginning 0)))
  12366. (goto-char end)
  12367. (insert "\n")
  12368. (backward-char))
  12369. (insert ":" property ":")
  12370. (when value (insert " " value))
  12371. (org-indent-line)))))
  12372. (run-hook-with-args 'org-property-changed-functions property value)))
  12373. (defun org-buffer-property-keys (&optional specials defaults columns)
  12374. "Get all property keys in the current buffer.
  12375. When SPECIALS is non-nil, also list the special properties that
  12376. reflect things like tags and TODO state.
  12377. When DEFAULTS is non-nil, also include properties that has
  12378. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  12379. DESCRIPTION, LOCATION, and LOGGING and others.
  12380. When COLUMNS in non-nil, also include property names given in
  12381. COLUMN formats in the current buffer."
  12382. (let ((case-fold-search t)
  12383. (props (append
  12384. (and specials org-special-properties)
  12385. (and defaults (cons org-effort-property org-default-properties))
  12386. nil)))
  12387. (org-with-wide-buffer
  12388. (goto-char (point-min))
  12389. (while (re-search-forward org-property-start-re nil t)
  12390. (catch :skip
  12391. (let ((range (org-get-property-block)))
  12392. (unless range (throw :skip nil))
  12393. (goto-char (car range))
  12394. (let ((begin (car range))
  12395. (end (cdr range)))
  12396. ;; Make sure that found property block is not located
  12397. ;; before current point, as it would generate an infloop.
  12398. ;; It can happen, for example, in the following
  12399. ;; situation:
  12400. ;;
  12401. ;; * Headline
  12402. ;; :PROPERTIES:
  12403. ;; ...
  12404. ;; :END:
  12405. ;; *************** Inlinetask
  12406. ;; #+BEGIN_EXAMPLE
  12407. ;; :PROPERTIES:
  12408. ;; #+END_EXAMPLE
  12409. ;;
  12410. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  12411. (while (< (point) end)
  12412. (let ((p (progn (looking-at org-property-re)
  12413. (match-string-no-properties 2))))
  12414. ;; Only add true property name, not extension symbol.
  12415. (push (if (not (string-match-p "\\+\\'" p)) p
  12416. (substring p 0 -1))
  12417. props))
  12418. (forward-line))))
  12419. (outline-next-heading)))
  12420. (when columns
  12421. (goto-char (point-min))
  12422. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  12423. (let ((element (org-element-at-point)))
  12424. (when (memq (org-element-type element) '(keyword node-property))
  12425. (let ((value (org-element-property :value element))
  12426. (start 0))
  12427. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  12428. \\(?:{[^}]+}\\)?"
  12429. value start)
  12430. (setq start (match-end 0))
  12431. (let ((p (match-string-no-properties 1 value)))
  12432. (unless (member-ignore-case p org-special-properties)
  12433. (push p props))))))))))
  12434. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  12435. (defun org-property-values (key)
  12436. "List all non-nil values of property KEY in current buffer."
  12437. (org-with-wide-buffer
  12438. (goto-char (point-min))
  12439. (let ((case-fold-search t)
  12440. (re (org-re-property key))
  12441. values)
  12442. (while (re-search-forward re nil t)
  12443. (push (org-entry-get (point) key) values))
  12444. (delete-dups values))))
  12445. (defun org-insert-property-drawer ()
  12446. "Insert a property drawer into the current entry.
  12447. Do nothing if the drawer already exists. The newly created
  12448. drawer is immediately hidden."
  12449. (org-with-wide-buffer
  12450. ;; Set point to the position where the drawer should be inserted.
  12451. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12452. (org-back-to-heading-or-point-min t)
  12453. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12454. (if (org-before-first-heading-p)
  12455. (while (and (org-at-comment-p) (bolp)) (forward-line))
  12456. (progn
  12457. (forward-line)
  12458. (when (looking-at-p org-planning-line-re) (forward-line))))
  12459. (unless (looking-at-p org-property-drawer-re)
  12460. ;; Make sure we start editing a line from current entry, not from
  12461. ;; next one. It prevents extending text properties or overlays
  12462. ;; belonging to the latter.
  12463. (when (and (bolp) (> (point) (point-min))) (backward-char))
  12464. (let ((begin (if (bobp) (point) (1+ (point))))
  12465. (inhibit-read-only t))
  12466. (unless (bobp) (insert "\n"))
  12467. (insert ":PROPERTIES:\n:END:")
  12468. (org-flag-drawer t nil (line-end-position 0) (point))
  12469. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  12470. (org-indent-region begin (point))))))
  12471. (defun org-insert-drawer (&optional arg drawer)
  12472. "Insert a drawer at point.
  12473. When optional argument ARG is non-nil, insert a property drawer.
  12474. Optional argument DRAWER, when non-nil, is a string representing
  12475. drawer's name. Otherwise, the user is prompted for a name.
  12476. If a region is active, insert the drawer around that region
  12477. instead.
  12478. Point is left between drawer's boundaries."
  12479. (interactive "P")
  12480. (let* ((drawer (if arg "PROPERTIES"
  12481. (or drawer (read-from-minibuffer "Drawer: ")))))
  12482. (cond
  12483. ;; With C-u, fall back on `org-insert-property-drawer'
  12484. (arg (org-insert-property-drawer))
  12485. ;; Check validity of suggested drawer's name.
  12486. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  12487. (user-error "Invalid drawer name"))
  12488. ;; With an active region, insert a drawer at point.
  12489. ((not (org-region-active-p))
  12490. (progn
  12491. (unless (bolp) (insert "\n"))
  12492. (insert (format ":%s:\n\n:END:\n" drawer))
  12493. (forward-line -2)))
  12494. ;; Otherwise, insert the drawer at point
  12495. (t
  12496. (let ((rbeg (region-beginning))
  12497. (rend (copy-marker (region-end))))
  12498. (unwind-protect
  12499. (progn
  12500. (goto-char rbeg)
  12501. (beginning-of-line)
  12502. (when (save-excursion
  12503. (re-search-forward org-outline-regexp-bol rend t))
  12504. (user-error "Drawers cannot contain headlines"))
  12505. ;; Position point at the beginning of the first
  12506. ;; non-blank line in region. Insert drawer's opening
  12507. ;; there, then indent it.
  12508. (org-skip-whitespace)
  12509. (beginning-of-line)
  12510. (insert ":" drawer ":\n")
  12511. (forward-line -1)
  12512. (indent-for-tab-command)
  12513. ;; Move point to the beginning of the first blank line
  12514. ;; after the last non-blank line in region. Insert
  12515. ;; drawer's closing, then indent it.
  12516. (goto-char rend)
  12517. (skip-chars-backward " \r\t\n")
  12518. (insert "\n:END:")
  12519. (deactivate-mark t)
  12520. (indent-for-tab-command)
  12521. (unless (eolp) (insert "\n")))
  12522. ;; Clear marker, whatever the outcome of insertion is.
  12523. (set-marker rend nil)))))))
  12524. (defvar org-property-set-functions-alist nil
  12525. "Property set function alist.
  12526. Each entry should have the following format:
  12527. (PROPERTY . READ-FUNCTION)
  12528. The read function will be called with the same argument as
  12529. `org-completing-read'.")
  12530. (defun org-set-property-function (property)
  12531. "Get the function that should be used to set PROPERTY.
  12532. This is computed according to `org-property-set-functions-alist'."
  12533. (or (cdr (assoc property org-property-set-functions-alist))
  12534. 'org-completing-read))
  12535. (defun org-read-property-value (property &optional pom)
  12536. "Read value for PROPERTY, as a string.
  12537. When optional argument POM is non-nil, completion uses additional
  12538. information, i.e., allowed or existing values at point or marker
  12539. POM."
  12540. (let* ((completion-ignore-case t)
  12541. (allowed
  12542. (or (org-property-get-allowed-values nil property 'table)
  12543. (and pom (org-property-get-allowed-values pom property 'table))))
  12544. (current (org-entry-get nil property))
  12545. (prompt (format "%s value%s: "
  12546. property
  12547. (if (org-string-nw-p current)
  12548. (format " [%s]" current)
  12549. "")))
  12550. (set-function (org-set-property-function property)))
  12551. (org-trim
  12552. (if allowed
  12553. (funcall set-function
  12554. prompt allowed nil
  12555. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  12556. (let ((all (mapcar #'list
  12557. (append (org-property-values property)
  12558. (and pom
  12559. (org-with-point-at pom
  12560. (org-property-values property)))))))
  12561. (funcall set-function prompt all nil nil "" nil current))))))
  12562. (defvar org-last-set-property nil)
  12563. (defvar org-last-set-property-value nil)
  12564. (defun org-read-property-name ()
  12565. "Read a property name."
  12566. (let ((completion-ignore-case t)
  12567. (default-prop (or (and (org-at-property-p)
  12568. (match-string-no-properties 2))
  12569. org-last-set-property)))
  12570. (org-completing-read
  12571. (concat "Property"
  12572. (if default-prop (concat " [" default-prop "]") "")
  12573. ": ")
  12574. (mapcar #'list (org-buffer-property-keys nil t t))
  12575. nil nil nil nil default-prop)))
  12576. (defun org-set-property-and-value (use-last)
  12577. "Allow to set [PROPERTY]: [value] direction from prompt.
  12578. When use-default, don't even ask, just use the last
  12579. \"[PROPERTY]: [value]\" string from the history."
  12580. (interactive "P")
  12581. (let* ((completion-ignore-case t)
  12582. (pv (or (and use-last org-last-set-property-value)
  12583. (org-completing-read
  12584. "Enter a \"[Property]: [value]\" pair: "
  12585. nil nil nil nil nil
  12586. org-last-set-property-value)))
  12587. prop val)
  12588. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12589. (setq prop (match-string 1 pv)
  12590. val (match-string 2 pv))
  12591. (org-set-property prop val))))
  12592. (defun org-set-property (property value)
  12593. "In the current entry, set PROPERTY to VALUE.
  12594. When called interactively, this will prompt for a property name, offering
  12595. completion on existing and default properties. And then it will prompt
  12596. for a value, offering completion either on allowed values (via an inherited
  12597. xxx_ALL property) or on existing values in other instances of this property
  12598. in the current file.
  12599. Throw an error when trying to set a property with an invalid name."
  12600. (interactive (list nil nil))
  12601. (let ((property (or property (org-read-property-name))))
  12602. ;; `org-entry-put' also makes the following check, but this one
  12603. ;; avoids polluting `org-last-set-property' and
  12604. ;; `org-last-set-property-value' needlessly.
  12605. (unless (org--valid-property-p property)
  12606. (user-error "Invalid property name: \"%s\"" property))
  12607. (let ((value (or value (org-read-property-value property)))
  12608. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12609. (setq org-last-set-property property)
  12610. (setq org-last-set-property-value (concat property ": " value))
  12611. ;; Possibly postprocess the inserted value:
  12612. (when fn (setq value (funcall fn value)))
  12613. (unless (equal (org-entry-get nil property) value)
  12614. (org-entry-put nil property value)))))
  12615. (defun org-find-property (property &optional value)
  12616. "Find first entry in buffer that sets PROPERTY.
  12617. When optional argument VALUE is non-nil, only consider an entry
  12618. if it contains PROPERTY set to this value. If PROPERTY should be
  12619. explicitly set to nil, use string \"nil\" for VALUE.
  12620. Return position where the entry begins, or nil if there is no
  12621. such entry. If narrowing is in effect, only search the visible
  12622. part of the buffer."
  12623. (save-excursion
  12624. (goto-char (point-min))
  12625. (let ((case-fold-search t)
  12626. (re (org-re-property property nil (not value) value)))
  12627. (catch 'exit
  12628. (while (re-search-forward re nil t)
  12629. (when (if value (org-at-property-p)
  12630. (org-entry-get (point) property nil t))
  12631. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  12632. (defun org-delete-property (property)
  12633. "In the current entry, delete PROPERTY."
  12634. (interactive
  12635. (let* ((completion-ignore-case t)
  12636. (cat (org-entry-get (point) "CATEGORY"))
  12637. (props0 (org-entry-properties nil 'standard))
  12638. (props (if cat props0
  12639. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12640. (prop (if (< 1 (length props))
  12641. (completing-read "Property: " props nil t)
  12642. (caar props))))
  12643. (list prop)))
  12644. (if (not property)
  12645. (message "No property to delete in this entry")
  12646. (org-entry-delete nil property)
  12647. (message "Property \"%s\" deleted" property)))
  12648. (defun org-delete-property-globally (property)
  12649. "Remove PROPERTY globally, from all entries.
  12650. This function ignores narrowing, if any."
  12651. (interactive
  12652. (let* ((completion-ignore-case t)
  12653. (prop (completing-read
  12654. "Globally remove property: "
  12655. (mapcar #'list (org-buffer-property-keys)))))
  12656. (list prop)))
  12657. (org-with-wide-buffer
  12658. (goto-char (point-min))
  12659. (let ((count 0)
  12660. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12661. (while (re-search-forward re nil t)
  12662. (when (org-entry-delete (point) property) (cl-incf count)))
  12663. (message "Property \"%s\" removed from %d entries" property count))))
  12664. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12665. (defun org-compute-property-at-point ()
  12666. "Compute the property at point.
  12667. This looks for an enclosing column format, extracts the operator and
  12668. then applies it to the property in the column format's scope."
  12669. (interactive)
  12670. (unless (org-at-property-p)
  12671. (user-error "Not at a property"))
  12672. (let ((prop (match-string-no-properties 2)))
  12673. (org-columns-get-format-and-top-level)
  12674. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12675. (user-error "No operator defined for property %s" prop))
  12676. (org-columns-compute prop)))
  12677. (defvar org-property-allowed-value-functions nil
  12678. "Hook for functions supplying allowed values for a specific property.
  12679. The functions must take a single argument, the name of the property, and
  12680. return a flat list of allowed values. If \":ETC\" is one of
  12681. the values, this means that these values are intended as defaults for
  12682. completion, but that other values should be allowed too.
  12683. The functions must return nil if they are not responsible for this
  12684. property.")
  12685. (defun org-property-get-allowed-values (pom property &optional table)
  12686. "Get allowed values for the property PROPERTY.
  12687. When TABLE is non-nil, return an alist that can directly be used for
  12688. completion."
  12689. (let (vals)
  12690. (cond
  12691. ((equal property "TODO")
  12692. (setq vals (org-with-point-at pom
  12693. (append org-todo-keywords-1 '("")))))
  12694. ((equal property "PRIORITY")
  12695. (let ((n org-priority-lowest))
  12696. (while (>= n org-priority-highest)
  12697. (push (char-to-string n) vals)
  12698. (setq n (1- n)))))
  12699. ((equal property "CATEGORY"))
  12700. ((member property org-special-properties))
  12701. ((setq vals (run-hook-with-args-until-success
  12702. 'org-property-allowed-value-functions property)))
  12703. (t
  12704. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12705. (when (and vals (string-match "\\S-" vals))
  12706. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12707. (setq vals (mapcar (lambda (x)
  12708. (cond ((stringp x) x)
  12709. ((numberp x) (number-to-string x))
  12710. ((symbolp x) (symbol-name x))
  12711. (t "???")))
  12712. vals)))))
  12713. (when (member ":ETC" vals)
  12714. (setq vals (remove ":ETC" vals))
  12715. (org-add-props (car vals) '(org-unrestricted t)))
  12716. (if table (mapcar 'list vals) vals)))
  12717. (defun org-property-previous-allowed-value (&optional _previous)
  12718. "Switch to the next allowed value for this property."
  12719. (interactive)
  12720. (org-property-next-allowed-value t))
  12721. (defun org-property-next-allowed-value (&optional previous)
  12722. "Switch to the next allowed value for this property."
  12723. (interactive)
  12724. (unless (org-at-property-p)
  12725. (user-error "Not at a property"))
  12726. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12727. (key (match-string 2))
  12728. (value (match-string 3))
  12729. (allowed (or (org-property-get-allowed-values (point) key)
  12730. (and (member value '("[ ]" "[-]" "[X]"))
  12731. '("[ ]" "[X]"))))
  12732. (heading (save-match-data (nth 4 (org-heading-components))))
  12733. nval)
  12734. (unless allowed
  12735. (user-error "Allowed values for this property have not been defined"))
  12736. (when previous (setq allowed (reverse allowed)))
  12737. (when (member value allowed)
  12738. (setq nval (car (cdr (member value allowed)))))
  12739. (setq nval (or nval (car allowed)))
  12740. (when (equal nval value)
  12741. (user-error "Only one allowed value for this property"))
  12742. (org-at-property-p)
  12743. (replace-match (concat " :" key ": " nval) t t)
  12744. (org-indent-line)
  12745. (beginning-of-line 1)
  12746. (skip-chars-forward " \t")
  12747. (when (equal prop org-effort-property)
  12748. (org-refresh-property
  12749. '((effort . identity)
  12750. (effort-minutes . org-duration-to-minutes))
  12751. nval)
  12752. (when (string= org-clock-current-task heading)
  12753. (setq org-clock-effort nval)
  12754. (org-clock-update-mode-line)))
  12755. (run-hook-with-args 'org-property-changed-functions key nval)))
  12756. (defun org-find-olp (path &optional this-buffer)
  12757. "Return a marker pointing to the entry at outline path OLP.
  12758. If anything goes wrong, throw an error.
  12759. You can wrap this call to catch the error like this:
  12760. (condition-case msg
  12761. (org-mobile-locate-entry (match-string 4))
  12762. (error (nth 1 msg)))
  12763. The return value will then be either a string with the error message,
  12764. or a marker if everything is OK.
  12765. If THIS-BUFFER is set, the outline path does not contain a file,
  12766. only headings."
  12767. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12768. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12769. (level 1)
  12770. (lmin 1)
  12771. (lmax 1)
  12772. end found flevel)
  12773. (unless buffer (error "File not found :%s" file))
  12774. (with-current-buffer buffer
  12775. (unless (derived-mode-p 'org-mode)
  12776. (error "Buffer %s needs to be in Org mode" buffer))
  12777. (org-with-wide-buffer
  12778. (goto-char (point-min))
  12779. (dolist (heading path)
  12780. (let ((re (format org-complex-heading-regexp-format
  12781. (regexp-quote heading)))
  12782. (cnt 0))
  12783. (while (re-search-forward re end t)
  12784. (setq level (- (match-end 1) (match-beginning 1)))
  12785. (when (and (>= level lmin) (<= level lmax))
  12786. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12787. (when (= cnt 0)
  12788. (error "Heading not found on level %d: %s" lmax heading))
  12789. (when (> cnt 1)
  12790. (error "Heading not unique on level %d: %s" lmax heading))
  12791. (goto-char found)
  12792. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12793. (setq end (save-excursion (org-end-of-subtree t t)))))
  12794. (when (org-at-heading-p)
  12795. (point-marker))))))
  12796. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12797. "Find node HEADING in BUFFER.
  12798. Return a marker to the heading if it was found, or nil if not.
  12799. If POS-ONLY is set, return just the position instead of a marker.
  12800. The heading text must match exact, but it may have a TODO keyword,
  12801. a priority cookie and tags in the standard locations."
  12802. (with-current-buffer (or buffer (current-buffer))
  12803. (org-with-wide-buffer
  12804. (goto-char (point-min))
  12805. (let (case-fold-search)
  12806. (when (re-search-forward
  12807. (format org-complex-heading-regexp-format
  12808. (regexp-quote heading)) nil t)
  12809. (if pos-only
  12810. (match-beginning 0)
  12811. (move-marker (make-marker) (match-beginning 0))))))))
  12812. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12813. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12814. When the target headline is found, return a marker to this location."
  12815. (let ((files (directory-files (or dir default-directory)
  12816. t "\\`[^.#].*\\.org\\'"))
  12817. visiting m buffer)
  12818. (catch 'found
  12819. (dolist (file files)
  12820. (message "trying %s" file)
  12821. (setq visiting (org-find-base-buffer-visiting file))
  12822. (setq buffer (or visiting (find-file-noselect file)))
  12823. (setq m (org-find-exact-headline-in-buffer
  12824. heading buffer))
  12825. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12826. (and m (throw 'found m))))))
  12827. (defun org-find-entry-with-id (ident)
  12828. "Locate the entry that contains the ID property with exact value IDENT.
  12829. IDENT can be a string, a symbol or a number, this function will search for
  12830. the string representation of it.
  12831. Return the position where this entry starts, or nil if there is no such entry."
  12832. (interactive "sID: ")
  12833. (let ((id (cond
  12834. ((stringp ident) ident)
  12835. ((symbolp ident) (symbol-name ident))
  12836. ((numberp ident) (number-to-string ident))
  12837. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12838. (org-with-wide-buffer (org-find-property "ID" id))))
  12839. ;;;; Timestamps
  12840. (defvar org-last-changed-timestamp nil)
  12841. (defvar org-last-inserted-timestamp nil
  12842. "The last time stamp inserted with `org-insert-time-stamp'.")
  12843. (defun org-time-stamp (arg &optional inactive)
  12844. "Prompt for a date/time and insert a time stamp.
  12845. If the user specifies a time like HH:MM or if this command is
  12846. called with at least one prefix argument, the time stamp contains
  12847. the date and the time. Otherwise, only the date is included.
  12848. All parts of a date not specified by the user are filled in from
  12849. the timestamp at point, if any, or the current date/time
  12850. otherwise.
  12851. If there is already a timestamp at the cursor, it is replaced.
  12852. With two universal prefix arguments, insert an active timestamp
  12853. with the current time without prompting the user.
  12854. When called from lisp, the timestamp is inactive if INACTIVE is
  12855. non-nil."
  12856. (interactive "P")
  12857. (let* ((ts (cond
  12858. ((org-at-date-range-p t)
  12859. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12860. ((org-at-timestamp-p 'lax) (match-string 0))))
  12861. ;; Default time is either the timestamp at point or today.
  12862. ;; When entering a range, only the range start is considered.
  12863. (default-time (and ts (org-time-string-to-time ts)))
  12864. (default-input (and ts (org-get-compact-tod ts)))
  12865. (repeater (and ts
  12866. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12867. (match-string 0 ts)))
  12868. org-time-was-given
  12869. org-end-time-was-given
  12870. (time
  12871. (if (equal arg '(16)) (current-time)
  12872. ;; Preserve `this-command' and `last-command'.
  12873. (let ((this-command this-command)
  12874. (last-command last-command))
  12875. (org-read-date
  12876. arg 'totime nil nil default-time default-input
  12877. inactive)))))
  12878. (cond
  12879. ((and ts
  12880. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12881. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12882. (insert "--")
  12883. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12884. (ts
  12885. ;; Make sure we're on a timestamp. When in the middle of a date
  12886. ;; range, move arbitrarily to range end.
  12887. (unless (org-at-timestamp-p 'lax)
  12888. (skip-chars-forward "-")
  12889. (org-at-timestamp-p 'lax))
  12890. (replace-match "")
  12891. (setq org-last-changed-timestamp
  12892. (org-insert-time-stamp
  12893. time (or org-time-was-given arg)
  12894. inactive nil nil (list org-end-time-was-given)))
  12895. (when repeater
  12896. (backward-char)
  12897. (insert " " repeater)
  12898. (setq org-last-changed-timestamp
  12899. (concat (substring org-last-inserted-timestamp 0 -1)
  12900. " " repeater ">")))
  12901. (message "Timestamp updated"))
  12902. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12903. (t (org-insert-time-stamp
  12904. time (or org-time-was-given arg) inactive nil nil
  12905. (list org-end-time-was-given))))))
  12906. ;; FIXME: can we use this for something else, like computing time differences?
  12907. (defun org-get-compact-tod (s)
  12908. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12909. (let* ((t1 (match-string 1 s))
  12910. (h1 (string-to-number (match-string 2 s)))
  12911. (m1 (string-to-number (match-string 3 s)))
  12912. (t2 (and (match-end 4) (match-string 5 s)))
  12913. (h2 (and t2 (string-to-number (match-string 6 s))))
  12914. (m2 (and t2 (string-to-number (match-string 7 s))))
  12915. dh dm)
  12916. (if (not t2)
  12917. t1
  12918. (setq dh (- h2 h1) dm (- m2 m1))
  12919. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12920. (concat t1 "+" (number-to-string dh)
  12921. (and (/= 0 dm) (format ":%02d" dm)))))))
  12922. (defun org-time-stamp-inactive (&optional arg)
  12923. "Insert an inactive time stamp.
  12924. An inactive time stamp is enclosed in square brackets instead of angle
  12925. brackets. It is inactive in the sense that it does not trigger agenda entries,
  12926. does not link to the calendar and cannot be changed with the S-cursor keys.
  12927. So these are more for recording a certain time/date.
  12928. If the user specifies a time like HH:MM or if this command is called with
  12929. at least one prefix argument, the time stamp contains the date and the time.
  12930. Otherwise, only the date is included.
  12931. When called with two universal prefix arguments, insert an active time stamp
  12932. with the current time without prompting the user."
  12933. (interactive "P")
  12934. (org-time-stamp arg 'inactive))
  12935. (defvar org-date-ovl (make-overlay 1 1))
  12936. (overlay-put org-date-ovl 'face 'org-date-selected)
  12937. (delete-overlay org-date-ovl)
  12938. (defvar org-ans1) ; dynamically scoped parameter
  12939. (defvar org-ans2) ; dynamically scoped parameter
  12940. (defvar org-plain-time-of-day-regexp) ; defined below
  12941. (defvar org-overriding-default-time nil) ; dynamically scoped
  12942. (defvar org-read-date-overlay nil)
  12943. (defvar org-read-date-history nil)
  12944. (defvar org-read-date-final-answer nil)
  12945. (defvar org-read-date-analyze-futurep nil)
  12946. (defvar org-read-date-analyze-forced-year nil)
  12947. (defvar org-read-date-inactive)
  12948. (defvar org-def)
  12949. (defvar org-defdecode)
  12950. (defvar org-with-time)
  12951. (defvar calendar-setup) ; Dynamically scoped.
  12952. (defun org-read-date (&optional with-time to-time from-string prompt
  12953. default-time default-input inactive)
  12954. "Read a date, possibly a time, and make things smooth for the user.
  12955. The prompt will suggest to enter an ISO date, but you can also enter anything
  12956. which will at least partially be understood by `parse-time-string'.
  12957. Unrecognized parts of the date will default to the current day, month, year,
  12958. hour and minute. If this command is called to replace a timestamp at point,
  12959. or to enter the second timestamp of a range, the default time is taken
  12960. from the existing stamp. Furthermore, the command prefers the future,
  12961. so if you are giving a date where the year is not given, and the day-month
  12962. combination is already past in the current year, it will assume you
  12963. mean next year. For details, see the manual. A few examples:
  12964. 3-2-5 --> 2003-02-05
  12965. feb 15 --> currentyear-02-15
  12966. 2/15 --> currentyear-02-15
  12967. sep 12 9 --> 2009-09-12
  12968. 12:45 --> today 12:45
  12969. 22 sept 0:34 --> currentyear-09-22 0:34
  12970. 12 --> currentyear-currentmonth-12
  12971. Fri --> nearest Friday after today
  12972. -Tue --> last Tuesday
  12973. etc.
  12974. Furthermore you can specify a relative date by giving, as the *first* thing
  12975. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12976. change in days weeks, months, years.
  12977. With a single plus or minus, the date is relative to today. With a double
  12978. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12979. +4d --> four days from today
  12980. +4 --> same as above
  12981. +2w --> two weeks from today
  12982. ++5 --> five days from default date
  12983. The function understands only English month and weekday abbreviations.
  12984. While prompting, a calendar is popped up - you can also select the
  12985. date with the mouse (button 1). The calendar shows a period of three
  12986. months. To scroll it to other months, use the keys `>' and `<'.
  12987. If you don't like the calendar, turn it off with
  12988. (setq org-read-date-popup-calendar nil)
  12989. With optional argument TO-TIME, the date will immediately be converted
  12990. to an internal time.
  12991. With an optional argument WITH-TIME, the prompt will suggest to
  12992. also insert a time. Note that when WITH-TIME is not set, you can
  12993. still enter a time, and this function will inform the calling routine
  12994. about this change. The calling routine may then choose to change the
  12995. format used to insert the time stamp into the buffer to include the time.
  12996. With optional argument FROM-STRING, read from this string instead from
  12997. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12998. the time/date that is used for everything that is not specified by the
  12999. user."
  13000. (require 'parse-time)
  13001. (let* ((org-with-time with-time)
  13002. (org-time-stamp-rounding-minutes
  13003. (if (equal org-with-time '(16))
  13004. '(0 0)
  13005. org-time-stamp-rounding-minutes))
  13006. (ct (org-current-time))
  13007. (org-def (or org-overriding-default-time default-time ct))
  13008. (org-defdecode (decode-time org-def))
  13009. (cur-frame (selected-frame))
  13010. (mouse-autoselect-window nil) ; Don't let the mouse jump
  13011. (calendar-setup
  13012. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  13013. (calendar-move-hook nil)
  13014. (calendar-view-diary-initially-flag nil)
  13015. (calendar-view-holidays-initially-flag nil)
  13016. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  13017. ;; Rationalize `org-def' and `org-defdecode', if required.
  13018. (when (< (nth 2 org-defdecode) org-extend-today-until)
  13019. (setf (nth 2 org-defdecode) -1)
  13020. (setf (nth 1 org-defdecode) 59)
  13021. (setq org-def (apply #'encode-time org-defdecode))
  13022. (setq org-defdecode (decode-time org-def)))
  13023. (let* ((timestr (format-time-string
  13024. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  13025. org-def))
  13026. (prompt (concat (if prompt (concat prompt " ") "")
  13027. (format "Date+time [%s]: " timestr))))
  13028. (cond
  13029. (from-string (setq ans from-string))
  13030. (org-read-date-popup-calendar
  13031. (save-excursion
  13032. (save-window-excursion
  13033. (calendar)
  13034. (when (eq calendar-setup 'calendar-only)
  13035. (setq cal-frame
  13036. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  13037. (select-frame cal-frame))
  13038. (org-eval-in-calendar '(setq cursor-type nil) t)
  13039. (unwind-protect
  13040. (progn
  13041. (calendar-forward-day (- (time-to-days org-def)
  13042. (calendar-absolute-from-gregorian
  13043. (calendar-current-date))))
  13044. (org-eval-in-calendar nil t)
  13045. (let* ((old-map (current-local-map))
  13046. (map (copy-keymap calendar-mode-map))
  13047. (minibuffer-local-map
  13048. (copy-keymap org-read-date-minibuffer-local-map)))
  13049. (org-defkey map (kbd "RET") 'org-calendar-select)
  13050. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  13051. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  13052. (unwind-protect
  13053. (progn
  13054. (use-local-map map)
  13055. (setq org-read-date-inactive inactive)
  13056. (add-hook 'post-command-hook 'org-read-date-display)
  13057. (setq org-ans0
  13058. (read-string prompt
  13059. default-input
  13060. 'org-read-date-history
  13061. nil))
  13062. ;; org-ans0: from prompt
  13063. ;; org-ans1: from mouse click
  13064. ;; org-ans2: from calendar motion
  13065. (setq ans
  13066. (concat org-ans0 " " (or org-ans1 org-ans2))))
  13067. (remove-hook 'post-command-hook 'org-read-date-display)
  13068. (use-local-map old-map)
  13069. (when org-read-date-overlay
  13070. (delete-overlay org-read-date-overlay)
  13071. (setq org-read-date-overlay nil)))))
  13072. (bury-buffer "*Calendar*")
  13073. (when cal-frame
  13074. (delete-frame cal-frame)
  13075. (select-frame-set-input-focus cur-frame))))))
  13076. (t ; Naked prompt only
  13077. (unwind-protect
  13078. (setq ans (read-string prompt default-input
  13079. 'org-read-date-history timestr))
  13080. (when org-read-date-overlay
  13081. (delete-overlay org-read-date-overlay)
  13082. (setq org-read-date-overlay nil))))))
  13083. (setq final (org-read-date-analyze ans org-def org-defdecode))
  13084. (when org-read-date-analyze-forced-year
  13085. (message "Year was forced into %s"
  13086. (if org-read-date-force-compatible-dates
  13087. "compatible range (1970-2037)"
  13088. "range representable on this machine"))
  13089. (ding))
  13090. (setq final (apply #'encode-time final))
  13091. (setq org-read-date-final-answer ans)
  13092. (if to-time
  13093. final
  13094. ;; This round-trip gets rid of 34th of August and stuff like that....
  13095. (setq final (decode-time final))
  13096. (if (and (boundp 'org-time-was-given) org-time-was-given)
  13097. (format "%04d-%02d-%02d %02d:%02d"
  13098. (nth 5 final) (nth 4 final) (nth 3 final)
  13099. (nth 2 final) (nth 1 final))
  13100. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  13101. (defun org-read-date-display ()
  13102. "Display the current date prompt interpretation in the minibuffer."
  13103. (when org-read-date-display-live
  13104. (when org-read-date-overlay
  13105. (delete-overlay org-read-date-overlay))
  13106. (when (minibufferp (current-buffer))
  13107. (save-excursion
  13108. (end-of-line 1)
  13109. (while (not (equal (buffer-substring
  13110. (max (point-min) (- (point) 4)) (point))
  13111. " "))
  13112. (insert " ")))
  13113. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  13114. " " (or org-ans1 org-ans2)))
  13115. (org-end-time-was-given nil)
  13116. (f (org-read-date-analyze ans org-def org-defdecode))
  13117. (fmts (if org-display-custom-times
  13118. org-time-stamp-custom-formats
  13119. org-time-stamp-formats))
  13120. (fmt (if (or org-with-time
  13121. (and (boundp 'org-time-was-given) org-time-was-given))
  13122. (cdr fmts)
  13123. (car fmts)))
  13124. (txt (format-time-string fmt (apply #'encode-time f)))
  13125. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  13126. (txt (concat "=> " txt)))
  13127. (when (and org-end-time-was-given
  13128. (string-match org-plain-time-of-day-regexp txt))
  13129. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  13130. org-end-time-was-given
  13131. (substring txt (match-end 0)))))
  13132. (when org-read-date-analyze-futurep
  13133. (setq txt (concat txt " (=>F)")))
  13134. (setq org-read-date-overlay
  13135. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  13136. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  13137. (defun org-read-date-analyze (ans def defdecode)
  13138. "Analyze the combined answer of the date prompt."
  13139. ;; FIXME: cleanup and comment
  13140. (let ((org-def def)
  13141. (org-defdecode defdecode)
  13142. (nowdecode (decode-time))
  13143. delta deltan deltaw deltadef year month day
  13144. hour minute second wday pm h2 m2 tl wday1
  13145. iso-year iso-weekday iso-week iso-date futurep kill-year)
  13146. (setq org-read-date-analyze-futurep nil
  13147. org-read-date-analyze-forced-year nil)
  13148. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  13149. (setq ans "+0"))
  13150. (when (setq delta (org-read-date-get-relative ans nil org-def))
  13151. (setq ans (replace-match "" t t ans)
  13152. deltan (car delta)
  13153. deltaw (nth 1 delta)
  13154. deltadef (nth 2 delta)))
  13155. ;; Check if there is an iso week date in there. If yes, store the
  13156. ;; info and postpone interpreting it until the rest of the parsing
  13157. ;; is done.
  13158. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  13159. (setq iso-year (when (match-end 1)
  13160. (org-small-year-to-year
  13161. (string-to-number (match-string 1 ans))))
  13162. iso-weekday (when (match-end 3)
  13163. (string-to-number (match-string 3 ans)))
  13164. iso-week (string-to-number (match-string 2 ans)))
  13165. (setq ans (replace-match "" t t ans)))
  13166. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  13167. (when (string-match
  13168. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  13169. (setq year (if (match-end 2)
  13170. (string-to-number (match-string 2 ans))
  13171. (progn (setq kill-year t)
  13172. (string-to-number (format-time-string "%Y"))))
  13173. month (string-to-number (match-string 3 ans))
  13174. day (string-to-number (match-string 4 ans)))
  13175. (setq year (org-small-year-to-year year))
  13176. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13177. t nil ans)))
  13178. ;; Help matching dotted european dates
  13179. (when (string-match
  13180. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  13181. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  13182. (setq kill-year t)
  13183. (string-to-number (format-time-string "%Y")))
  13184. day (string-to-number (match-string 1 ans))
  13185. month (string-to-number (match-string 2 ans))
  13186. ans (replace-match (format "%04d-%02d-%02d" year month day)
  13187. t nil ans)))
  13188. ;; Help matching american dates, like 5/30 or 5/30/7
  13189. (when (string-match
  13190. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  13191. (setq year (if (match-end 4)
  13192. (string-to-number (match-string 4 ans))
  13193. (progn (setq kill-year t)
  13194. (string-to-number (format-time-string "%Y"))))
  13195. month (string-to-number (match-string 1 ans))
  13196. day (string-to-number (match-string 2 ans)))
  13197. (setq year (org-small-year-to-year year))
  13198. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13199. t nil ans)))
  13200. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  13201. ;; If there is a time with am/pm, and *no* time without it, we convert
  13202. ;; so that matching will be successful.
  13203. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  13204. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  13205. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  13206. (setq hour (string-to-number (match-string 1 ans))
  13207. minute (if (match-end 3)
  13208. (string-to-number (match-string 3 ans))
  13209. 0)
  13210. pm (equal ?p
  13211. (string-to-char (downcase (match-string 4 ans)))))
  13212. (if (and (= hour 12) (not pm))
  13213. (setq hour 0)
  13214. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  13215. (setq ans (replace-match (format "%02d:%02d" hour minute)
  13216. t t ans))))
  13217. ;; Check if a time range is given as a duration
  13218. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  13219. (setq hour (string-to-number (match-string 1 ans))
  13220. h2 (+ hour (string-to-number (match-string 3 ans)))
  13221. minute (string-to-number (match-string 2 ans))
  13222. m2 (+ minute (if (match-end 5) (string-to-number
  13223. (match-string 5 ans))0)))
  13224. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  13225. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  13226. t t ans)))
  13227. ;; Check if there is a time range
  13228. (when (boundp 'org-end-time-was-given)
  13229. (setq org-time-was-given nil)
  13230. (when (and (string-match org-plain-time-of-day-regexp ans)
  13231. (match-end 8))
  13232. (setq org-end-time-was-given (match-string 8 ans))
  13233. (setq ans (concat (substring ans 0 (match-beginning 7))
  13234. (substring ans (match-end 7))))))
  13235. (setq tl (parse-time-string ans)
  13236. day (or (nth 3 tl) (nth 3 org-defdecode))
  13237. month
  13238. (cond ((nth 4 tl))
  13239. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  13240. ;; Day was specified. Make sure DAY+MONTH
  13241. ;; combination happens in the future.
  13242. ((nth 3 tl)
  13243. (setq futurep t)
  13244. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  13245. (nth 4 nowdecode)))
  13246. (t (nth 4 org-defdecode)))
  13247. year
  13248. (cond ((and (not kill-year) (nth 5 tl)))
  13249. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  13250. ;; Month was guessed in the future and is at least
  13251. ;; equal to NOWDECODE's. Fix year accordingly.
  13252. (futurep
  13253. (if (or (> month (nth 4 nowdecode))
  13254. (>= day (nth 3 nowdecode)))
  13255. (nth 5 nowdecode)
  13256. (1+ (nth 5 nowdecode))))
  13257. ;; Month was specified. Make sure MONTH+YEAR
  13258. ;; combination happens in the future.
  13259. ((nth 4 tl)
  13260. (setq futurep t)
  13261. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  13262. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  13263. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  13264. (t (nth 5 nowdecode))))
  13265. (t (nth 5 org-defdecode)))
  13266. hour (or (nth 2 tl) (nth 2 org-defdecode))
  13267. minute (or (nth 1 tl) (nth 1 org-defdecode))
  13268. second (or (nth 0 tl) 0)
  13269. wday (nth 6 tl))
  13270. (when (and (eq org-read-date-prefer-future 'time)
  13271. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  13272. (equal day (nth 3 nowdecode))
  13273. (equal month (nth 4 nowdecode))
  13274. (equal year (nth 5 nowdecode))
  13275. (nth 2 tl)
  13276. (or (< (nth 2 tl) (nth 2 nowdecode))
  13277. (and (= (nth 2 tl) (nth 2 nowdecode))
  13278. (nth 1 tl)
  13279. (< (nth 1 tl) (nth 1 nowdecode)))))
  13280. (setq day (1+ day)
  13281. futurep t))
  13282. ;; Special date definitions below
  13283. (cond
  13284. (iso-week
  13285. ;; There was an iso week
  13286. (require 'cal-iso)
  13287. (setq futurep nil)
  13288. (setq year (or iso-year year)
  13289. day (or iso-weekday wday 1)
  13290. wday nil ; to make sure that the trigger below does not match
  13291. iso-date (calendar-gregorian-from-absolute
  13292. (calendar-iso-to-absolute
  13293. (list iso-week day year))))
  13294. ; FIXME: Should we also push ISO weeks into the future?
  13295. ; (when (and org-read-date-prefer-future
  13296. ; (not iso-year)
  13297. ; (< (calendar-absolute-from-gregorian iso-date)
  13298. ; (time-to-days nil)))
  13299. ; (setq year (1+ year)
  13300. ; iso-date (calendar-gregorian-from-absolute
  13301. ; (calendar-iso-to-absolute
  13302. ; (list iso-week day year)))))
  13303. (setq month (car iso-date)
  13304. year (nth 2 iso-date)
  13305. day (nth 1 iso-date)))
  13306. (deltan
  13307. (setq futurep nil)
  13308. (unless deltadef
  13309. (let ((now (decode-time)))
  13310. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  13311. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  13312. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  13313. ((equal deltaw "m") (setq month (+ month deltan)))
  13314. ((equal deltaw "y") (setq year (+ year deltan)))))
  13315. ((and wday (not (nth 3 tl)))
  13316. ;; Weekday was given, but no day, so pick that day in the week
  13317. ;; on or after the derived date.
  13318. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  13319. (unless (equal wday wday1)
  13320. (setq day (+ day (% (- wday wday1 -7) 7))))))
  13321. (when (and (boundp 'org-time-was-given)
  13322. (nth 2 tl))
  13323. (setq org-time-was-given t))
  13324. (when (< year 100) (setq year (+ 2000 year)))
  13325. ;; Check of the date is representable
  13326. (if org-read-date-force-compatible-dates
  13327. (progn
  13328. (when (< year 1970)
  13329. (setq year 1970 org-read-date-analyze-forced-year t))
  13330. (when (> year 2037)
  13331. (setq year 2037 org-read-date-analyze-forced-year t)))
  13332. (condition-case nil
  13333. (ignore (encode-time second minute hour day month year))
  13334. (error
  13335. (setq year (nth 5 org-defdecode))
  13336. (setq org-read-date-analyze-forced-year t))))
  13337. (setq org-read-date-analyze-futurep futurep)
  13338. (list second minute hour day month year)))
  13339. (defvar parse-time-weekdays)
  13340. (defun org-read-date-get-relative (s today default)
  13341. "Check string S for special relative date string.
  13342. TODAY and DEFAULT are internal times, for today and for a default.
  13343. Return shift list (N what def-flag)
  13344. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  13345. N is the number of WHATs to shift.
  13346. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  13347. the DEFAULT date rather than TODAY."
  13348. (require 'parse-time)
  13349. (when (and
  13350. (string-match
  13351. (concat
  13352. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  13353. "\\([0-9]+\\)?"
  13354. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  13355. "\\([ \t]\\|$\\)") s)
  13356. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  13357. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  13358. (string-to-char (substring (match-string 1 s) -1))
  13359. ?+))
  13360. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  13361. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  13362. (what (if (match-end 3) (match-string 3 s) "d"))
  13363. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  13364. (date (if rel default today))
  13365. (wday (nth 6 (decode-time date)))
  13366. delta)
  13367. (if wday1
  13368. (progn
  13369. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  13370. (when (= delta 0) (setq delta 7))
  13371. (when (= dir ?-)
  13372. (setq delta (- delta 7))
  13373. (when (= delta 0) (setq delta -7)))
  13374. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  13375. (list delta "d" rel))
  13376. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  13377. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  13378. "Turn a user-specified date into the internal representation.
  13379. The internal representation needed by the calendar is (month day year).
  13380. This is a wrapper to handle the brain-dead convention in calendar that
  13381. user function argument order change dependent on argument order."
  13382. (pcase calendar-date-style
  13383. (`american (list arg1 arg2 arg3))
  13384. (`european (list arg2 arg1 arg3))
  13385. (`iso (list arg2 arg3 arg1))))
  13386. (defun org-eval-in-calendar (form &optional keepdate)
  13387. "Eval FORM in the calendar window and return to current window.
  13388. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  13389. (let ((sf (selected-frame))
  13390. (sw (selected-window)))
  13391. (select-window (get-buffer-window "*Calendar*" t))
  13392. (eval form)
  13393. (when (and (not keepdate) (calendar-cursor-to-date))
  13394. (let* ((date (calendar-cursor-to-date))
  13395. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13396. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  13397. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  13398. (select-window sw)
  13399. (select-frame-set-input-focus sf)))
  13400. (defun org-calendar-select ()
  13401. "Return to `org-read-date' with the date currently selected.
  13402. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13403. (interactive)
  13404. (when (calendar-cursor-to-date)
  13405. (let* ((date (calendar-cursor-to-date))
  13406. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13407. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13408. (when (active-minibuffer-window) (exit-minibuffer))))
  13409. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  13410. "Insert a date stamp for the date given by the internal TIME.
  13411. See `format-time-string' for the format of TIME.
  13412. WITH-HM means use the stamp format that includes the time of the day.
  13413. INACTIVE means use square brackets instead of angular ones, so that the
  13414. stamp will not contribute to the agenda.
  13415. PRE and POST are optional strings to be inserted before and after the
  13416. stamp.
  13417. The command returns the inserted time stamp."
  13418. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  13419. stamp)
  13420. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  13421. (insert-before-markers (or pre ""))
  13422. (when (listp extra)
  13423. (setq extra (car extra))
  13424. (if (and (stringp extra)
  13425. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  13426. (setq extra (format "-%02d:%02d"
  13427. (string-to-number (match-string 1 extra))
  13428. (string-to-number (match-string 2 extra))))
  13429. (setq extra nil)))
  13430. (when extra
  13431. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  13432. (insert-before-markers (setq stamp (format-time-string fmt time)))
  13433. (insert-before-markers (or post ""))
  13434. (setq org-last-inserted-timestamp stamp)))
  13435. (defun org-toggle-time-stamp-overlays ()
  13436. "Toggle the use of custom time stamp formats."
  13437. (interactive)
  13438. (setq org-display-custom-times (not org-display-custom-times))
  13439. (unless org-display-custom-times
  13440. (let ((p (point-min)) (bmp (buffer-modified-p)))
  13441. (while (setq p (next-single-property-change p 'display))
  13442. (when (and (get-text-property p 'display)
  13443. (eq (get-text-property p 'face) 'org-date))
  13444. (remove-text-properties
  13445. p (setq p (next-single-property-change p 'display))
  13446. '(display t))))
  13447. (set-buffer-modified-p bmp)))
  13448. (org-restart-font-lock)
  13449. (setq org-table-may-need-update t)
  13450. (if org-display-custom-times
  13451. (message "Time stamps are overlaid with custom format")
  13452. (message "Time stamp overlays removed")))
  13453. (defun org-display-custom-time (beg end)
  13454. "Overlay modified time stamp format over timestamp between BEG and END."
  13455. (let* ((ts (buffer-substring beg end))
  13456. t1 with-hm tf time str (off 0))
  13457. (save-match-data
  13458. (setq t1 (org-parse-time-string ts t))
  13459. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  13460. (setq off (- (match-end 0) (match-beginning 0)))))
  13461. (setq end (- end off))
  13462. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  13463. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  13464. time (org-fix-decoded-time t1)
  13465. str (org-add-props
  13466. (format-time-string
  13467. (substring tf 1 -1) (apply 'encode-time time))
  13468. nil 'mouse-face 'highlight))
  13469. (put-text-property beg end 'display str)))
  13470. (defun org-fix-decoded-time (time)
  13471. "Set 0 instead of nil for the first 6 elements of time.
  13472. Don't touch the rest."
  13473. (let ((n 0))
  13474. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  13475. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  13476. "Difference between TIMESTAMP-STRING and now in days.
  13477. If SECONDS is non-nil, return the difference in seconds."
  13478. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  13479. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  13480. (funcall fdiff nil))))
  13481. (defun org-deadline-close-p (timestamp-string &optional ndays)
  13482. "Is the time in TIMESTAMP-STRING close to the current date?"
  13483. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  13484. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  13485. (not (org-entry-is-done-p))))
  13486. (defun org-get-wdays (ts &optional delay zero-delay)
  13487. "Get the deadline lead time appropriate for timestring TS.
  13488. When DELAY is non-nil, get the delay time for scheduled items
  13489. instead of the deadline lead time. When ZERO-DELAY is non-nil
  13490. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  13491. don't try to find the delay cookie in the scheduled timestamp."
  13492. (let ((tv (if delay org-scheduled-delay-days
  13493. org-deadline-warning-days)))
  13494. (cond
  13495. ((or (and delay (< tv 0))
  13496. (and delay zero-delay (<= tv 0))
  13497. (and (not delay) (<= tv 0)))
  13498. ;; Enforce this value no matter what
  13499. (- tv))
  13500. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  13501. ;; lead time is specified.
  13502. (floor (* (string-to-number (match-string 1 ts))
  13503. (cdr (assoc (match-string 2 ts)
  13504. '(("d" . 1) ("w" . 7)
  13505. ("m" . 30.4) ("y" . 365.25)
  13506. ("h" . 0.041667)))))))
  13507. ;; go for the default.
  13508. (t tv))))
  13509. (defun org-calendar-select-mouse (ev)
  13510. "Return to `org-read-date' with the date currently selected.
  13511. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13512. (interactive "e")
  13513. (mouse-set-point ev)
  13514. (when (calendar-cursor-to-date)
  13515. (let* ((date (calendar-cursor-to-date))
  13516. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13517. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13518. (when (active-minibuffer-window) (exit-minibuffer))))
  13519. (defun org-check-deadlines (ndays)
  13520. "Check if there are any deadlines due or past due.
  13521. A deadline is considered due if it happens within `org-deadline-warning-days'
  13522. days from today's date. If the deadline appears in an entry marked DONE,
  13523. it is not shown. A numeric prefix argument NDAYS can be used to test that
  13524. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  13525. are shown."
  13526. (interactive "P")
  13527. (let* ((org-warn-days
  13528. (cond
  13529. ((equal ndays '(4)) 100000)
  13530. (ndays (prefix-numeric-value ndays))
  13531. (t (abs org-deadline-warning-days))))
  13532. (case-fold-search nil)
  13533. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  13534. (callback
  13535. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  13536. (message "%d deadlines past-due or due within %d days"
  13537. (org-occur regexp nil callback)
  13538. org-warn-days)))
  13539. (defsubst org-re-timestamp (type)
  13540. "Return a regexp for timestamp TYPE.
  13541. Allowed values for TYPE are:
  13542. all: all timestamps
  13543. active: only active timestamps (<...>)
  13544. inactive: only inactive timestamps ([...])
  13545. scheduled: only scheduled timestamps
  13546. deadline: only deadline timestamps
  13547. closed: only closed time-stamps
  13548. When TYPE is nil, fall back on returning a regexp that matches
  13549. both scheduled and deadline timestamps."
  13550. (cl-case type
  13551. (all org-ts-regexp-both)
  13552. (active org-ts-regexp)
  13553. (inactive org-ts-regexp-inactive)
  13554. (scheduled org-scheduled-time-regexp)
  13555. (deadline org-deadline-time-regexp)
  13556. (closed org-closed-time-regexp)
  13557. (otherwise
  13558. (concat "\\<"
  13559. (regexp-opt (list org-deadline-string org-scheduled-string))
  13560. " *<\\([^>]+\\)>"))))
  13561. (defun org-check-before-date (d)
  13562. "Check if there are deadlines or scheduled entries before date D."
  13563. (interactive (list (org-read-date)))
  13564. (let* ((case-fold-search nil)
  13565. (regexp (org-re-timestamp org-ts-type))
  13566. (ts-type org-ts-type)
  13567. (callback
  13568. (lambda ()
  13569. (let ((match (match-string 1)))
  13570. (and (if (memq ts-type '(active inactive all))
  13571. (eq (org-element-type (save-excursion
  13572. (backward-char)
  13573. (org-element-context)))
  13574. 'timestamp)
  13575. (org-at-planning-p))
  13576. (time-less-p
  13577. (org-time-string-to-time match)
  13578. (org-time-string-to-time d)))))))
  13579. (message "%d entries before %s"
  13580. (org-occur regexp nil callback)
  13581. d)))
  13582. (defun org-check-after-date (d)
  13583. "Check if there are deadlines or scheduled entries after date D."
  13584. (interactive (list (org-read-date)))
  13585. (let* ((case-fold-search nil)
  13586. (regexp (org-re-timestamp org-ts-type))
  13587. (ts-type org-ts-type)
  13588. (callback
  13589. (lambda ()
  13590. (let ((match (match-string 1)))
  13591. (and (if (memq ts-type '(active inactive all))
  13592. (eq (org-element-type (save-excursion
  13593. (backward-char)
  13594. (org-element-context)))
  13595. 'timestamp)
  13596. (org-at-planning-p))
  13597. (not (time-less-p
  13598. (org-time-string-to-time match)
  13599. (org-time-string-to-time d))))))))
  13600. (message "%d entries after %s"
  13601. (org-occur regexp nil callback)
  13602. d)))
  13603. (defun org-check-dates-range (start-date end-date)
  13604. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13605. (interactive (list (org-read-date nil nil nil "Range starts")
  13606. (org-read-date nil nil nil "Range end")))
  13607. (let ((case-fold-search nil)
  13608. (regexp (org-re-timestamp org-ts-type))
  13609. (callback
  13610. (let ((type org-ts-type))
  13611. (lambda ()
  13612. (let ((match (match-string 1)))
  13613. (and
  13614. (if (memq type '(active inactive all))
  13615. (eq (org-element-type (save-excursion
  13616. (backward-char)
  13617. (org-element-context)))
  13618. 'timestamp)
  13619. (org-at-planning-p))
  13620. (not (time-less-p
  13621. (org-time-string-to-time match)
  13622. (org-time-string-to-time start-date)))
  13623. (time-less-p
  13624. (org-time-string-to-time match)
  13625. (org-time-string-to-time end-date))))))))
  13626. (message "%d entries between %s and %s"
  13627. (org-occur regexp nil callback) start-date end-date)))
  13628. (defun org-evaluate-time-range (&optional to-buffer)
  13629. "Evaluate a time range by computing the difference between start and end.
  13630. Normally the result is just printed in the echo area, but with prefix arg
  13631. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13632. If the time range is actually in a table, the result is inserted into the
  13633. next column.
  13634. For time difference computation, a year is assumed to be exactly 365
  13635. days in order to avoid rounding problems."
  13636. (interactive "P")
  13637. (or
  13638. (org-clock-update-time-maybe)
  13639. (save-excursion
  13640. (unless (org-at-date-range-p t)
  13641. (goto-char (point-at-bol))
  13642. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13643. (unless (org-at-date-range-p t)
  13644. (user-error "Not at a time-stamp range, and none found in current line")))
  13645. (let* ((ts1 (match-string 1))
  13646. (ts2 (match-string 2))
  13647. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13648. (match-end (match-end 0))
  13649. (time1 (org-time-string-to-time ts1))
  13650. (time2 (org-time-string-to-time ts2))
  13651. (diff (abs (float-time (time-subtract time2 time1))))
  13652. (negative (time-less-p time2 time1))
  13653. ;; (ys (floor (* 365 24 60 60)))
  13654. (ds (* 24 60 60))
  13655. (hs (* 60 60))
  13656. (fy "%dy %dd %02d:%02d")
  13657. (fy1 "%dy %dd")
  13658. (fd "%dd %02d:%02d")
  13659. (fd1 "%dd")
  13660. (fh "%02d:%02d")
  13661. y d h m align)
  13662. (if havetime
  13663. (setq ; y (floor diff ys) diff (mod diff ys)
  13664. y 0
  13665. d (floor diff ds) diff (mod diff ds)
  13666. h (floor diff hs) diff (mod diff hs)
  13667. m (floor diff 60))
  13668. (setq ; y (floor diff ys) diff (mod diff ys)
  13669. y 0
  13670. d (round diff ds)
  13671. h 0 m 0))
  13672. (if (not to-buffer)
  13673. (message "%s" (org-make-tdiff-string y d h m))
  13674. (if (org-at-table-p)
  13675. (progn
  13676. (goto-char match-end)
  13677. (setq align t)
  13678. (and (looking-at " *|") (goto-char (match-end 0))))
  13679. (goto-char match-end))
  13680. (when (looking-at
  13681. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13682. (replace-match ""))
  13683. (when negative (insert " -"))
  13684. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13685. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13686. (insert " " (format fh h m))))
  13687. (when align (org-table-align))
  13688. (message "Time difference inserted")))))
  13689. (defun org-make-tdiff-string (y d h m)
  13690. (let ((fmt "")
  13691. (l nil))
  13692. (when (> y 0)
  13693. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13694. (push y l))
  13695. (when (> d 0)
  13696. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13697. (push d l))
  13698. (when (> h 0)
  13699. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13700. (push h l))
  13701. (when (> m 0)
  13702. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13703. (push m l))
  13704. (apply 'format fmt (nreverse l))))
  13705. (defun org-time-string-to-time (s)
  13706. "Convert timestamp string S into internal time."
  13707. (apply #'encode-time (org-parse-time-string s)))
  13708. (defun org-time-string-to-seconds (s)
  13709. "Convert a timestamp string S into a number of seconds."
  13710. (float-time (org-time-string-to-time s)))
  13711. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13712. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13713. "Convert time stamp S to an absolute day number.
  13714. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13715. stamp, get the closest date to DAYNR. If PREFER is
  13716. `past' (respectively `future') return a date past (respectively
  13717. after) or equal to DAYNR.
  13718. POS is the location of time stamp S, as a buffer position in
  13719. BUFFER.
  13720. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13721. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13722. signaled."
  13723. (cond
  13724. ((string-match "\\`%%\\((.*)\\)" s)
  13725. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13726. ;; only able to match individual dates. If it fails, raise an
  13727. ;; error.
  13728. (if (and daynr
  13729. (org-diary-sexp-entry
  13730. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13731. daynr
  13732. (signal 'org-diary-sexp-no-match (list s))))
  13733. (daynr (org-closest-date s daynr prefer))
  13734. (t (time-to-days
  13735. (condition-case errdata
  13736. (org-time-string-to-time s)
  13737. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13738. s
  13739. (if (not (and buffer pos)) ""
  13740. (format-message " at %d in buffer `%s'" pos buffer))
  13741. (cdr errdata))))))))
  13742. (defun org-days-to-iso-week (days)
  13743. "Return the iso week number."
  13744. (require 'cal-iso)
  13745. (car (calendar-iso-from-absolute days)))
  13746. (defun org-small-year-to-year (year)
  13747. "Convert 2-digit years into 4-digit years.
  13748. YEAR is expanded into one of the 30 next years, if possible, or
  13749. into a past one. Any year larger than 99 is returned unchanged."
  13750. (if (>= year 100) year
  13751. (let* ((current (string-to-number (format-time-string "%Y")))
  13752. (century (/ current 100))
  13753. (offset (- year (% current 100))))
  13754. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13755. ((> offset -70) (+ (* century 100) year))
  13756. (t (+ (* (1+ century) 100) year))))))
  13757. (defun org-time-from-absolute (d)
  13758. "Return the time corresponding to date D.
  13759. D may be an absolute day number, or a calendar-type list (month day year)."
  13760. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13761. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13762. (defvar org-agenda-current-date)
  13763. (defun org-calendar-holiday ()
  13764. "List of holidays, for Diary display in Org mode."
  13765. (require 'holidays)
  13766. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13767. (and hl (mapconcat #'identity hl "; "))))
  13768. (defun org-diary-sexp-entry (sexp entry d)
  13769. "Process a SEXP diary ENTRY for date D."
  13770. (require 'diary-lib)
  13771. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13772. ;; dynamically.
  13773. (let* ((sexp `(let ((entry ,entry)
  13774. (date ',d))
  13775. ,(car (read-from-string sexp))))
  13776. (result (if calendar-debug-sexp (eval sexp)
  13777. (condition-case nil
  13778. (eval sexp)
  13779. (error
  13780. (beep)
  13781. (message "Bad sexp at line %d in %s: %s"
  13782. (org-current-line)
  13783. (buffer-file-name) sexp)
  13784. (sleep-for 2))))))
  13785. (cond ((stringp result) (split-string result "; "))
  13786. ((and (consp result)
  13787. (not (consp (cdr result)))
  13788. (stringp (cdr result))) (cdr result))
  13789. ((and (consp result)
  13790. (stringp (car result))) result)
  13791. (result entry))))
  13792. (defun org-diary-to-ical-string (frombuf)
  13793. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13794. This uses the icalendar.el library."
  13795. (let* ((tmpdir temporary-file-directory)
  13796. (tmpfile (make-temp-name
  13797. (expand-file-name "orgics" tmpdir)))
  13798. buf rtn b e)
  13799. (with-current-buffer frombuf
  13800. (icalendar-export-region (point-min) (point-max) tmpfile)
  13801. (setq buf (find-buffer-visiting tmpfile))
  13802. (set-buffer buf)
  13803. (goto-char (point-min))
  13804. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13805. (setq b (match-beginning 0)))
  13806. (goto-char (point-max))
  13807. (when (re-search-backward "^END:VEVENT" nil t)
  13808. (setq e (match-end 0)))
  13809. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13810. (kill-buffer buf)
  13811. (delete-file tmpfile)
  13812. rtn))
  13813. (defun org-closest-date (start current prefer)
  13814. "Return closest date to CURRENT starting from START.
  13815. CURRENT and START are both time stamps.
  13816. When PREFER is `past', return a date that is either CURRENT or
  13817. past. When PREFER is `future', return a date that is either
  13818. CURRENT or future.
  13819. Only time stamps with a repeater are modified. Any other time
  13820. stamp stay unchanged. In any case, return value is an absolute
  13821. day number."
  13822. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13823. ;; No repeater. Do not shift time stamp.
  13824. (time-to-days (org-time-string-to-time start))
  13825. (let ((value (string-to-number (match-string 1 start)))
  13826. (type (match-string 2 start)))
  13827. (if (= 0 value)
  13828. ;; Repeater with a 0-value is considered as void.
  13829. (time-to-days (org-time-string-to-time start))
  13830. (let* ((base (org-date-to-gregorian start))
  13831. (target (org-date-to-gregorian current))
  13832. (sday (calendar-absolute-from-gregorian base))
  13833. (cday (calendar-absolute-from-gregorian target))
  13834. n1 n2)
  13835. ;; If START is already past CURRENT, just return START.
  13836. (if (<= cday sday) sday
  13837. ;; Compute closest date before (N1) and closest date past
  13838. ;; (N2) CURRENT.
  13839. (pcase type
  13840. ("h"
  13841. (let ((missing-hours
  13842. (mod (+ (- (* 24 (- cday sday))
  13843. (nth 2 (org-parse-time-string start)))
  13844. org-extend-today-until)
  13845. value)))
  13846. (setf n1 (if (= missing-hours 0) cday
  13847. (- cday (1+ (/ missing-hours 24)))))
  13848. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13849. ((or "d" "w")
  13850. (let ((value (if (equal type "w") (* 7 value) value)))
  13851. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13852. (setf n2 (+ n1 value))))
  13853. ("m"
  13854. (let* ((add-months
  13855. (lambda (d n)
  13856. ;; Add N months to gregorian date D, i.e.,
  13857. ;; a list (MONTH DAY YEAR). Return a valid
  13858. ;; gregorian date.
  13859. (let ((m (+ (nth 0 d) n)))
  13860. (list (mod m 12)
  13861. (nth 1 d)
  13862. (+ (/ m 12) (nth 2 d))))))
  13863. (months ; Complete months to TARGET.
  13864. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13865. (- (nth 0 target) (nth 0 base))
  13866. ;; If START's day is greater than
  13867. ;; TARGET's, remove incomplete month.
  13868. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13869. value)
  13870. value))
  13871. (before (funcall add-months base months)))
  13872. (setf n1 (calendar-absolute-from-gregorian before))
  13873. (setf n2
  13874. (calendar-absolute-from-gregorian
  13875. (funcall add-months before value)))))
  13876. (_
  13877. (let* ((d (nth 1 base))
  13878. (m (nth 0 base))
  13879. (y (nth 2 base))
  13880. (years ; Complete years to TARGET.
  13881. (* (/ (- (nth 2 target)
  13882. y
  13883. ;; If START's month and day are
  13884. ;; greater than TARGET's, remove
  13885. ;; incomplete year.
  13886. (if (or (> (nth 0 target) m)
  13887. (and (= (nth 0 target) m)
  13888. (> (nth 1 target) d)))
  13889. 0
  13890. 1))
  13891. value)
  13892. value))
  13893. (before (list m d (+ y years))))
  13894. (setf n1 (calendar-absolute-from-gregorian before))
  13895. (setf n2 (calendar-absolute-from-gregorian
  13896. (list m d (+ (nth 2 before) value)))))))
  13897. ;; Handle PREFER parameter, if any.
  13898. (cond
  13899. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13900. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13901. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13902. (defun org-date-to-gregorian (d)
  13903. "Turn any specification of date D into a Gregorian date for the calendar."
  13904. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13905. ((and (listp d) (= (length d) 3)) d)
  13906. ((stringp d)
  13907. (let ((d (org-parse-time-string d)))
  13908. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13909. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13910. (defun org-timestamp-up (&optional arg)
  13911. "Increase the date item at the cursor by one.
  13912. If the cursor is on the year, change the year. If it is on the month,
  13913. the day or the time, change that. If the cursor is on the enclosing
  13914. bracket, change the timestamp type.
  13915. With prefix ARG, change by that many units."
  13916. (interactive "p")
  13917. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13918. (defun org-timestamp-down (&optional arg)
  13919. "Decrease the date item at the cursor by one.
  13920. If the cursor is on the year, change the year. If it is on the month,
  13921. the day or the time, change that. If the cursor is on the enclosing
  13922. bracket, change the timestamp type.
  13923. With prefix ARG, change by that many units."
  13924. (interactive "p")
  13925. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13926. (defun org-timestamp-up-day (&optional arg)
  13927. "Increase the date in the time stamp by one day.
  13928. With prefix ARG, change that many days."
  13929. (interactive "p")
  13930. (if (and (not (org-at-timestamp-p 'lax))
  13931. (org-at-heading-p))
  13932. (org-todo 'up)
  13933. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13934. (defun org-timestamp-down-day (&optional arg)
  13935. "Decrease the date in the time stamp by one day.
  13936. With prefix ARG, change that many days."
  13937. (interactive "p")
  13938. (if (and (not (org-at-timestamp-p 'lax))
  13939. (org-at-heading-p))
  13940. (org-todo 'down)
  13941. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13942. (defun org-at-timestamp-p (&optional extended)
  13943. "Non-nil if point is inside a timestamp.
  13944. By default, the function only consider syntactically valid active
  13945. timestamps. However, the caller may have a broader definition
  13946. for timestamps. As a consequence, optional argument EXTENDED can
  13947. be set to the following values
  13948. `inactive'
  13949. Include also syntactically valid inactive timestamps.
  13950. `agenda'
  13951. Include timestamps allowed in Agenda, i.e., those in
  13952. properties drawers, planning lines and clock lines.
  13953. `lax'
  13954. Ignore context. The function matches any part of the
  13955. document looking like a timestamp. This includes comments,
  13956. example blocks...
  13957. For backward-compatibility with Org 9.0, every other non-nil
  13958. value is equivalent to `inactive'.
  13959. When at a timestamp, return the position of the point as a symbol
  13960. among `bracket', `after', `year', `month', `hour', `minute',
  13961. `day' or a number of character from the last know part of the
  13962. time stamp.
  13963. When matching, the match groups are the following:
  13964. group 1: year
  13965. group 2: month
  13966. group 3: day number
  13967. group 4: day name
  13968. group 5: hours, if any
  13969. group 6: minutes, if any"
  13970. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13971. (pos (point))
  13972. (match?
  13973. (let ((boundaries (org-in-regexp regexp)))
  13974. (save-match-data
  13975. (cond ((null boundaries) nil)
  13976. ((eq extended 'lax) t)
  13977. (t
  13978. (or (and (eq extended 'agenda)
  13979. (or (org-at-planning-p)
  13980. (org-at-property-p)
  13981. (and (bound-and-true-p
  13982. org-agenda-include-inactive-timestamps)
  13983. (org-at-clock-log-p))))
  13984. (eq 'timestamp
  13985. (save-excursion
  13986. (when (= pos (cdr boundaries)) (forward-char -1))
  13987. (org-element-type (org-element-context)))))))))))
  13988. (cond
  13989. ((not match?) nil)
  13990. ((= pos (match-beginning 0)) 'bracket)
  13991. ;; Distinguish location right before the closing bracket from
  13992. ;; right after it.
  13993. ((= pos (1- (match-end 0))) 'bracket)
  13994. ((= pos (match-end 0)) 'after)
  13995. ((org-pos-in-match-range pos 2) 'year)
  13996. ((org-pos-in-match-range pos 3) 'month)
  13997. ((org-pos-in-match-range pos 7) 'hour)
  13998. ((org-pos-in-match-range pos 8) 'minute)
  13999. ((or (org-pos-in-match-range pos 4)
  14000. (org-pos-in-match-range pos 5)) 'day)
  14001. ((and (> pos (or (match-end 8) (match-end 5)))
  14002. (< pos (match-end 0)))
  14003. (- pos (or (match-end 8) (match-end 5))))
  14004. (t 'day))))
  14005. (defun org-toggle-timestamp-type ()
  14006. "Toggle the type (<active> or [inactive]) of a time stamp."
  14007. (interactive)
  14008. (when (org-at-timestamp-p 'lax)
  14009. (let ((beg (match-beginning 0)) (end (match-end 0))
  14010. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  14011. (save-excursion
  14012. (goto-char beg)
  14013. (while (re-search-forward "[][<>]" end t)
  14014. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  14015. t t)))
  14016. (message "Timestamp is now %sactive"
  14017. (if (equal (char-after beg) ?<) "" "in")))))
  14018. (defun org-at-clock-log-p ()
  14019. "Non-nil if point is on a clock log line."
  14020. (and (org-match-line org-clock-line-re)
  14021. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  14022. (defvar org-clock-history) ; defined in org-clock.el
  14023. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  14024. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  14025. "Change the date in the time stamp at point.
  14026. The date is changed by N times WHAT. WHAT can be `day', `month',
  14027. `year', `hour', or `minute'. If WHAT is not given, the cursor
  14028. position in the timestamp determines what is changed.
  14029. When optional argument UPDOWN is non-nil, minutes are rounded
  14030. according to `org-time-stamp-rounding-minutes'.
  14031. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  14032. \"--2d\"."
  14033. (let ((origin (point))
  14034. (timestamp? (org-at-timestamp-p 'lax))
  14035. origin-cat
  14036. with-hm inactive
  14037. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  14038. extra rem
  14039. ts time time0 fixnext clrgx)
  14040. (unless timestamp? (user-error "Not at a timestamp"))
  14041. (if (and (not what) (eq timestamp? 'bracket))
  14042. (org-toggle-timestamp-type)
  14043. ;; Point isn't on brackets. Remember the part of the time-stamp
  14044. ;; the point was in. Indeed, size of time-stamps may change,
  14045. ;; but point must be kept in the same category nonetheless.
  14046. (setq origin-cat timestamp?)
  14047. (when (and (not what) (not (eq timestamp? 'day))
  14048. org-display-custom-times
  14049. (get-text-property (point) 'display)
  14050. (not (get-text-property (1- (point)) 'display)))
  14051. (setq timestamp? 'day))
  14052. (setq timestamp? (or what timestamp?)
  14053. inactive (= (char-after (match-beginning 0)) ?\[)
  14054. ts (match-string 0))
  14055. (replace-match "")
  14056. (when (string-match
  14057. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  14058. ts)
  14059. (setq extra (match-string 1 ts))
  14060. (when suppress-tmp-delay
  14061. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  14062. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  14063. (setq with-hm t))
  14064. (setq time0 (org-parse-time-string ts))
  14065. (when (and updown
  14066. (eq timestamp? 'minute)
  14067. (not current-prefix-arg))
  14068. ;; This looks like s-up and s-down. Change by one rounding step.
  14069. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  14070. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  14071. (setcar (cdr time0) (+ (nth 1 time0)
  14072. (if (> n 0) (- rem) (- dm rem))))))
  14073. (setq time
  14074. (apply #'encode-time
  14075. (or (car time0) 0)
  14076. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  14077. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  14078. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  14079. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  14080. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  14081. (nthcdr 6 time0)))
  14082. (when (and (memq timestamp? '(hour minute))
  14083. extra
  14084. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  14085. (setq extra (org-modify-ts-extra
  14086. extra
  14087. (if (eq timestamp? 'hour) 2 5)
  14088. n dm)))
  14089. (when (integerp timestamp?)
  14090. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  14091. (when (eq what 'calendar)
  14092. (let ((cal-date (org-get-date-from-calendar)))
  14093. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  14094. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  14095. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  14096. (setcar time0 (or (car time0) 0))
  14097. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  14098. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  14099. (setq time (apply 'encode-time time0))))
  14100. ;; Insert the new time-stamp, and ensure point stays in the same
  14101. ;; category as before (i.e. not after the last position in that
  14102. ;; category).
  14103. (let ((pos (point)))
  14104. ;; Stay before inserted string. `save-excursion' is of no use.
  14105. (setq org-last-changed-timestamp
  14106. (org-insert-time-stamp time with-hm inactive nil nil extra))
  14107. (goto-char pos))
  14108. (save-match-data
  14109. (looking-at org-ts-regexp3)
  14110. (goto-char
  14111. (pcase origin-cat
  14112. ;; `day' category ends before `hour' if any, or at the end
  14113. ;; of the day name.
  14114. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  14115. (`hour (min (match-end 7) origin))
  14116. (`minute (min (1- (match-end 8)) origin))
  14117. ((pred integerp) (min (1- (match-end 0)) origin))
  14118. ;; Point was right after the time-stamp. However, the
  14119. ;; time-stamp length might have changed, so refer to
  14120. ;; (match-end 0) instead.
  14121. (`after (match-end 0))
  14122. ;; `year' and `month' have both fixed size: point couldn't
  14123. ;; have moved into another part.
  14124. (_ origin))))
  14125. ;; Update clock if on a CLOCK line.
  14126. (org-clock-update-time-maybe)
  14127. ;; Maybe adjust the closest clock in `org-clock-history'
  14128. (when org-clock-adjust-closest
  14129. (if (not (and (org-at-clock-log-p)
  14130. (< 1 (length (delq nil (mapcar 'marker-position
  14131. org-clock-history))))))
  14132. (message "No clock to adjust")
  14133. (cond ((save-excursion ; fix previous clock?
  14134. (re-search-backward org-ts-regexp0 nil t)
  14135. (looking-back (concat org-clock-string " \\[")
  14136. (line-beginning-position)))
  14137. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  14138. ((save-excursion ; fix next clock?
  14139. (re-search-backward org-ts-regexp0 nil t)
  14140. (looking-at (concat org-ts-regexp0 "\\] =>")))
  14141. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  14142. (save-window-excursion
  14143. ;; Find closest clock to point, adjust the previous/next one in history
  14144. (let* ((p (save-excursion (org-back-to-heading t)))
  14145. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  14146. (clfixnth
  14147. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  14148. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  14149. (if (not clfixpos)
  14150. (message "No clock to adjust")
  14151. (save-excursion
  14152. (org-goto-marker-or-bmk clfixpos)
  14153. (org-show-subtree)
  14154. (when (re-search-forward clrgx nil t)
  14155. (goto-char (match-beginning 1))
  14156. (let (org-clock-adjust-closest)
  14157. (org-timestamp-change n timestamp? updown))
  14158. (message "Clock adjusted in %s for heading: %s"
  14159. (file-name-nondirectory (buffer-file-name))
  14160. (org-get-heading t t)))))))))
  14161. ;; Try to recenter the calendar window, if any.
  14162. (when (and org-calendar-follow-timestamp-change
  14163. (get-buffer-window "*Calendar*" t)
  14164. (memq timestamp? '(day month year)))
  14165. (org-recenter-calendar (time-to-days time))))))
  14166. (defun org-modify-ts-extra (s pos n dm)
  14167. "Change the different parts of the lead-time and repeat fields in timestamp."
  14168. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  14169. ng h m new rem)
  14170. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  14171. (cond
  14172. ((or (org-pos-in-match-range pos 2)
  14173. (org-pos-in-match-range pos 3))
  14174. (setq m (string-to-number (match-string 3 s))
  14175. h (string-to-number (match-string 2 s)))
  14176. (if (org-pos-in-match-range pos 2)
  14177. (setq h (+ h n))
  14178. (setq n (* dm (with-no-warnings (cl-signum n))))
  14179. (unless (= 0 (setq rem (% m dm)))
  14180. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  14181. (setq m (+ m n)))
  14182. (when (< m 0) (setq m (+ m 60) h (1- h)))
  14183. (when (> m 59) (setq m (- m 60) h (1+ h)))
  14184. (setq h (mod h 24))
  14185. (setq ng 1 new (format "-%02d:%02d" h m)))
  14186. ((org-pos-in-match-range pos 6)
  14187. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  14188. ((org-pos-in-match-range pos 5)
  14189. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  14190. ((org-pos-in-match-range pos 9)
  14191. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  14192. ((org-pos-in-match-range pos 8)
  14193. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  14194. (when ng
  14195. (setq s (concat
  14196. (substring s 0 (match-beginning ng))
  14197. new
  14198. (substring s (match-end ng))))))
  14199. s))
  14200. (defun org-recenter-calendar (d)
  14201. "If the calendar is visible, recenter it to date D."
  14202. (let ((cwin (get-buffer-window "*Calendar*" t)))
  14203. (when cwin
  14204. (let ((calendar-move-hook nil))
  14205. (with-selected-window cwin
  14206. (calendar-goto-date
  14207. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  14208. (defun org-goto-calendar (&optional arg)
  14209. "Go to the Emacs calendar at the current date.
  14210. If there is a time stamp in the current line, go to that date.
  14211. A prefix ARG can be used to force the current date."
  14212. (interactive "P")
  14213. (let ((calendar-move-hook nil)
  14214. (calendar-view-holidays-initially-flag nil)
  14215. (calendar-view-diary-initially-flag nil)
  14216. diff)
  14217. (when (or (org-at-timestamp-p 'lax)
  14218. (org-match-line (concat ".*" org-ts-regexp)))
  14219. (let ((d1 (time-to-days nil))
  14220. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  14221. (setq diff (- d2 d1))))
  14222. (calendar)
  14223. (calendar-goto-today)
  14224. (when (and diff (not arg)) (calendar-forward-day diff))))
  14225. (defun org-get-date-from-calendar ()
  14226. "Return a list (month day year) of date at point in calendar."
  14227. (with-current-buffer "*Calendar*"
  14228. (save-match-data
  14229. (calendar-cursor-to-date))))
  14230. (defun org-date-from-calendar ()
  14231. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  14232. If there is already a time stamp at the cursor position, update it."
  14233. (interactive)
  14234. (if (org-at-timestamp-p 'lax)
  14235. (org-timestamp-change 0 'calendar)
  14236. (let ((cal-date (org-get-date-from-calendar)))
  14237. (org-insert-time-stamp
  14238. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  14239. (defcustom org-image-actual-width t
  14240. "When non-nil, use the actual width of images when inlining them.
  14241. When set to a number, use imagemagick (when available) to set the
  14242. image's width to this value.
  14243. When set to a number in a list, try to get the width from any
  14244. #+ATTR.* keyword if it matches a width specification like
  14245. #+ATTR_HTML: :width 300px
  14246. and fall back on that number if none is found.
  14247. When set to nil, try to get the width from an #+ATTR.* keyword
  14248. and fall back on the original width if none is found.
  14249. When set to any other non-nil value, always use the image width.
  14250. This requires Emacs >= 24.1, built with imagemagick support."
  14251. :group 'org-appearance
  14252. :version "24.4"
  14253. :package-version '(Org . "8.0")
  14254. :type '(choice
  14255. (const :tag "Use the image width" t)
  14256. (integer :tag "Use a number of pixels")
  14257. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  14258. (const :tag "Use #+ATTR* or don't resize" nil)))
  14259. (defcustom org-agenda-inhibit-startup nil
  14260. "Inhibit startup when preparing agenda buffers.
  14261. When this variable is t, the initialization of the Org agenda
  14262. buffers is inhibited: e.g. the visibility state is not set, the
  14263. tables are not re-aligned, etc."
  14264. :type 'boolean
  14265. :version "24.3"
  14266. :group 'org-agenda)
  14267. (defcustom org-agenda-ignore-properties nil
  14268. "Avoid updating text properties when building the agenda.
  14269. Properties are used to prepare buffers for effort estimates,
  14270. appointments, statistics and subtree-local categories.
  14271. If you don't use these in the agenda, you can add them to this
  14272. list and agenda building will be a bit faster.
  14273. The value is a list, with zero or more of the symbols `effort', `appt',
  14274. `stats' or `category'."
  14275. :type '(set :greedy t
  14276. (const effort)
  14277. (const appt)
  14278. (const stats)
  14279. (const category))
  14280. :version "26.1"
  14281. :package-version '(Org . "8.3")
  14282. :group 'org-agenda)
  14283. ;;;; Files
  14284. (defun org-save-all-org-buffers ()
  14285. "Save all Org buffers without user confirmation."
  14286. (interactive)
  14287. (message "Saving all Org buffers...")
  14288. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  14289. (when (featurep 'org-id) (org-id-locations-save))
  14290. (message "Saving all Org buffers... done"))
  14291. (defun org-revert-all-org-buffers ()
  14292. "Revert all Org buffers.
  14293. Prompt for confirmation when there are unsaved changes.
  14294. Be sure you know what you are doing before letting this function
  14295. overwrite your changes.
  14296. This function is useful in a setup where one tracks Org files
  14297. with a version control system, to revert on one machine after pulling
  14298. changes from another. I believe the procedure must be like this:
  14299. 1. M-x org-save-all-org-buffers
  14300. 2. Pull changes from the other machine, resolve conflicts
  14301. 3. M-x org-revert-all-org-buffers"
  14302. (interactive)
  14303. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  14304. (user-error "Abort"))
  14305. (save-excursion
  14306. (save-window-excursion
  14307. (dolist (b (buffer-list))
  14308. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  14309. (with-current-buffer b buffer-file-name))
  14310. (pop-to-buffer-same-window b)
  14311. (revert-buffer t 'no-confirm)))
  14312. (when (and (featurep 'org-id) org-id-track-globally)
  14313. (org-id-locations-load)))))
  14314. ;;;; Agenda files
  14315. ;;;###autoload
  14316. (defun org-switchb (&optional arg)
  14317. "Switch between Org buffers.
  14318. With `\\[universal-argument]' prefix, restrict available buffers to files.
  14319. With `\\[universal-argument] \\[universal-argument]' \
  14320. prefix, restrict available buffers to agenda files."
  14321. (interactive "P")
  14322. (let ((blist (org-buffer-list
  14323. (cond ((equal arg '(4)) 'files)
  14324. ((equal arg '(16)) 'agenda)))))
  14325. (pop-to-buffer-same-window
  14326. (completing-read "Org buffer: "
  14327. (mapcar #'list (mapcar #'buffer-name blist))
  14328. nil t))))
  14329. (defun org-buffer-list (&optional predicate exclude-tmp)
  14330. "Return a list of Org buffers.
  14331. PREDICATE can be `export', `files' or `agenda'.
  14332. export restrict the list to Export buffers.
  14333. files restrict the list to buffers visiting Org files.
  14334. agenda restrict the list to buffers visiting agenda files.
  14335. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  14336. (let* ((bfn nil)
  14337. (agenda-files (and (eq predicate 'agenda)
  14338. (mapcar 'file-truename (org-agenda-files t))))
  14339. (filter
  14340. (cond
  14341. ((eq predicate 'files)
  14342. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  14343. ((eq predicate 'export)
  14344. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  14345. ((eq predicate 'agenda)
  14346. (lambda (b)
  14347. (with-current-buffer b
  14348. (and (derived-mode-p 'org-mode)
  14349. (setq bfn (buffer-file-name b))
  14350. (member (file-truename bfn) agenda-files)))))
  14351. (t (lambda (b) (with-current-buffer b
  14352. (or (derived-mode-p 'org-mode)
  14353. (string-match "\\*Org .*Export"
  14354. (buffer-name b)))))))))
  14355. (delq nil
  14356. (mapcar
  14357. (lambda(b)
  14358. (if (and (funcall filter b)
  14359. (or (not exclude-tmp)
  14360. (not (string-match "tmp" (buffer-name b)))))
  14361. b
  14362. nil))
  14363. (buffer-list)))))
  14364. (defun org-agenda-files (&optional unrestricted archives)
  14365. "Get the list of agenda files.
  14366. Optional UNRESTRICTED means return the full list even if a restriction
  14367. is currently in place.
  14368. When ARCHIVES is t, include all archive files that are really being
  14369. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  14370. `org-agenda-archives-mode' is t."
  14371. (let ((files
  14372. (cond
  14373. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  14374. ((stringp org-agenda-files) (org-read-agenda-file-list))
  14375. ((listp org-agenda-files) org-agenda-files)
  14376. (t (error "Invalid value of `org-agenda-files'")))))
  14377. (setq files (apply 'append
  14378. (mapcar (lambda (f)
  14379. (if (file-directory-p f)
  14380. (directory-files
  14381. f t org-agenda-file-regexp)
  14382. (list f)))
  14383. files)))
  14384. (when org-agenda-skip-unavailable-files
  14385. (setq files (delq nil
  14386. (mapcar (function
  14387. (lambda (file)
  14388. (and (file-readable-p file) file)))
  14389. files))))
  14390. (when (or (eq archives t)
  14391. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  14392. (setq files (org-add-archive-files files)))
  14393. files))
  14394. (defun org-agenda-file-p (&optional file)
  14395. "Return non-nil, if FILE is an agenda file.
  14396. If FILE is omitted, use the file associated with the current
  14397. buffer."
  14398. (let ((fname (or file (buffer-file-name))))
  14399. (and fname
  14400. (member (file-truename fname)
  14401. (mapcar #'file-truename (org-agenda-files t))))))
  14402. (defun org-edit-agenda-file-list ()
  14403. "Edit the list of agenda files.
  14404. Depending on setup, this either uses customize to edit the variable
  14405. `org-agenda-files', or it visits the file that is holding the list. In the
  14406. latter case, the buffer is set up in a way that saving it automatically kills
  14407. the buffer and restores the previous window configuration."
  14408. (interactive)
  14409. (if (stringp org-agenda-files)
  14410. (let ((cw (current-window-configuration)))
  14411. (find-file org-agenda-files)
  14412. (setq-local org-window-configuration cw)
  14413. (add-hook 'after-save-hook
  14414. (lambda ()
  14415. (set-window-configuration
  14416. (prog1 org-window-configuration
  14417. (kill-buffer (current-buffer))))
  14418. (org-install-agenda-files-menu)
  14419. (message "New agenda file list installed"))
  14420. nil 'local)
  14421. (message "%s" (substitute-command-keys
  14422. "Edit list and finish with \\[save-buffer]")))
  14423. (customize-variable 'org-agenda-files)))
  14424. (defun org-store-new-agenda-file-list (list)
  14425. "Set new value for the agenda file list and save it correctly."
  14426. (if (stringp org-agenda-files)
  14427. (let ((fe (org-read-agenda-file-list t)) b u)
  14428. (while (setq b (find-buffer-visiting org-agenda-files))
  14429. (kill-buffer b))
  14430. (with-temp-file org-agenda-files
  14431. (insert
  14432. (mapconcat
  14433. (lambda (f) ;; Keep un-expanded entries.
  14434. (if (setq u (assoc f fe))
  14435. (cdr u)
  14436. f))
  14437. list "\n")
  14438. "\n")))
  14439. (let ((org-mode-hook nil) (org-inhibit-startup t)
  14440. (org-insert-mode-line-in-empty-file nil))
  14441. (setq org-agenda-files list)
  14442. (customize-save-variable 'org-agenda-files org-agenda-files))))
  14443. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  14444. "Read the list of agenda files from a file.
  14445. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  14446. filenames, used by `org-store-new-agenda-file-list' to write back
  14447. un-expanded file names."
  14448. (when (file-directory-p org-agenda-files)
  14449. (error "`org-agenda-files' cannot be a single directory"))
  14450. (when (stringp org-agenda-files)
  14451. (with-temp-buffer
  14452. (insert-file-contents org-agenda-files)
  14453. (mapcar
  14454. (lambda (f)
  14455. (let ((e (expand-file-name (substitute-in-file-name f)
  14456. org-directory)))
  14457. (if pair-with-expansion
  14458. (cons e f)
  14459. e)))
  14460. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  14461. ;;;###autoload
  14462. (defun org-cycle-agenda-files ()
  14463. "Cycle through the files in `org-agenda-files'.
  14464. If the current buffer visits an agenda file, find the next one in the list.
  14465. If the current buffer does not, find the first agenda file."
  14466. (interactive)
  14467. (let* ((fs (or (org-agenda-files t)
  14468. (user-error "No agenda files")))
  14469. (files (copy-sequence fs))
  14470. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  14471. file)
  14472. (when tcf
  14473. (while (and (setq file (pop files))
  14474. (not (equal (file-truename file) tcf)))))
  14475. (find-file (car (or files fs)))
  14476. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  14477. (defun org-agenda-file-to-front (&optional to-end)
  14478. "Move/add the current file to the top of the agenda file list.
  14479. If the file is not present in the list, it is added to the front. If it is
  14480. present, it is moved there. With optional argument TO-END, add/move to the
  14481. end of the list."
  14482. (interactive "P")
  14483. (let ((org-agenda-skip-unavailable-files nil)
  14484. (file-alist (mapcar (lambda (x)
  14485. (cons (file-truename x) x))
  14486. (org-agenda-files t)))
  14487. (ctf (file-truename
  14488. (or buffer-file-name
  14489. (user-error "Please save the current buffer to a file"))))
  14490. x had)
  14491. (setq x (assoc ctf file-alist) had x)
  14492. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  14493. (if to-end
  14494. (setq file-alist (append (delq x file-alist) (list x)))
  14495. (setq file-alist (cons x (delq x file-alist))))
  14496. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  14497. (org-install-agenda-files-menu)
  14498. (message "File %s to %s of agenda file list"
  14499. (if had "moved" "added") (if to-end "end" "front"))))
  14500. (defun org-remove-file (&optional file)
  14501. "Remove current file from the list of files in variable `org-agenda-files'.
  14502. These are the files which are being checked for agenda entries.
  14503. Optional argument FILE means use this file instead of the current."
  14504. (interactive)
  14505. (let* ((org-agenda-skip-unavailable-files nil)
  14506. (file (or file buffer-file-name
  14507. (user-error "Current buffer does not visit a file")))
  14508. (true-file (file-truename file))
  14509. (afile (abbreviate-file-name file))
  14510. (files (delq nil (mapcar
  14511. (lambda (x)
  14512. (unless (equal true-file
  14513. (file-truename x))
  14514. x))
  14515. (org-agenda-files t)))))
  14516. (if (not (= (length files) (length (org-agenda-files t))))
  14517. (progn
  14518. (org-store-new-agenda-file-list files)
  14519. (org-install-agenda-files-menu)
  14520. (message "Removed from Org Agenda list: %s" afile))
  14521. (message "File was not in list: %s (not removed)" afile))))
  14522. (defun org-file-menu-entry (file)
  14523. (vector file (list 'find-file file) t))
  14524. (defun org-check-agenda-file (file)
  14525. "Make sure FILE exists. If not, ask user what to do."
  14526. (unless (file-exists-p file)
  14527. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  14528. (abbreviate-file-name file))
  14529. (let ((r (downcase (read-char-exclusive))))
  14530. (cond
  14531. ((equal r ?r)
  14532. (org-remove-file file)
  14533. (throw 'nextfile t))
  14534. (t (user-error "Abort"))))))
  14535. (defun org-get-agenda-file-buffer (file)
  14536. "Get an agenda buffer visiting FILE.
  14537. If the buffer needs to be created, add it to the list of buffers
  14538. which might be released later."
  14539. (let ((buf (org-find-base-buffer-visiting file)))
  14540. (if buf
  14541. buf ; just return it
  14542. ;; Make a new buffer and remember it
  14543. (setq buf (find-file-noselect file))
  14544. (when buf (push buf org-agenda-new-buffers))
  14545. buf)))
  14546. (defun org-release-buffers (blist)
  14547. "Release all buffers in list, asking the user for confirmation when needed.
  14548. When a buffer is unmodified, it is just killed. When modified, it is saved
  14549. \(if the user agrees) and then killed."
  14550. (let (file)
  14551. (dolist (buf blist)
  14552. (setq file (buffer-file-name buf))
  14553. (when (and (buffer-modified-p buf)
  14554. file
  14555. (y-or-n-p (format "Save file %s? " file)))
  14556. (with-current-buffer buf (save-buffer)))
  14557. (kill-buffer buf))))
  14558. (defun org-agenda-prepare-buffers (files)
  14559. "Create buffers for all agenda files, protect archived trees and comments."
  14560. (interactive)
  14561. (let ((pa '(:org-archived t))
  14562. (pc '(:org-comment t))
  14563. (pall '(:org-archived t :org-comment t))
  14564. (inhibit-read-only t)
  14565. (org-inhibit-startup org-agenda-inhibit-startup)
  14566. (rea (org-make-tag-string (list org-archive-tag)))
  14567. re pos)
  14568. (setq org-tag-alist-for-agenda nil
  14569. org-tag-groups-alist-for-agenda nil)
  14570. (save-excursion
  14571. (save-restriction
  14572. (dolist (file files)
  14573. (catch 'nextfile
  14574. (if (bufferp file)
  14575. (set-buffer file)
  14576. (org-check-agenda-file file)
  14577. (set-buffer (org-get-agenda-file-buffer file)))
  14578. (widen)
  14579. (org-set-regexps-and-options 'tags-only)
  14580. (setq pos (point))
  14581. (or (memq 'category org-agenda-ignore-properties)
  14582. (org-refresh-category-properties))
  14583. (or (memq 'stats org-agenda-ignore-properties)
  14584. (org-refresh-stats-properties))
  14585. (or (memq 'effort org-agenda-ignore-properties)
  14586. (org-refresh-effort-properties))
  14587. (or (memq 'appt org-agenda-ignore-properties)
  14588. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14589. (setq org-todo-keywords-for-agenda
  14590. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14591. (setq org-done-keywords-for-agenda
  14592. (append org-done-keywords-for-agenda org-done-keywords))
  14593. (setq org-todo-keyword-alist-for-agenda
  14594. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14595. (setq org-tag-alist-for-agenda
  14596. (org--tag-add-to-alist
  14597. org-tag-alist-for-agenda
  14598. org-current-tag-alist))
  14599. ;; Merge current file's tag groups into global
  14600. ;; `org-tag-groups-alist-for-agenda'.
  14601. (when org-group-tags
  14602. (dolist (alist org-tag-groups-alist)
  14603. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14604. (if old
  14605. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14606. (push alist org-tag-groups-alist-for-agenda)))))
  14607. (with-silent-modifications
  14608. (save-excursion
  14609. (remove-text-properties (point-min) (point-max) pall)
  14610. (when org-agenda-skip-archived-trees
  14611. (goto-char (point-min))
  14612. (while (re-search-forward rea nil t)
  14613. (when (org-at-heading-p t)
  14614. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  14615. (goto-char (point-min))
  14616. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  14617. (while (re-search-forward re nil t)
  14618. (when (save-match-data (org-in-commented-heading-p t))
  14619. (add-text-properties
  14620. (match-beginning 0) (org-end-of-subtree t) pc)))))
  14621. (goto-char pos)))))
  14622. (setq org-todo-keywords-for-agenda
  14623. (org-uniquify org-todo-keywords-for-agenda))
  14624. (setq org-todo-keyword-alist-for-agenda
  14625. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14626. ;;;; CDLaTeX minor mode
  14627. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14628. "Keymap for the minor `org-cdlatex-mode'.")
  14629. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14630. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14631. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14632. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14633. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14634. (defvar org-cdlatex-texmathp-advice-is-done nil
  14635. "Flag remembering if we have applied the advice to texmathp already.")
  14636. (define-minor-mode org-cdlatex-mode
  14637. "Toggle the minor `org-cdlatex-mode'.
  14638. This mode supports entering LaTeX environment and math in LaTeX fragments
  14639. in Org mode.
  14640. \\{org-cdlatex-mode-map}"
  14641. nil " OCDL" nil
  14642. (when org-cdlatex-mode
  14643. (require 'cdlatex)
  14644. (run-hooks 'cdlatex-mode-hook)
  14645. (cdlatex-compute-tables))
  14646. (unless org-cdlatex-texmathp-advice-is-done
  14647. (setq org-cdlatex-texmathp-advice-is-done t)
  14648. (defadvice texmathp (around org-math-always-on activate)
  14649. "Always return t in Org buffers.
  14650. This is because we want to insert math symbols without dollars even outside
  14651. the LaTeX math segments. If Org mode thinks that point is actually inside
  14652. an embedded LaTeX fragment, let `texmathp' do its job.
  14653. `\\[org-cdlatex-mode-map]'"
  14654. (interactive)
  14655. (let (p)
  14656. (cond
  14657. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14658. ((eq this-command 'cdlatex-math-symbol)
  14659. (setq ad-return-value t
  14660. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14661. (t
  14662. (let ((p (org-inside-LaTeX-fragment-p)))
  14663. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14664. (setq ad-return-value t
  14665. texmathp-why '("Org mode embedded math" . 0))
  14666. (when p ad-do-it)))))))))
  14667. (defun turn-on-org-cdlatex ()
  14668. "Unconditionally turn on `org-cdlatex-mode'."
  14669. (org-cdlatex-mode 1))
  14670. (defun org-try-cdlatex-tab ()
  14671. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14672. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14673. - inside a LaTeX fragment, or
  14674. - after the first word in a line, where an abbreviation expansion could
  14675. insert a LaTeX environment."
  14676. (when org-cdlatex-mode
  14677. (cond
  14678. ;; Before any word on the line: No expansion possible.
  14679. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14680. ;; Just after first word on the line: Expand it. Make sure it
  14681. ;; cannot happen on headlines, though.
  14682. ((save-excursion
  14683. (skip-chars-backward "a-zA-Z0-9*")
  14684. (skip-chars-backward " \t")
  14685. (and (bolp) (not (org-at-heading-p))))
  14686. (cdlatex-tab) t)
  14687. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14688. (defun org-cdlatex-underscore-caret (&optional _arg)
  14689. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14690. Revert to the normal definition outside of these fragments."
  14691. (interactive "P")
  14692. (if (org-inside-LaTeX-fragment-p)
  14693. (call-interactively 'cdlatex-sub-superscript)
  14694. (let (org-cdlatex-mode)
  14695. (call-interactively (key-binding (vector last-input-event))))))
  14696. (defun org-cdlatex-math-modify (&optional _arg)
  14697. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14698. Revert to the normal definition outside of these fragments."
  14699. (interactive "P")
  14700. (if (org-inside-LaTeX-fragment-p)
  14701. (call-interactively 'cdlatex-math-modify)
  14702. (let (org-cdlatex-mode)
  14703. (call-interactively (key-binding (vector last-input-event))))))
  14704. (defun org-cdlatex-environment-indent (&optional environment item)
  14705. "Execute `cdlatex-environment' and indent the inserted environment.
  14706. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14707. The inserted environment is indented to current indentation
  14708. unless point is at the beginning of the line, in which the
  14709. environment remains unintended."
  14710. (interactive)
  14711. ;; cdlatex-environment always return nil. Therefore, capture output
  14712. ;; first and determine if an environment was selected.
  14713. (let* ((beg (point-marker))
  14714. (end (copy-marker (point) t))
  14715. (inserted (progn
  14716. (ignore-errors (cdlatex-environment environment item))
  14717. (< beg end)))
  14718. ;; Figure out how many lines to move forward after the
  14719. ;; environment has been inserted.
  14720. (lines (when inserted
  14721. (save-excursion
  14722. (- (cl-loop while (< beg (point))
  14723. with x = 0
  14724. do (forward-line -1)
  14725. (cl-incf x)
  14726. finally return x)
  14727. (if (progn (goto-char beg)
  14728. (and (progn (skip-chars-forward " \t") (eolp))
  14729. (progn (skip-chars-backward " \t") (bolp))))
  14730. 1 0)))))
  14731. (env (org-trim (delete-and-extract-region beg end))))
  14732. (when inserted
  14733. ;; Get indentation of next line unless at column 0.
  14734. (let ((ind (if (bolp) 0
  14735. (save-excursion
  14736. (org-return-indent)
  14737. (prog1 (current-indentation)
  14738. (when (progn (skip-chars-forward " \t") (eolp))
  14739. (delete-region beg (point)))))))
  14740. (bol (progn (skip-chars-backward " \t") (bolp))))
  14741. ;; Insert a newline before environment unless at column zero
  14742. ;; to "escape" the current line. Insert a newline if
  14743. ;; something is one the same line as \end{ENVIRONMENT}.
  14744. (insert
  14745. (concat (unless bol "\n") env
  14746. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14747. (unless (zerop ind)
  14748. (save-excursion
  14749. (goto-char beg)
  14750. (while (< (point) end)
  14751. (unless (eolp) (indent-line-to ind))
  14752. (forward-line))))
  14753. (goto-char beg)
  14754. (forward-line lines)
  14755. (indent-line-to ind)))
  14756. (set-marker beg nil)
  14757. (set-marker end nil)))
  14758. ;;;; LaTeX fragments
  14759. (defun org-inside-LaTeX-fragment-p ()
  14760. "Test if point is inside a LaTeX fragment.
  14761. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14762. sequence appearing also before point.
  14763. Even though the matchers for math are configurable, this function assumes
  14764. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14765. delimiters are skipped when they have been removed by customization.
  14766. The return value is nil, or a cons cell with the delimiter and the
  14767. position of this delimiter.
  14768. This function does a reasonably good job, but can locally be fooled by
  14769. for example currency specifications. For example it will assume being in
  14770. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14771. fragments that are properly closed, but during editing, we have to live
  14772. with the uncertainty caused by missing closing delimiters. This function
  14773. looks only before point, not after."
  14774. (catch 'exit
  14775. (let ((pos (point))
  14776. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14777. (lim (save-excursion (org-backward-paragraph) (point)))
  14778. dd-on str (start 0) m re)
  14779. (goto-char pos)
  14780. (when dodollar
  14781. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14782. re (nth 1 (assoc "$" org-latex-regexps)))
  14783. (while (string-match re str start)
  14784. (cond
  14785. ((= (match-end 0) (length str))
  14786. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14787. ((= (match-end 0) (- (length str) 5))
  14788. (throw 'exit nil))
  14789. (t (setq start (match-end 0))))))
  14790. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14791. (goto-char pos)
  14792. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14793. (and (match-beginning 2) (throw 'exit nil))
  14794. ;; count $$
  14795. (while (re-search-backward "\\$\\$" lim t)
  14796. (setq dd-on (not dd-on)))
  14797. (goto-char pos)
  14798. (when dd-on (cons "$$" m))))))
  14799. (defun org-inside-latex-macro-p ()
  14800. "Is point inside a LaTeX macro or its arguments?"
  14801. (save-match-data
  14802. (org-in-regexp
  14803. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14804. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14805. "Build an overlay between BEG and END using IMAGE file.
  14806. Argument IMAGETYPE is the extension of the displayed image,
  14807. as a string. It defaults to \"png\"."
  14808. (let ((ov (make-overlay beg end))
  14809. (imagetype (or (intern imagetype) 'png)))
  14810. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14811. (overlay-put ov 'evaporate t)
  14812. (overlay-put ov
  14813. 'modification-hooks
  14814. (list (lambda (o _flag _beg _end &optional _l)
  14815. (delete-overlay o))))
  14816. (overlay-put ov
  14817. 'display
  14818. (list 'image :type imagetype :file image :ascent 'center))))
  14819. (defun org-clear-latex-preview (&optional beg end)
  14820. "Remove all overlays with LaTeX fragment images in current buffer.
  14821. When optional arguments BEG and END are non-nil, remove all
  14822. overlays between them instead. Return a non-nil value when some
  14823. overlays were removed, nil otherwise."
  14824. (let ((overlays
  14825. (cl-remove-if-not
  14826. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14827. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14828. (mapc #'delete-overlay overlays)
  14829. overlays))
  14830. (defun org--latex-preview-region (beg end)
  14831. "Preview LaTeX fragments between BEG and END.
  14832. BEG and END are buffer positions."
  14833. (let ((file (buffer-file-name (buffer-base-buffer))))
  14834. (save-excursion
  14835. (org-format-latex
  14836. (concat org-preview-latex-image-directory "org-ltximg")
  14837. beg end
  14838. ;; Emacs cannot overlay images from remote hosts. Create it in
  14839. ;; `temporary-file-directory' instead.
  14840. (if (or (not file) (file-remote-p file))
  14841. temporary-file-directory
  14842. default-directory)
  14843. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14844. (defun org-latex-preview (&optional arg)
  14845. "Toggle preview of the LaTeX fragment at point.
  14846. If the cursor is on a LaTeX fragment, create the image and
  14847. overlay it over the source code, if there is none. Remove it
  14848. otherwise. If there is no fragment at point, display images for
  14849. all fragments in the current section.
  14850. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14851. for all fragments
  14852. in the current section.
  14853. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14854. argument ARG, display image for all
  14855. fragments in the buffer.
  14856. With a `\\[universal-argument] \\[universal-argument] \
  14857. \\[universal-argument]' prefix argument ARG, clear image for all
  14858. fragments in the buffer."
  14859. (interactive "P")
  14860. (cond
  14861. ((not (display-graphic-p)) nil)
  14862. ;; Clear whole buffer.
  14863. ((equal arg '(64))
  14864. (org-clear-latex-preview (point-min) (point-max))
  14865. (message "LaTeX previews removed from buffer"))
  14866. ;; Preview whole buffer.
  14867. ((equal arg '(16))
  14868. (message "Creating LaTeX previews in buffer...")
  14869. (org--latex-preview-region (point-min) (point-max))
  14870. (message "Creating LaTeX previews in buffer... done."))
  14871. ;; Clear current section.
  14872. ((equal arg '(4))
  14873. (org-clear-latex-preview
  14874. (if (org-before-first-heading-p) (point-min)
  14875. (save-excursion
  14876. (org-with-limited-levels (org-back-to-heading t) (point))))
  14877. (org-with-limited-levels (org-entry-end-position))))
  14878. ;; Toggle preview on LaTeX code at point.
  14879. ((let ((datum (org-element-context)))
  14880. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14881. (let ((beg (org-element-property :begin datum))
  14882. (end (org-element-property :end datum)))
  14883. (if (org-clear-latex-preview beg end)
  14884. (message "LaTeX preview removed")
  14885. (message "Creating LaTeX preview...")
  14886. (org--latex-preview-region beg end)
  14887. (message "Creating LaTeX preview... done."))
  14888. t))))
  14889. ;; Preview current section.
  14890. (t
  14891. (let ((beg (if (org-before-first-heading-p) (point-min)
  14892. (save-excursion
  14893. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14894. (end (org-with-limited-levels (org-entry-end-position))))
  14895. (message "Creating LaTeX previews in section...")
  14896. (org--latex-preview-region beg end)
  14897. (message "Creating LaTeX previews in section... done.")))))
  14898. (defun org-format-latex
  14899. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14900. "Replace LaTeX fragments with links to an image.
  14901. The function takes care of creating the replacement image.
  14902. Only consider fragments between BEG and END when those are
  14903. provided.
  14904. When optional argument OVERLAYS is non-nil, display the image on
  14905. top of the fragment instead of replacing it.
  14906. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14907. Some of the options can be changed using the variable
  14908. `org-format-latex-options', which see."
  14909. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14910. (unless (eq processing-type 'verbatim)
  14911. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14912. (cnt 0)
  14913. checkdir-flag)
  14914. (goto-char (or beg (point-min)))
  14915. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14916. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14917. (overlay-recenter (or end (point-max))))
  14918. (while (re-search-forward math-regexp end t)
  14919. (unless (and overlays
  14920. (eq (get-char-property (point) 'org-overlay-type)
  14921. 'org-latex-overlay))
  14922. (let* ((context (org-element-context))
  14923. (type (org-element-type context)))
  14924. (when (memq type '(latex-environment latex-fragment))
  14925. (let ((block-type (eq type 'latex-environment))
  14926. (value (org-element-property :value context))
  14927. (beg (org-element-property :begin context))
  14928. (end (save-excursion
  14929. (goto-char (org-element-property :end context))
  14930. (skip-chars-backward " \r\t\n")
  14931. (point))))
  14932. (cond
  14933. ((eq processing-type 'mathjax)
  14934. ;; Prepare for MathJax processing.
  14935. (if (not (string-match "\\`\\$\\$?" value))
  14936. (goto-char end)
  14937. (delete-region beg end)
  14938. (if (string= (match-string 0 value) "$$")
  14939. (insert "\\[" (substring value 2 -2) "\\]")
  14940. (insert "\\(" (substring value 1 -1) "\\)"))))
  14941. ((assq processing-type org-preview-latex-process-alist)
  14942. ;; Process to an image.
  14943. (cl-incf cnt)
  14944. (goto-char beg)
  14945. (let* ((processing-info
  14946. (cdr (assq processing-type org-preview-latex-process-alist)))
  14947. (face (face-at-point))
  14948. ;; Get the colors from the face at point.
  14949. (fg
  14950. (let ((color (plist-get org-format-latex-options
  14951. :foreground)))
  14952. (if (and forbuffer (eq color 'auto))
  14953. (face-attribute face :foreground nil 'default)
  14954. color)))
  14955. (bg
  14956. (let ((color (plist-get org-format-latex-options
  14957. :background)))
  14958. (if (and forbuffer (eq color 'auto))
  14959. (face-attribute face :background nil 'default)
  14960. color)))
  14961. (hash (sha1 (prin1-to-string
  14962. (list org-format-latex-header
  14963. org-latex-default-packages-alist
  14964. org-latex-packages-alist
  14965. org-format-latex-options
  14966. forbuffer value fg bg))))
  14967. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14968. (absprefix (expand-file-name prefix dir))
  14969. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14970. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14971. (sep (and block-type "\n\n"))
  14972. (link (concat sep "[[file:" linkfile "]]" sep))
  14973. (options
  14974. (org-combine-plists
  14975. org-format-latex-options
  14976. `(:foreground ,fg :background ,bg))))
  14977. (when msg (message msg cnt))
  14978. (unless checkdir-flag ; Ensure the directory exists.
  14979. (setq checkdir-flag t)
  14980. (let ((todir (file-name-directory absprefix)))
  14981. (unless (file-directory-p todir)
  14982. (make-directory todir t))))
  14983. (unless (file-exists-p movefile)
  14984. (org-create-formula-image
  14985. value movefile options forbuffer processing-type))
  14986. (if overlays
  14987. (progn
  14988. (dolist (o (overlays-in beg end))
  14989. (when (eq (overlay-get o 'org-overlay-type)
  14990. 'org-latex-overlay)
  14991. (delete-overlay o)))
  14992. (org--make-preview-overlay beg end movefile imagetype)
  14993. (goto-char end))
  14994. (delete-region beg end)
  14995. (insert
  14996. (org-add-props link
  14997. (list 'org-latex-src
  14998. (replace-regexp-in-string "\"" "" value)
  14999. 'org-latex-src-embed-type
  15000. (if block-type 'paragraph 'character)))))))
  15001. ((eq processing-type 'mathml)
  15002. ;; Process to MathML.
  15003. (unless (org-format-latex-mathml-available-p)
  15004. (user-error "LaTeX to MathML converter not configured"))
  15005. (cl-incf cnt)
  15006. (when msg (message msg cnt))
  15007. (goto-char beg)
  15008. (delete-region beg end)
  15009. (insert (org-format-latex-as-mathml
  15010. value block-type prefix dir)))
  15011. (t
  15012. (error "Unknown conversion process %s for LaTeX fragments"
  15013. processing-type)))))))))))
  15014. (defun org-create-math-formula (latex-frag &optional mathml-file)
  15015. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  15016. Use `org-latex-to-mathml-convert-command'. If the conversion is
  15017. successful, return the portion between \"<math...> </math>\"
  15018. elements otherwise return nil. When MATHML-FILE is specified,
  15019. write the results in to that file. When invoked as an
  15020. interactive command, prompt for LATEX-FRAG, with initial value
  15021. set to the current active region and echo the results for user
  15022. inspection."
  15023. (interactive (list (let ((frag (when (org-region-active-p)
  15024. (buffer-substring-no-properties
  15025. (region-beginning) (region-end)))))
  15026. (read-string "LaTeX Fragment: " frag nil frag))))
  15027. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  15028. (let* ((tmp-in-file
  15029. (let ((file (file-relative-name
  15030. (make-temp-name (expand-file-name "ltxmathml-in")))))
  15031. (write-region latex-frag nil file)
  15032. file))
  15033. (tmp-out-file (file-relative-name
  15034. (make-temp-name (expand-file-name "ltxmathml-out"))))
  15035. (cmd (format-spec
  15036. org-latex-to-mathml-convert-command
  15037. `((?j . ,(and org-latex-to-mathml-jar-file
  15038. (shell-quote-argument
  15039. (expand-file-name
  15040. org-latex-to-mathml-jar-file))))
  15041. (?I . ,(shell-quote-argument tmp-in-file))
  15042. (?i . ,latex-frag)
  15043. (?o . ,(shell-quote-argument tmp-out-file)))))
  15044. mathml shell-command-output)
  15045. (when (called-interactively-p 'any)
  15046. (unless (org-format-latex-mathml-available-p)
  15047. (user-error "LaTeX to MathML converter not configured")))
  15048. (message "Running %s" cmd)
  15049. (setq shell-command-output (shell-command-to-string cmd))
  15050. (setq mathml
  15051. (when (file-readable-p tmp-out-file)
  15052. (with-current-buffer (find-file-noselect tmp-out-file t)
  15053. (goto-char (point-min))
  15054. (when (re-search-forward
  15055. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  15056. (regexp-quote
  15057. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  15058. nil t)
  15059. (prog1 (match-string 0) (kill-buffer))))))
  15060. (cond
  15061. (mathml
  15062. (setq mathml
  15063. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  15064. (when mathml-file
  15065. (write-region mathml nil mathml-file))
  15066. (when (called-interactively-p 'any)
  15067. (message mathml)))
  15068. ((message "LaTeX to MathML conversion failed")
  15069. (message shell-command-output)))
  15070. (delete-file tmp-in-file)
  15071. (when (file-exists-p tmp-out-file)
  15072. (delete-file tmp-out-file))
  15073. mathml))
  15074. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  15075. prefix &optional dir)
  15076. "Use `org-create-math-formula' but check local cache first."
  15077. (let* ((absprefix (expand-file-name prefix dir))
  15078. (print-length nil) (print-level nil)
  15079. (formula-id (concat
  15080. "formula-"
  15081. (sha1
  15082. (prin1-to-string
  15083. (list latex-frag
  15084. org-latex-to-mathml-convert-command)))))
  15085. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  15086. (formula-cache-dir (file-name-directory formula-cache)))
  15087. (unless (file-directory-p formula-cache-dir)
  15088. (make-directory formula-cache-dir t))
  15089. (unless (file-exists-p formula-cache)
  15090. (org-create-math-formula latex-frag formula-cache))
  15091. (if (file-exists-p formula-cache)
  15092. ;; Successful conversion. Return the link to MathML file.
  15093. (org-add-props
  15094. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  15095. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  15096. 'org-latex-src-embed-type (if latex-frag-type
  15097. 'paragraph 'character)))
  15098. ;; Failed conversion. Return the LaTeX fragment verbatim
  15099. latex-frag)))
  15100. (defun org--get-display-dpi ()
  15101. "Get the DPI of the display.
  15102. The function assumes that the display has the same pixel width in
  15103. the horizontal and vertical directions."
  15104. (if (display-graphic-p)
  15105. (round (/ (display-pixel-height)
  15106. (/ (display-mm-height) 25.4)))
  15107. (error "Attempt to calculate the dpi of a non-graphic display")))
  15108. (defun org-create-formula-image
  15109. (string tofile options buffer &optional processing-type)
  15110. "Create an image from LaTeX source using external processes.
  15111. The LaTeX STRING is saved to a temporary LaTeX file, then
  15112. converted to an image file by process PROCESSING-TYPE defined in
  15113. `org-preview-latex-process-alist'. A nil value defaults to
  15114. `org-preview-latex-default-process'.
  15115. The generated image file is eventually moved to TOFILE.
  15116. The OPTIONS argument controls the size, foreground color and
  15117. background color of the generated image.
  15118. When BUFFER non-nil, this function is used for LaTeX previewing.
  15119. Otherwise, it is used to deal with LaTeX snippets showed in
  15120. a HTML file."
  15121. (let* ((processing-type (or processing-type
  15122. org-preview-latex-default-process))
  15123. (processing-info
  15124. (cdr (assq processing-type org-preview-latex-process-alist)))
  15125. (programs (plist-get processing-info :programs))
  15126. (error-message (or (plist-get processing-info :message) ""))
  15127. (image-input-type (plist-get processing-info :image-input-type))
  15128. (image-output-type (plist-get processing-info :image-output-type))
  15129. (post-clean (or (plist-get processing-info :post-clean)
  15130. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  15131. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  15132. (latex-header
  15133. (or (plist-get processing-info :latex-header)
  15134. (org-latex-make-preamble
  15135. (org-export-get-environment (org-export-get-backend 'latex))
  15136. org-format-latex-header
  15137. 'snippet)))
  15138. (latex-compiler (plist-get processing-info :latex-compiler))
  15139. (image-converter (plist-get processing-info :image-converter))
  15140. (tmpdir temporary-file-directory)
  15141. (texfilebase (make-temp-name
  15142. (expand-file-name "orgtex" tmpdir)))
  15143. (texfile (concat texfilebase ".tex"))
  15144. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  15145. '(1.0 . 1.0)))
  15146. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  15147. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  15148. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  15149. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  15150. "Black"))
  15151. (bg (or (plist-get options (if buffer :background :html-background))
  15152. "Transparent"))
  15153. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  15154. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  15155. (dolist (program programs)
  15156. (org-check-external-command program error-message))
  15157. (if (eq fg 'default)
  15158. (setq fg (org-latex-color :foreground))
  15159. (setq fg (org-latex-color-format fg)))
  15160. (if (eq bg 'default)
  15161. (setq bg (org-latex-color :background))
  15162. (setq bg (org-latex-color-format
  15163. (if (string= bg "Transparent") "white" bg))))
  15164. ;; Remove TeX \par at end of snippet to avoid trailing space.
  15165. (if (string-suffix-p string "\n")
  15166. (aset string (1- (length string)) ?%)
  15167. (setq string (concat string "%")))
  15168. (with-temp-file texfile
  15169. (insert latex-header)
  15170. (insert "\n\\begin{document}\n"
  15171. "\\definecolor{fg}{rgb}{" fg "}%\n"
  15172. "\\definecolor{bg}{rgb}{" bg "}%\n"
  15173. "\n\\pagecolor{bg}%\n"
  15174. "\n{\\color{fg}\n"
  15175. string
  15176. "\n}\n"
  15177. "\n\\end{document}\n"))
  15178. (let* ((err-msg (format "Please adjust `%s' part of \
  15179. `org-preview-latex-process-alist'."
  15180. processing-type))
  15181. (image-input-file
  15182. (org-compile-file
  15183. texfile latex-compiler image-input-type err-msg log-buf))
  15184. (image-output-file
  15185. (org-compile-file
  15186. image-input-file image-converter image-output-type err-msg log-buf
  15187. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  15188. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  15189. (copy-file image-output-file tofile 'replace)
  15190. (dolist (e post-clean)
  15191. (when (file-exists-p (concat texfilebase e))
  15192. (delete-file (concat texfilebase e))))
  15193. image-output-file)))
  15194. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  15195. "Fill a LaTeX header template TPL.
  15196. In the template, the following place holders will be recognized:
  15197. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  15198. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  15199. [PACKAGES] \\usepackage statements for PKG
  15200. [NO-PACKAGES] do not include PKG
  15201. [EXTRA] the string EXTRA
  15202. [NO-EXTRA] do not include EXTRA
  15203. For backward compatibility, if both the positive and the negative place
  15204. holder is missing, the positive one (without the \"NO-\") will be
  15205. assumed to be present at the end of the template.
  15206. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  15207. EXTRA is a string.
  15208. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  15209. (let (rpl (end ""))
  15210. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  15211. (setq rpl (if (or (match-end 1) (not def-pkg))
  15212. "" (org-latex-packages-to-string def-pkg snippets-p t))
  15213. tpl (replace-match rpl t t tpl))
  15214. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  15215. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  15216. (setq rpl (if (or (match-end 1) (not pkg))
  15217. "" (org-latex-packages-to-string pkg snippets-p t))
  15218. tpl (replace-match rpl t t tpl))
  15219. (when pkg (setq end
  15220. (concat end "\n"
  15221. (org-latex-packages-to-string pkg snippets-p)))))
  15222. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  15223. (setq rpl (if (or (match-end 1) (not extra))
  15224. "" (concat extra "\n"))
  15225. tpl (replace-match rpl t t tpl))
  15226. (when (and extra (string-match "\\S-" extra))
  15227. (setq end (concat end "\n" extra))))
  15228. (if (string-match "\\S-" end)
  15229. (concat tpl "\n" end)
  15230. tpl)))
  15231. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  15232. "Turn an alist of packages into a string with the \\usepackage macros."
  15233. (setq pkg (mapconcat (lambda(p)
  15234. (cond
  15235. ((stringp p) p)
  15236. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  15237. (format "%% Package %s omitted" (cadr p)))
  15238. ((equal "" (car p))
  15239. (format "\\usepackage{%s}" (cadr p)))
  15240. (t
  15241. (format "\\usepackage[%s]{%s}"
  15242. (car p) (cadr p)))))
  15243. pkg
  15244. "\n"))
  15245. (if newline (concat pkg "\n") pkg))
  15246. (defun org-dvipng-color (attr)
  15247. "Return a RGB color specification for dvipng."
  15248. (org-dvipng-color-format (face-attribute 'default attr nil)))
  15249. (defun org-dvipng-color-format (color-name)
  15250. "Convert COLOR-NAME to a RGB color value for dvipng."
  15251. (apply #'format "rgb %s %s %s"
  15252. (mapcar 'org-normalize-color
  15253. (color-values color-name))))
  15254. (defun org-latex-color (attr)
  15255. "Return a RGB color for the LaTeX color package."
  15256. (org-latex-color-format (face-attribute 'default attr nil)))
  15257. (defun org-latex-color-format (color-name)
  15258. "Convert COLOR-NAME to a RGB color value."
  15259. (apply #'format "%s,%s,%s"
  15260. (mapcar 'org-normalize-color
  15261. (color-values color-name))))
  15262. (defun org-normalize-color (value)
  15263. "Return string to be used as color value for an RGB component."
  15264. (format "%g" (/ value 65535.0)))
  15265. ;; Image display
  15266. (defvar-local org-inline-image-overlays nil)
  15267. (defun org-toggle-inline-images (&optional include-linked)
  15268. "Toggle the display of inline images.
  15269. INCLUDE-LINKED is passed to `org-display-inline-images'."
  15270. (interactive "P")
  15271. (if org-inline-image-overlays
  15272. (progn
  15273. (org-remove-inline-images)
  15274. (when (called-interactively-p 'interactive)
  15275. (message "Inline image display turned off")))
  15276. (org-display-inline-images include-linked)
  15277. (when (called-interactively-p 'interactive)
  15278. (message (if org-inline-image-overlays
  15279. (format "%d images displayed inline"
  15280. (length org-inline-image-overlays))
  15281. "No images to display inline")))))
  15282. (defun org-redisplay-inline-images ()
  15283. "Refresh the display of inline images."
  15284. (interactive)
  15285. (if (not org-inline-image-overlays)
  15286. (org-toggle-inline-images)
  15287. (org-toggle-inline-images)
  15288. (org-toggle-inline-images)))
  15289. ;; For without-x builds.
  15290. (declare-function image-refresh "image" (spec &optional frame))
  15291. (defcustom org-display-remote-inline-images 'skip
  15292. "How to display remote inline images.
  15293. Possible values of this option are:
  15294. skip Don't display remote images.
  15295. download Always download and display remote images.
  15296. cache Display remote images, and open them in separate buffers
  15297. for cacheing. Silently update the image buffer when a file
  15298. change is detected."
  15299. :group 'org-appearance
  15300. :package-version '(Org . "9.4")
  15301. :type '(choice
  15302. (const :tag "Ignore remote images" skip)
  15303. (const :tag "Always display remote images" download)
  15304. (const :tag "Display and silently update remote images" cache))
  15305. :safe #'symbolp)
  15306. (defun org--create-inline-image (file width)
  15307. "Create image located at FILE, or return nil.
  15308. WIDTH is the width of the image. The image may not be created
  15309. according to the value of `org-display-remote-inline-images'."
  15310. (let* ((remote? (file-remote-p file))
  15311. (file-or-data
  15312. (pcase org-display-remote-inline-images
  15313. ((guard (not remote?)) file)
  15314. (`download (with-temp-buffer
  15315. (set-buffer-multibyte nil)
  15316. (insert-file-contents-literally file)
  15317. (buffer-string)))
  15318. (`cache (let ((revert-without-query '(".")))
  15319. (with-current-buffer (find-file-noselect file)
  15320. (buffer-string))))
  15321. (`skip nil)
  15322. (other
  15323. (message "Invalid value of `org-display-remote-inline-images': %S"
  15324. other)
  15325. nil))))
  15326. (when file-or-data
  15327. (create-image file-or-data
  15328. (and (image-type-available-p 'imagemagick)
  15329. width
  15330. 'imagemagick)
  15331. remote?
  15332. :width width))))
  15333. (defun org-display-inline-images (&optional include-linked refresh beg end)
  15334. "Display inline images.
  15335. An inline image is a link which follows either of these
  15336. conventions:
  15337. 1. Its path is a file with an extension matching return value
  15338. from `image-file-name-regexp' and it has no contents.
  15339. 2. Its description consists in a single link of the previous
  15340. type. In this case, that link must be a well-formed plain
  15341. or angle link, i.e., it must have an explicit \"file\" type.
  15342. Equip each image with the key-map `image-map'.
  15343. When optional argument INCLUDE-LINKED is non-nil, also links with
  15344. a text description part will be inlined. This can be nice for
  15345. a quick look at those images, but it does not reflect what
  15346. exported files will look like.
  15347. When optional argument REFRESH is non-nil, refresh existing
  15348. images between BEG and END. This will create new image displays
  15349. only if necessary.
  15350. BEG and END define the considered part. They default to the
  15351. buffer boundaries with possible narrowing."
  15352. (interactive "P")
  15353. (when (display-graphic-p)
  15354. (unless refresh
  15355. (org-remove-inline-images)
  15356. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  15357. (let ((end (or end (point-max))))
  15358. (org-with-point-at (or beg (point-min))
  15359. (let* ((case-fold-search t)
  15360. (file-extension-re (image-file-name-regexp))
  15361. (link-abbrevs (mapcar #'car
  15362. (append org-link-abbrev-alist-local
  15363. org-link-abbrev-alist)))
  15364. ;; Check absolute, relative file names and explicit
  15365. ;; "file:" links. Also check link abbreviations since
  15366. ;; some might expand to "file" links.
  15367. (file-types-re
  15368. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  15369. (if (not link-abbrevs) ""
  15370. (concat "\\|" (regexp-opt link-abbrevs))))))
  15371. (while (re-search-forward file-types-re end t)
  15372. (let* ((link (org-element-lineage
  15373. (save-match-data (org-element-context))
  15374. '(link) t))
  15375. (linktype (org-element-property :type link))
  15376. (inner-start (match-beginning 1))
  15377. (path
  15378. (cond
  15379. ;; No link at point; no inline image.
  15380. ((not link) nil)
  15381. ;; File link without a description. Also handle
  15382. ;; INCLUDE-LINKED here since it should have
  15383. ;; precedence over the next case. I.e., if link
  15384. ;; contains filenames in both the path and the
  15385. ;; description, prioritize the path only when
  15386. ;; INCLUDE-LINKED is non-nil.
  15387. ((or (not (org-element-property :contents-begin link))
  15388. include-linked)
  15389. (and (or (equal "file" linktype)
  15390. (equal "attachment" linktype))
  15391. (org-element-property :path link)))
  15392. ;; Link with a description. Check if description
  15393. ;; is a filename. Even if Org doesn't have syntax
  15394. ;; for those -- clickable image -- constructs, fake
  15395. ;; them, as in `org-export-insert-image-links'.
  15396. ((not inner-start) nil)
  15397. (t
  15398. (org-with-point-at inner-start
  15399. (and (looking-at
  15400. (if (char-equal ?< (char-after inner-start))
  15401. org-link-angle-re
  15402. org-link-plain-re))
  15403. ;; File name must fill the whole
  15404. ;; description.
  15405. (= (org-element-property :contents-end link)
  15406. (match-end 0))
  15407. (match-string 2)))))))
  15408. (when (and path (string-match-p file-extension-re path))
  15409. (let ((file (if (equal "attachment" linktype)
  15410. (progn
  15411. (require 'org-attach)
  15412. (ignore-errors (org-attach-expand path)))
  15413. (expand-file-name path))))
  15414. (when (and file (file-exists-p file))
  15415. (let ((width
  15416. ;; Apply `org-image-actual-width' specifications.
  15417. (cond
  15418. ((eq org-image-actual-width t) nil)
  15419. ((listp org-image-actual-width)
  15420. (or
  15421. ;; First try to find a width among
  15422. ;; attributes associated to the paragraph
  15423. ;; containing link.
  15424. (pcase (org-element-lineage link '(paragraph))
  15425. (`nil nil)
  15426. (p
  15427. (let* ((case-fold-search t)
  15428. (end (org-element-property :post-affiliated p))
  15429. (re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"))
  15430. (when (org-with-point-at
  15431. (org-element-property :begin p)
  15432. (re-search-forward re end t))
  15433. (string-to-number (match-string 1))))))
  15434. ;; Otherwise, fall-back to provided number.
  15435. (car org-image-actual-width)))
  15436. ((numberp org-image-actual-width)
  15437. org-image-actual-width)
  15438. (t nil)))
  15439. (old (get-char-property-and-overlay
  15440. (org-element-property :begin link)
  15441. 'org-image-overlay)))
  15442. (if (and (car-safe old) refresh)
  15443. (image-refresh (overlay-get (cdr old) 'display))
  15444. (let ((image (org--create-inline-image file width)))
  15445. (when image
  15446. (let ((ov (make-overlay
  15447. (org-element-property :begin link)
  15448. (progn
  15449. (goto-char
  15450. (org-element-property :end link))
  15451. (skip-chars-backward " \t")
  15452. (point)))))
  15453. (overlay-put ov 'display image)
  15454. (overlay-put ov 'face 'default)
  15455. (overlay-put ov 'org-image-overlay t)
  15456. (overlay-put
  15457. ov 'modification-hooks
  15458. (list 'org-display-inline-remove-overlay))
  15459. (when (<= 26 emacs-major-version)
  15460. (cl-assert (boundp 'image-map))
  15461. (overlay-put ov 'keymap image-map))
  15462. (push ov org-inline-image-overlays))))))))))))))))
  15463. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  15464. "Remove inline-display overlay if a corresponding region is modified."
  15465. (let ((inhibit-modification-hooks t))
  15466. (when (and ov after)
  15467. (delete ov org-inline-image-overlays)
  15468. (delete-overlay ov))))
  15469. (defun org-remove-inline-images ()
  15470. "Remove inline display of images."
  15471. (interactive)
  15472. (mapc #'delete-overlay org-inline-image-overlays)
  15473. (setq org-inline-image-overlays nil))
  15474. (defvar org-self-insert-command-undo-counter 0)
  15475. (defvar org-speed-command nil)
  15476. (defun org-self-insert-command (N)
  15477. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  15478. If the cursor is in a table looking at whitespace, the whitespace is
  15479. overwritten, and the table is not marked as requiring realignment."
  15480. (interactive "p")
  15481. (org-check-before-invisible-edit 'insert)
  15482. (cond
  15483. ((and org-use-speed-commands
  15484. (let ((kv (this-command-keys-vector)))
  15485. (setq org-speed-command
  15486. (run-hook-with-args-until-success
  15487. 'org-speed-command-hook
  15488. (make-string 1 (aref kv (1- (length kv))))))))
  15489. (cond
  15490. ((commandp org-speed-command)
  15491. (setq this-command org-speed-command)
  15492. (call-interactively org-speed-command))
  15493. ((functionp org-speed-command)
  15494. (funcall org-speed-command))
  15495. ((and org-speed-command (listp org-speed-command))
  15496. (eval org-speed-command))
  15497. (t (let (org-use-speed-commands)
  15498. (call-interactively 'org-self-insert-command)))))
  15499. ((and
  15500. (= N 1)
  15501. (not (org-region-active-p))
  15502. (org-at-table-p)
  15503. (progn
  15504. ;; Check if we blank the field, and if that triggers align.
  15505. (and (featurep 'org-table)
  15506. org-table-auto-blank-field
  15507. (memq last-command
  15508. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  15509. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  15510. ;; Got extra space, this field does not determine
  15511. ;; column width.
  15512. (let (org-table-may-need-update) (org-table-blank-field))
  15513. ;; No extra space, this field may determine column
  15514. ;; width.
  15515. (org-table-blank-field)))
  15516. t)
  15517. (looking-at "[^|\n]* |"))
  15518. ;; There is room for insertion without re-aligning the table.
  15519. (self-insert-command N)
  15520. (org-table-with-shrunk-field
  15521. (save-excursion
  15522. (skip-chars-forward "^|")
  15523. ;; Do not delete last space, which is
  15524. ;; `org-table-separator-space', but the regular space before
  15525. ;; it.
  15526. (delete-region (- (point) 2) (1- (point))))))
  15527. (t
  15528. (setq org-table-may-need-update t)
  15529. (self-insert-command N)
  15530. (org-fix-tags-on-the-fly)
  15531. (when org-self-insert-cluster-for-undo
  15532. (if (not (eq last-command 'org-self-insert-command))
  15533. (setq org-self-insert-command-undo-counter 1)
  15534. (if (>= org-self-insert-command-undo-counter 20)
  15535. (setq org-self-insert-command-undo-counter 1)
  15536. (and (> org-self-insert-command-undo-counter 0)
  15537. buffer-undo-list (listp buffer-undo-list)
  15538. (not (cadr buffer-undo-list)) ; remove nil entry
  15539. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15540. (setq org-self-insert-command-undo-counter
  15541. (1+ org-self-insert-command-undo-counter))))))))
  15542. (defun org-check-before-invisible-edit (kind)
  15543. "Check is editing if kind KIND would be dangerous with invisible text around.
  15544. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15545. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15546. (when (and org-catch-invisible-edits
  15547. (or (not (boundp 'visible-mode)) (not visible-mode))
  15548. (or (get-char-property (point) 'invisible)
  15549. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15550. ;; OK, we need to take a closer look. Do not consider
  15551. ;; invisibility obtained through text properties (e.g., link
  15552. ;; fontification), as it cannot be toggled.
  15553. (let* ((invisible-at-point
  15554. (pcase (get-char-property-and-overlay (point) 'invisible)
  15555. (`(,_ . ,(and (pred overlayp) o)) o)))
  15556. ;; Assume that point cannot land in the middle of an
  15557. ;; overlay, or between two overlays.
  15558. (invisible-before-point
  15559. (and (not invisible-at-point)
  15560. (not (bobp))
  15561. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15562. (`(,_ . ,(and (pred overlayp) o)) o))))
  15563. (border-and-ok-direction
  15564. (or
  15565. ;; Check if we are acting predictably before invisible
  15566. ;; text.
  15567. (and invisible-at-point
  15568. (memq kind '(insert delete-backward)))
  15569. ;; Check if we are acting predictably after invisible text
  15570. ;; This works not well, and I have turned it off. It seems
  15571. ;; better to always show and stop after invisible text.
  15572. ;; (and (not invisible-at-point) invisible-before-point
  15573. ;; (memq kind '(insert delete)))
  15574. )))
  15575. (when (or invisible-at-point invisible-before-point)
  15576. (when (eq org-catch-invisible-edits 'error)
  15577. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15578. (if (and org-custom-properties-overlays
  15579. (y-or-n-p "Display invisible properties in this buffer? "))
  15580. (org-toggle-custom-properties-visibility)
  15581. ;; Make the area visible
  15582. (save-excursion
  15583. (when invisible-before-point
  15584. (goto-char
  15585. (previous-single-char-property-change (point) 'invisible)))
  15586. ;; Remove whatever overlay is currently making yet-to-be
  15587. ;; edited text invisible. Also remove nested invisibility
  15588. ;; related overlays.
  15589. (delete-overlay (or invisible-at-point invisible-before-point))
  15590. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15591. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15592. (`(,_ . ,(and (pred overlayp) o))
  15593. (delete-overlay o)
  15594. t)))))
  15595. (cond
  15596. ((eq org-catch-invisible-edits 'show)
  15597. ;; That's it, we do the edit after showing
  15598. (message
  15599. "Unfolding invisible region around point before editing")
  15600. (sit-for 1))
  15601. ((and (eq org-catch-invisible-edits 'smart)
  15602. border-and-ok-direction)
  15603. (message "Unfolding invisible region around point before editing"))
  15604. (t
  15605. ;; Don't do the edit, make the user repeat it in full visibility
  15606. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15607. (defun org-fix-tags-on-the-fly ()
  15608. "Align tags in headline at point.
  15609. Unlike `org-align-tags', this function does nothing if point is
  15610. either not currently on a tagged headline or on a tag."
  15611. (when (and (org-match-line org-tag-line-re)
  15612. (< (point) (match-beginning 1)))
  15613. (org-align-tags)))
  15614. (defun org-delete-backward-char (N)
  15615. "Like `delete-backward-char', insert whitespace at field end in tables.
  15616. When deleting backwards, in tables this function will insert whitespace in
  15617. front of the next \"|\" separator, to keep the table aligned. The table will
  15618. still be marked for re-alignment if the field did fill the entire column,
  15619. because, in this case the deletion might narrow the column."
  15620. (interactive "p")
  15621. (save-match-data
  15622. (org-check-before-invisible-edit 'delete-backward)
  15623. (if (and (= N 1)
  15624. (not overwrite-mode)
  15625. (not (org-region-active-p))
  15626. (not (eq (char-before) ?|))
  15627. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15628. (looking-at-p ".*?|")
  15629. (org-at-table-p))
  15630. (progn (forward-char -1) (org-delete-char 1))
  15631. (backward-delete-char N)
  15632. (org-fix-tags-on-the-fly))))
  15633. (defun org-delete-char (N)
  15634. "Like `delete-char', but insert whitespace at field end in tables.
  15635. When deleting characters, in tables this function will insert whitespace in
  15636. front of the next \"|\" separator, to keep the table aligned. The table will
  15637. still be marked for re-alignment if the field did fill the entire column,
  15638. because, in this case the deletion might narrow the column."
  15639. (interactive "p")
  15640. (save-match-data
  15641. (org-check-before-invisible-edit 'delete)
  15642. (cond
  15643. ((or (/= N 1)
  15644. (eq (char-after) ?|)
  15645. (save-excursion (skip-chars-backward " \t") (bolp))
  15646. (not (org-at-table-p)))
  15647. (delete-char N)
  15648. (org-fix-tags-on-the-fly))
  15649. ((looking-at ".\\(.*?\\)|")
  15650. (let* ((update? org-table-may-need-update)
  15651. (noalign (looking-at-p ".*? |")))
  15652. (delete-char 1)
  15653. (org-table-with-shrunk-field
  15654. (save-excursion
  15655. ;; Last space is `org-table-separator-space', so insert
  15656. ;; a regular one before it instead.
  15657. (goto-char (- (match-end 0) 2))
  15658. (insert " ")))
  15659. ;; If there were two spaces at the end, this field does not
  15660. ;; determine the width of the column.
  15661. (when noalign (setq org-table-may-need-update update?))))
  15662. (t
  15663. (delete-char N)))))
  15664. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15665. (put 'org-self-insert-command 'delete-selection
  15666. (lambda ()
  15667. (not (run-hook-with-args-until-success
  15668. 'self-insert-uses-region-functions))))
  15669. (put 'orgtbl-self-insert-command 'delete-selection
  15670. (lambda ()
  15671. (not (run-hook-with-args-until-success
  15672. 'self-insert-uses-region-functions))))
  15673. (put 'org-delete-char 'delete-selection 'supersede)
  15674. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15675. (put 'org-yank 'delete-selection 'yank)
  15676. ;; Make `flyspell-mode' delay after some commands
  15677. (put 'org-self-insert-command 'flyspell-delayed t)
  15678. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15679. (put 'org-delete-char 'flyspell-delayed t)
  15680. (put 'org-delete-backward-char 'flyspell-delayed t)
  15681. ;; Make pabbrev-mode expand after Org mode commands
  15682. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15683. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15684. (defun org-transpose-words ()
  15685. "Transpose words for Org.
  15686. This uses the `org-mode-transpose-word-syntax-table' syntax
  15687. table, which interprets characters in `org-emphasis-alist' as
  15688. word constituents."
  15689. (interactive)
  15690. (with-syntax-table org-mode-transpose-word-syntax-table
  15691. (call-interactively 'transpose-words)))
  15692. (defvar org-ctrl-c-ctrl-c-hook nil
  15693. "Hook for functions attaching themselves to `C-c C-c'.
  15694. This can be used to add additional functionality to the C-c C-c
  15695. key which executes context-dependent commands. This hook is run
  15696. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15697. run after the last test.
  15698. Each function will be called with no arguments. The function
  15699. must check if the context is appropriate for it to act. If yes,
  15700. it should do its thing and then return a non-nil value. If the
  15701. context is wrong, just do nothing and return nil.")
  15702. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15703. "Hook for functions attaching themselves to `C-c C-c'.
  15704. This can be used to add additional functionality to the C-c C-c
  15705. key which executes context-dependent commands. This hook is run
  15706. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15707. before the first test.
  15708. Each function will be called with no arguments. The function
  15709. must check if the context is appropriate for it to act. If yes,
  15710. it should do its thing and then return a non-nil value. If the
  15711. context is wrong, just do nothing and return nil.")
  15712. (defvar org-tab-first-hook nil
  15713. "Hook for functions to attach themselves to TAB.
  15714. See `org-ctrl-c-ctrl-c-hook' for more information.
  15715. This hook runs as the first action when TAB is pressed, even before
  15716. `org-cycle' messes around with the `outline-regexp' to cater for
  15717. inline tasks and plain list item folding.
  15718. If any function in this hook returns t, any other actions that
  15719. would have been caused by TAB (such as table field motion or visibility
  15720. cycling) will not occur.")
  15721. (defvar org-tab-after-check-for-table-hook nil
  15722. "Hook for functions to attach themselves to TAB.
  15723. See `org-ctrl-c-ctrl-c-hook' for more information.
  15724. This hook runs after it has been established that the cursor is not in a
  15725. table, but before checking if the cursor is in a headline or if global cycling
  15726. should be done.
  15727. If any function in this hook returns t, not other actions like visibility
  15728. cycling will be done.")
  15729. (defvar org-tab-after-check-for-cycling-hook nil
  15730. "Hook for functions to attach themselves to TAB.
  15731. See `org-ctrl-c-ctrl-c-hook' for more information.
  15732. This hook runs after it has been established that not table field motion and
  15733. not visibility should be done because of current context. This is probably
  15734. the place where a package like yasnippets can hook in.")
  15735. (defvar org-tab-before-tab-emulation-hook nil
  15736. "Hook for functions to attach themselves to TAB.
  15737. See `org-ctrl-c-ctrl-c-hook' for more information.
  15738. This hook runs after every other options for TAB have been exhausted, but
  15739. before indentation and \t insertion takes place.")
  15740. (defvar org-metaleft-hook nil
  15741. "Hook for functions attaching themselves to `M-left'.
  15742. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15743. (defvar org-metaright-hook nil
  15744. "Hook for functions attaching themselves to `M-right'.
  15745. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15746. (defvar org-metaup-hook nil
  15747. "Hook for functions attaching themselves to `M-up'.
  15748. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15749. (defvar org-metadown-hook nil
  15750. "Hook for functions attaching themselves to `M-down'.
  15751. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15752. (defvar org-shiftmetaleft-hook nil
  15753. "Hook for functions attaching themselves to `M-S-left'.
  15754. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15755. (defvar org-shiftmetaright-hook nil
  15756. "Hook for functions attaching themselves to `M-S-right'.
  15757. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15758. (defvar org-shiftmetaup-hook nil
  15759. "Hook for functions attaching themselves to `M-S-up'.
  15760. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15761. (defvar org-shiftmetadown-hook nil
  15762. "Hook for functions attaching themselves to `M-S-down'.
  15763. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15764. (defvar org-metareturn-hook nil
  15765. "Hook for functions attaching themselves to `M-RET'.
  15766. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15767. (defvar org-shiftup-hook nil
  15768. "Hook for functions attaching themselves to `S-up'.
  15769. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15770. (defvar org-shiftup-final-hook nil
  15771. "Hook for functions attaching themselves to `S-up'.
  15772. This one runs after all other options except shift-select have been excluded.
  15773. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15774. (defvar org-shiftdown-hook nil
  15775. "Hook for functions attaching themselves to `S-down'.
  15776. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15777. (defvar org-shiftdown-final-hook nil
  15778. "Hook for functions attaching themselves to `S-down'.
  15779. This one runs after all other options except shift-select have been excluded.
  15780. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15781. (defvar org-shiftleft-hook nil
  15782. "Hook for functions attaching themselves to `S-left'.
  15783. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15784. (defvar org-shiftleft-final-hook nil
  15785. "Hook for functions attaching themselves to `S-left'.
  15786. This one runs after all other options except shift-select have been excluded.
  15787. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15788. (defvar org-shiftright-hook nil
  15789. "Hook for functions attaching themselves to `S-right'.
  15790. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15791. (defvar org-shiftright-final-hook nil
  15792. "Hook for functions attaching themselves to `S-right'.
  15793. This one runs after all other options except shift-select have been excluded.
  15794. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15795. (defun org-modifier-cursor-error ()
  15796. "Throw an error, a modified cursor command was applied in wrong context."
  15797. (user-error "This command is active in special context like tables, headlines or items"))
  15798. (defun org-shiftselect-error ()
  15799. "Throw an error because Shift-Cursor command was applied in wrong context."
  15800. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15801. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15802. (user-error "This command works only in special context like headlines or timestamps")))
  15803. (defun org-call-for-shift-select (cmd)
  15804. (let ((this-command-keys-shift-translated t))
  15805. (call-interactively cmd)))
  15806. (defun org-shifttab (&optional arg)
  15807. "Global visibility cycling or move to previous table field.
  15808. Call `org-table-previous-field' within a table.
  15809. When ARG is nil, cycle globally through visibility states.
  15810. When ARG is a numeric prefix, show contents of this level."
  15811. (interactive "P")
  15812. (cond
  15813. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15814. ((integerp arg)
  15815. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15816. (message "Content view to level: %d" arg)
  15817. (org-content (prefix-numeric-value arg2))
  15818. (org-cycle-show-empty-lines t)
  15819. (setq org-cycle-global-status 'overview)))
  15820. (t (call-interactively 'org-global-cycle))))
  15821. (defun org-shiftmetaleft ()
  15822. "Promote subtree or delete table column.
  15823. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15824. `org-table-delete-column', depending on context. See the
  15825. individual commands for more information."
  15826. (interactive)
  15827. (cond
  15828. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15829. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15830. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15831. ((if (not (org-region-active-p)) (org-at-item-p)
  15832. (save-excursion (goto-char (region-beginning))
  15833. (org-at-item-p)))
  15834. (call-interactively 'org-outdent-item-tree))
  15835. (t (org-modifier-cursor-error))))
  15836. (defun org-shiftmetaright ()
  15837. "Demote subtree or insert table column.
  15838. Calls `org-demote-subtree', `org-indent-item-tree', or
  15839. `org-table-insert-column', depending on context. See the
  15840. individual commands for more information."
  15841. (interactive)
  15842. (cond
  15843. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15844. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15845. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15846. ((if (not (org-region-active-p)) (org-at-item-p)
  15847. (save-excursion (goto-char (region-beginning))
  15848. (org-at-item-p)))
  15849. (call-interactively 'org-indent-item-tree))
  15850. (t (org-modifier-cursor-error))))
  15851. (defun org-shiftmetaup (&optional _arg)
  15852. "Drag the line at point up.
  15853. In a table, kill the current row.
  15854. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15855. but also adjust the previous clocked item in the clock history.
  15856. Everywhere else, drag the line at point up."
  15857. (interactive "P")
  15858. (cond
  15859. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15860. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15861. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15862. (call-interactively 'org-timestamp-up)))
  15863. (t (call-interactively 'org-drag-line-backward))))
  15864. (defun org-shiftmetadown (&optional _arg)
  15865. "Drag the line at point down.
  15866. In a table, insert an empty row at the current line.
  15867. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15868. but also adjust the previous clocked item in the clock history.
  15869. Everywhere else, drag the line at point down."
  15870. (interactive "P")
  15871. (cond
  15872. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15873. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15874. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15875. (call-interactively 'org-timestamp-down)))
  15876. (t (call-interactively 'org-drag-line-forward))))
  15877. (defsubst org-hidden-tree-error ()
  15878. (user-error
  15879. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15880. (defun org-metaleft (&optional _arg)
  15881. "Promote heading, list item at point or move table column left.
  15882. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15883. depending on context. With no specific context, calls the Emacs
  15884. default `backward-word'. See the individual commands for more
  15885. information.
  15886. This function runs the hook `org-metaleft-hook' as a first step,
  15887. and returns at first non-nil value."
  15888. (interactive "P")
  15889. (cond
  15890. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15891. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15892. ((org-with-limited-levels
  15893. (or (org-at-heading-p)
  15894. (and (org-region-active-p)
  15895. (save-excursion
  15896. (goto-char (region-beginning))
  15897. (org-at-heading-p)))))
  15898. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15899. (call-interactively 'org-do-promote))
  15900. ;; At an inline task.
  15901. ((org-at-heading-p)
  15902. (call-interactively 'org-inlinetask-promote))
  15903. ((or (org-at-item-p)
  15904. (and (org-region-active-p)
  15905. (save-excursion
  15906. (goto-char (region-beginning))
  15907. (org-at-item-p))))
  15908. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15909. (call-interactively 'org-outdent-item))
  15910. (t (call-interactively 'backward-word))))
  15911. (defun org-metaright (&optional _arg)
  15912. "Demote heading, list item at point or move table column right.
  15913. In front of a drawer or a block keyword, indent it correctly.
  15914. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15915. `org-indent-drawer' or `org-indent-block' depending on context.
  15916. With no specific context, calls the Emacs default `forward-word'.
  15917. See the individual commands for more information.
  15918. This function runs the hook `org-metaright-hook' as a first step,
  15919. and returns at first non-nil value."
  15920. (interactive "P")
  15921. (cond
  15922. ((run-hook-with-args-until-success 'org-metaright-hook))
  15923. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15924. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15925. ((org-at-block-p) (call-interactively 'org-indent-block))
  15926. ((org-with-limited-levels
  15927. (or (org-at-heading-p)
  15928. (and (org-region-active-p)
  15929. (save-excursion
  15930. (goto-char (region-beginning))
  15931. (org-at-heading-p)))))
  15932. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15933. (call-interactively 'org-do-demote))
  15934. ;; At an inline task.
  15935. ((org-at-heading-p)
  15936. (call-interactively 'org-inlinetask-demote))
  15937. ((or (org-at-item-p)
  15938. (and (org-region-active-p)
  15939. (save-excursion
  15940. (goto-char (region-beginning))
  15941. (org-at-item-p))))
  15942. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15943. (call-interactively 'org-indent-item))
  15944. (t (call-interactively 'forward-word))))
  15945. (defun org-check-for-hidden (what)
  15946. "Check if there are hidden headlines/items in the current visual line.
  15947. WHAT can be either `headlines' or `items'. If the current line is
  15948. an outline or item heading and it has a folded subtree below it,
  15949. this function returns t, nil otherwise."
  15950. (let ((re (cond
  15951. ((eq what 'headlines) org-outline-regexp-bol)
  15952. ((eq what 'items) (org-item-beginning-re))
  15953. (t (error "This should not happen"))))
  15954. beg end)
  15955. (save-excursion
  15956. (catch 'exit
  15957. (unless (org-region-active-p)
  15958. (setq beg (point-at-bol))
  15959. (beginning-of-line 2)
  15960. (while (and (not (eobp)) ;; this is like `next-line'
  15961. (get-char-property (1- (point)) 'invisible))
  15962. (beginning-of-line 2))
  15963. (setq end (point))
  15964. (goto-char beg)
  15965. (goto-char (point-at-eol))
  15966. (setq end (max end (point)))
  15967. (while (re-search-forward re end t)
  15968. (when (get-char-property (match-beginning 0) 'invisible)
  15969. (throw 'exit t))))
  15970. nil))))
  15971. (defun org-metaup (&optional _arg)
  15972. "Move subtree up or move table row up.
  15973. Calls `org-move-subtree-up' or `org-table-move-row' or
  15974. `org-move-item-up', depending on context. See the individual commands
  15975. for more information."
  15976. (interactive "P")
  15977. (cond
  15978. ((run-hook-with-args-until-success 'org-metaup-hook))
  15979. ((org-region-active-p)
  15980. (let* ((a (save-excursion
  15981. (goto-char (min (region-beginning) (region-end)))
  15982. (line-beginning-position)))
  15983. (b (save-excursion
  15984. (goto-char (max (region-beginning) (region-end)))
  15985. (if (bolp) (1- (point)) (line-end-position))))
  15986. (c (save-excursion
  15987. (goto-char a)
  15988. (move-beginning-of-line 0)
  15989. (point)))
  15990. (d (save-excursion
  15991. (goto-char a)
  15992. (move-end-of-line 0)
  15993. (point))))
  15994. (transpose-regions a b c d)
  15995. (goto-char c)))
  15996. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15997. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15998. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15999. (t (org-drag-element-backward))))
  16000. (defun org-metadown (&optional _arg)
  16001. "Move subtree down or move table row down.
  16002. Calls `org-move-subtree-down' or `org-table-move-row' or
  16003. `org-move-item-down', depending on context. See the individual
  16004. commands for more information."
  16005. (interactive "P")
  16006. (cond
  16007. ((run-hook-with-args-until-success 'org-metadown-hook))
  16008. ((org-region-active-p)
  16009. (let* ((a (save-excursion
  16010. (goto-char (min (region-beginning) (region-end)))
  16011. (line-beginning-position)))
  16012. (b (save-excursion
  16013. (goto-char (max (region-beginning) (region-end)))
  16014. (if (bolp) (1- (point)) (line-end-position))))
  16015. (c (save-excursion
  16016. (goto-char b)
  16017. (move-beginning-of-line (if (bolp) 1 2))
  16018. (point)))
  16019. (d (save-excursion
  16020. (goto-char b)
  16021. (move-end-of-line (if (bolp) 1 2))
  16022. (point))))
  16023. (transpose-regions a b c d)
  16024. (goto-char d)))
  16025. ((org-at-table-p) (call-interactively 'org-table-move-row))
  16026. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  16027. ((org-at-item-p) (call-interactively 'org-move-item-down))
  16028. (t (org-drag-element-forward))))
  16029. (defun org-shiftup (&optional arg)
  16030. "Act on current element according to context.
  16031. Call `org-timestamp-up' or `org-priority-up', or
  16032. `org-previous-item', or `org-table-move-cell-up'. See the
  16033. individual commands for more information."
  16034. (interactive "P")
  16035. (cond
  16036. ((run-hook-with-args-until-success 'org-shiftup-hook))
  16037. ((and org-support-shift-select (org-region-active-p))
  16038. (org-call-for-shift-select 'previous-line))
  16039. ((org-at-timestamp-p 'lax)
  16040. (call-interactively (if org-edit-timestamp-down-means-later
  16041. 'org-timestamp-down 'org-timestamp-up)))
  16042. ((and (not (eq org-support-shift-select 'always))
  16043. org-priority-enable-commands
  16044. (org-at-heading-p))
  16045. (call-interactively 'org-priority-up))
  16046. ((and (not org-support-shift-select) (org-at-item-p))
  16047. (call-interactively 'org-previous-item))
  16048. ((org-clocktable-try-shift 'up arg))
  16049. ((org-at-table-p) (org-table-move-cell-up))
  16050. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  16051. (org-support-shift-select
  16052. (org-call-for-shift-select 'previous-line))
  16053. (t (org-shiftselect-error))))
  16054. (defun org-shiftdown (&optional arg)
  16055. "Act on current element according to context.
  16056. Call `org-timestamp-down' or `org-priority-down', or
  16057. `org-next-item', or `org-table-move-cell-down'. See the
  16058. individual commands for more information."
  16059. (interactive "P")
  16060. (cond
  16061. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  16062. ((and org-support-shift-select (org-region-active-p))
  16063. (org-call-for-shift-select 'next-line))
  16064. ((org-at-timestamp-p 'lax)
  16065. (call-interactively (if org-edit-timestamp-down-means-later
  16066. 'org-timestamp-up 'org-timestamp-down)))
  16067. ((and (not (eq org-support-shift-select 'always))
  16068. org-priority-enable-commands
  16069. (org-at-heading-p))
  16070. (call-interactively 'org-priority-down))
  16071. ((and (not org-support-shift-select) (org-at-item-p))
  16072. (call-interactively 'org-next-item))
  16073. ((org-clocktable-try-shift 'down arg))
  16074. ((org-at-table-p) (org-table-move-cell-down))
  16075. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  16076. (org-support-shift-select
  16077. (org-call-for-shift-select 'next-line))
  16078. (t (org-shiftselect-error))))
  16079. (defun org-shiftright (&optional arg)
  16080. "Act on the current element according to context.
  16081. This does one of the following:
  16082. - switch a timestamp at point one day into the future
  16083. - on a headline, switch to the next TODO keyword
  16084. - on an item, switch entire list to the next bullet type
  16085. - on a property line, switch to the next allowed value
  16086. - on a clocktable definition line, move time block into the future
  16087. - in a table, move a single cell right"
  16088. (interactive "P")
  16089. (cond
  16090. ((run-hook-with-args-until-success 'org-shiftright-hook))
  16091. ((and org-support-shift-select (org-region-active-p))
  16092. (org-call-for-shift-select 'forward-char))
  16093. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  16094. ((and (not (eq org-support-shift-select 'always))
  16095. (org-at-heading-p))
  16096. (let ((org-inhibit-logging
  16097. (not org-treat-S-cursor-todo-selection-as-state-change))
  16098. (org-inhibit-blocking
  16099. (not org-treat-S-cursor-todo-selection-as-state-change)))
  16100. (org-call-with-arg 'org-todo 'right)))
  16101. ((or (and org-support-shift-select
  16102. (not (eq org-support-shift-select 'always))
  16103. (org-at-item-bullet-p))
  16104. (and (not org-support-shift-select) (org-at-item-p)))
  16105. (org-call-with-arg 'org-cycle-list-bullet nil))
  16106. ((and (not (eq org-support-shift-select 'always))
  16107. (org-at-property-p))
  16108. (call-interactively 'org-property-next-allowed-value))
  16109. ((org-clocktable-try-shift 'right arg))
  16110. ((org-at-table-p) (org-table-move-cell-right))
  16111. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  16112. (org-support-shift-select
  16113. (org-call-for-shift-select 'forward-char))
  16114. (t (org-shiftselect-error))))
  16115. (defun org-shiftleft (&optional arg)
  16116. "Act on current element according to context.
  16117. This does one of the following:
  16118. - switch a timestamp at point one day into the past
  16119. - on a headline, switch to the previous TODO keyword.
  16120. - on an item, switch entire list to the previous bullet type
  16121. - on a property line, switch to the previous allowed value
  16122. - on a clocktable definition line, move time block into the past
  16123. - in a table, move a single cell left"
  16124. (interactive "P")
  16125. (cond
  16126. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  16127. ((and org-support-shift-select (org-region-active-p))
  16128. (org-call-for-shift-select 'backward-char))
  16129. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  16130. ((and (not (eq org-support-shift-select 'always))
  16131. (org-at-heading-p))
  16132. (let ((org-inhibit-logging
  16133. (not org-treat-S-cursor-todo-selection-as-state-change))
  16134. (org-inhibit-blocking
  16135. (not org-treat-S-cursor-todo-selection-as-state-change)))
  16136. (org-call-with-arg 'org-todo 'left)))
  16137. ((or (and org-support-shift-select
  16138. (not (eq org-support-shift-select 'always))
  16139. (org-at-item-bullet-p))
  16140. (and (not org-support-shift-select) (org-at-item-p)))
  16141. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  16142. ((and (not (eq org-support-shift-select 'always))
  16143. (org-at-property-p))
  16144. (call-interactively 'org-property-previous-allowed-value))
  16145. ((org-clocktable-try-shift 'left arg))
  16146. ((org-at-table-p) (org-table-move-cell-left))
  16147. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  16148. (org-support-shift-select
  16149. (org-call-for-shift-select 'backward-char))
  16150. (t (org-shiftselect-error))))
  16151. (defun org-shiftcontrolright ()
  16152. "Switch to next TODO set."
  16153. (interactive)
  16154. (cond
  16155. ((and org-support-shift-select (org-region-active-p))
  16156. (org-call-for-shift-select 'forward-word))
  16157. ((and (not (eq org-support-shift-select 'always))
  16158. (org-at-heading-p))
  16159. (org-call-with-arg 'org-todo 'nextset))
  16160. (org-support-shift-select
  16161. (org-call-for-shift-select 'forward-word))
  16162. (t (org-shiftselect-error))))
  16163. (defun org-shiftcontrolleft ()
  16164. "Switch to previous TODO set."
  16165. (interactive)
  16166. (cond
  16167. ((and org-support-shift-select (org-region-active-p))
  16168. (org-call-for-shift-select 'backward-word))
  16169. ((and (not (eq org-support-shift-select 'always))
  16170. (org-at-heading-p))
  16171. (org-call-with-arg 'org-todo 'previousset))
  16172. (org-support-shift-select
  16173. (org-call-for-shift-select 'backward-word))
  16174. (t (org-shiftselect-error))))
  16175. (defun org-shiftcontrolup (&optional n)
  16176. "Change timestamps synchronously up in CLOCK log lines.
  16177. Optional argument N tells to change by that many units."
  16178. (interactive "P")
  16179. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  16180. (let (org-support-shift-select)
  16181. (org-clock-timestamps-up n))
  16182. (user-error "Not at a clock log")))
  16183. (defun org-shiftcontroldown (&optional n)
  16184. "Change timestamps synchronously down in CLOCK log lines.
  16185. Optional argument N tells to change by that many units."
  16186. (interactive "P")
  16187. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  16188. (let (org-support-shift-select)
  16189. (org-clock-timestamps-down n))
  16190. (user-error "Not at a clock log")))
  16191. (defun org-increase-number-at-point (&optional inc)
  16192. "Increment the number at point.
  16193. With an optional prefix numeric argument INC, increment using
  16194. this numeric value."
  16195. (interactive "p")
  16196. (if (not (number-at-point))
  16197. (user-error "Not on a number")
  16198. (unless inc (setq inc 1))
  16199. (let ((pos (point))
  16200. (beg (skip-chars-backward "-+^/*0-9eE."))
  16201. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  16202. (setq nap (buffer-substring-no-properties
  16203. (+ pos beg) (+ pos beg end)))
  16204. (delete-region (+ pos beg) (+ pos beg end))
  16205. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  16206. (when (org-at-table-p)
  16207. (org-table-align)
  16208. (org-table-end-of-field 1))))
  16209. (defun org-decrease-number-at-point (&optional inc)
  16210. "Decrement the number at point.
  16211. With an optional prefix numeric argument INC, decrement using
  16212. this numeric value."
  16213. (interactive "p")
  16214. (org-increase-number-at-point (- (or inc 1))))
  16215. (defun org-ctrl-c-ret ()
  16216. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  16217. (interactive)
  16218. (cond
  16219. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  16220. (t (call-interactively 'org-insert-heading))))
  16221. (defun org-copy-visible (beg end)
  16222. "Copy the visible parts of the region."
  16223. (interactive "r")
  16224. (let ((result ""))
  16225. (while (/= beg end)
  16226. (when (get-char-property beg 'invisible)
  16227. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  16228. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  16229. (setq result (concat result (buffer-substring beg next)))
  16230. (setq beg next)))
  16231. (setq deactivate-mark t)
  16232. (kill-new result)
  16233. (message "Visible strings have been copied to the kill ring.")))
  16234. (defun org-copy-special ()
  16235. "Copy region in table or copy current subtree.
  16236. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  16237. context. See the individual commands for more information."
  16238. (interactive)
  16239. (call-interactively
  16240. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  16241. (defun org-cut-special ()
  16242. "Cut region in table or cut current subtree.
  16243. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  16244. context. See the individual commands for more information."
  16245. (interactive)
  16246. (call-interactively
  16247. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  16248. (defun org-paste-special (arg)
  16249. "Paste rectangular region into table, or past subtree relative to level.
  16250. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  16251. See the individual commands for more information."
  16252. (interactive "P")
  16253. (if (org-at-table-p)
  16254. (org-table-paste-rectangle)
  16255. (org-paste-subtree arg)))
  16256. (defun org-edit-special (&optional arg)
  16257. "Call a special editor for the element at point.
  16258. When at a table, call the formula editor with `org-table-edit-formulas'.
  16259. When in a source code block, call `org-edit-src-code'.
  16260. When in a fixed-width region, call `org-edit-fixed-width-region'.
  16261. When in an export block, call `org-edit-export-block'.
  16262. When in a LaTeX environment, call `org-edit-latex-environment'.
  16263. When at an #+INCLUDE keyword, visit the included file.
  16264. When at a footnote reference, call `org-edit-footnote-reference'.
  16265. When at a planning line call, `org-deadline' and/or `org-schedule'.
  16266. When at an active timestamp, call `org-time-stamp'.
  16267. When at an inactive timestamp, call `org-time-stamp-inactive'.
  16268. On a link, call `ffap' to visit the link at point.
  16269. Otherwise, return a user error."
  16270. (interactive "P")
  16271. (let ((element (org-element-at-point)))
  16272. (barf-if-buffer-read-only)
  16273. (pcase (org-element-type element)
  16274. (`src-block
  16275. (if (not arg) (org-edit-src-code)
  16276. (let* ((info (org-babel-get-src-block-info))
  16277. (lang (nth 0 info))
  16278. (params (nth 2 info))
  16279. (session (cdr (assq :session params))))
  16280. (if (not session) (org-edit-src-code)
  16281. ;; At a source block with a session and function called
  16282. ;; with an ARG: switch to the buffer related to the
  16283. ;; inferior process.
  16284. (switch-to-buffer
  16285. (funcall (intern (concat "org-babel-prep-session:" lang))
  16286. session params))))))
  16287. (`keyword
  16288. (unless (member (org-element-property :key element)
  16289. '("INCLUDE" "SETUPFILE"))
  16290. (user-error "No special environment to edit here"))
  16291. (let ((value (org-element-property :value element)))
  16292. (unless (org-string-nw-p value) (user-error "No file to edit"))
  16293. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  16294. (or (match-string 1 value)
  16295. (match-string 0 value)))))
  16296. (when (org-file-url-p file)
  16297. (user-error "Files located with a URL cannot be edited"))
  16298. (org-link-open-from-string
  16299. (format "[[%s]]" (expand-file-name file))))))
  16300. (`table
  16301. (if (eq (org-element-property :type element) 'table.el)
  16302. (org-edit-table.el)
  16303. (call-interactively 'org-table-edit-formulas)))
  16304. ;; Only Org tables contain `table-row' type elements.
  16305. (`table-row (call-interactively 'org-table-edit-formulas))
  16306. (`example-block (org-edit-src-code))
  16307. (`export-block (org-edit-export-block))
  16308. (`fixed-width (org-edit-fixed-width-region))
  16309. (`latex-environment (org-edit-latex-environment))
  16310. (`planning
  16311. (let ((proplist (cadr element)))
  16312. (mapc #'call-interactively
  16313. (remq nil
  16314. (list
  16315. (when (plist-get proplist :deadline) #'org-deadline)
  16316. (when (plist-get proplist :scheduled) #'org-schedule))))))
  16317. (_
  16318. ;; No notable element at point. Though, we may be at a link or
  16319. ;; a footnote reference, which are objects. Thus, scan deeper.
  16320. (let ((context (org-element-context element)))
  16321. (pcase (org-element-type context)
  16322. (`footnote-reference (org-edit-footnote-reference))
  16323. (`inline-src-block (org-edit-inline-src-code))
  16324. (`timestamp (if (eq 'inactive (org-element-property :type context))
  16325. (call-interactively #'org-time-stamp-inactive)
  16326. (call-interactively #'org-time-stamp)))
  16327. (`link (call-interactively #'ffap))
  16328. (_ (user-error "No special environment to edit here"))))))))
  16329. (defun org-ctrl-c-ctrl-c (&optional arg)
  16330. "Set tags in headline, or update according to changed information at point.
  16331. This command does many different things, depending on context:
  16332. - If column view is active, in agenda or org buffers, quit it.
  16333. - If there are highlights, remove them.
  16334. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  16335. this is what we do.
  16336. - If the cursor is on a statistics cookie, update it.
  16337. - If the cursor is in a headline, in an agenda or an org buffer,
  16338. prompt for tags and insert them into the current line, aligned
  16339. to `org-tags-column'. When called with prefix arg, realign all
  16340. tags in the current buffer.
  16341. - If the cursor is in one of the special #+KEYWORD lines, this
  16342. triggers scanning the buffer for these lines and updating the
  16343. information.
  16344. - If the cursor is inside a table, realign the table. This command
  16345. works even if the automatic table editor has been turned off.
  16346. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  16347. the entire table.
  16348. - If the cursor is at a footnote reference or definition, jump to
  16349. the corresponding definition or references, respectively.
  16350. - If the cursor is a the beginning of a dynamic block, update it.
  16351. - If the current buffer is a capture buffer, close note and file it.
  16352. - If the cursor is on a <<<target>>>, update radio targets and
  16353. corresponding links in this buffer.
  16354. - If the cursor is on a numbered item in a plain list, renumber the
  16355. ordered list.
  16356. - If the cursor is on a checkbox, toggle it.
  16357. - If the cursor is on a code block, evaluate it. The variable
  16358. `org-confirm-babel-evaluate' can be used to control prompting
  16359. before code block evaluation, by default every code block
  16360. evaluation requires confirmation. Code block evaluation can be
  16361. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  16362. (interactive "P")
  16363. (cond
  16364. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  16365. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  16366. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  16367. (org-remove-occur-highlights)
  16368. (message "Temporary highlights/overlays removed from current buffer"))
  16369. ((and (local-variable-p 'org-finish-function)
  16370. (fboundp org-finish-function))
  16371. (funcall org-finish-function))
  16372. ((org-babel-hash-at-point))
  16373. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  16374. (t
  16375. (let* ((context
  16376. (org-element-lineage
  16377. (org-element-context)
  16378. ;; Limit to supported contexts.
  16379. '(babel-call clock dynamic-block footnote-definition
  16380. footnote-reference inline-babel-call inline-src-block
  16381. inlinetask item keyword node-property paragraph
  16382. plain-list planning property-drawer radio-target
  16383. src-block statistics-cookie table table-cell table-row
  16384. timestamp)
  16385. t))
  16386. (type (org-element-type context)))
  16387. ;; For convenience: at the first line of a paragraph on the same
  16388. ;; line as an item, apply function on that item instead.
  16389. (when (eq type 'paragraph)
  16390. (let ((parent (org-element-property :parent context)))
  16391. (when (and (eq (org-element-type parent) 'item)
  16392. (= (line-beginning-position)
  16393. (org-element-property :begin parent)))
  16394. (setq context parent)
  16395. (setq type 'item))))
  16396. ;; Act according to type of element or object at point.
  16397. ;;
  16398. ;; Do nothing on a blank line, except if it is contained in
  16399. ;; a source block. Hence, we first check if point is in such
  16400. ;; a block and then if it is at a blank line.
  16401. (pcase type
  16402. ((or `inline-src-block `src-block)
  16403. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  16404. (org-babel-eval-wipe-error-buffer)
  16405. (org-babel-execute-src-block
  16406. current-prefix-arg (org-babel-get-src-block-info nil context))))
  16407. ((guard (org-match-line "[ \t]*$"))
  16408. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  16409. (user-error
  16410. (substitute-command-keys
  16411. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  16412. ((or `babel-call `inline-babel-call)
  16413. (let ((info (org-babel-lob-get-info context)))
  16414. (when info (org-babel-execute-src-block nil info))))
  16415. (`clock (org-clock-update-time-maybe))
  16416. (`dynamic-block
  16417. (save-excursion
  16418. (goto-char (org-element-property :post-affiliated context))
  16419. (org-update-dblock)))
  16420. (`footnote-definition
  16421. (goto-char (org-element-property :post-affiliated context))
  16422. (call-interactively 'org-footnote-action))
  16423. (`footnote-reference (call-interactively #'org-footnote-action))
  16424. ((or `headline `inlinetask)
  16425. (save-excursion (goto-char (org-element-property :begin context))
  16426. (call-interactively #'org-set-tags-command)))
  16427. (`item
  16428. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  16429. ;; unconditionally, whereas `C-u' will toggle its presence.
  16430. ;; Without a universal argument, if the item has a checkbox,
  16431. ;; toggle it. Otherwise repair the list.
  16432. (let* ((box (org-element-property :checkbox context))
  16433. (struct (org-element-property :structure context))
  16434. (old-struct (copy-tree struct))
  16435. (parents (org-list-parents-alist struct))
  16436. (prevs (org-list-prevs-alist struct))
  16437. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  16438. (org-list-set-checkbox
  16439. (org-element-property :begin context) struct
  16440. (cond ((equal arg '(16)) "[-]")
  16441. ((and (not box) (equal arg '(4))) "[ ]")
  16442. ((or (not box) (equal arg '(4))) nil)
  16443. ((eq box 'on) "[ ]")
  16444. (t "[X]")))
  16445. ;; Mimic `org-list-write-struct' but with grabbing a return
  16446. ;; value from `org-list-struct-fix-box'.
  16447. (org-list-struct-fix-ind struct parents 2)
  16448. (org-list-struct-fix-item-end struct)
  16449. (org-list-struct-fix-bul struct prevs)
  16450. (org-list-struct-fix-ind struct parents)
  16451. (let ((block-item
  16452. (org-list-struct-fix-box struct parents prevs orderedp)))
  16453. (if (and box (equal struct old-struct))
  16454. (if (equal arg '(16))
  16455. (message "Checkboxes already reset")
  16456. (user-error "Cannot toggle this checkbox: %s"
  16457. (if (eq box 'on)
  16458. "all subitems checked"
  16459. "unchecked subitems")))
  16460. (org-list-struct-apply-struct struct old-struct)
  16461. (org-update-checkbox-count-maybe))
  16462. (when block-item
  16463. (message "Checkboxes were removed due to empty box at line %d"
  16464. (org-current-line block-item))))))
  16465. (`keyword
  16466. (let ((org-inhibit-startup-visibility-stuff t)
  16467. (org-startup-align-all-tables nil))
  16468. (when (boundp 'org-table-coordinate-overlays)
  16469. (mapc #'delete-overlay org-table-coordinate-overlays)
  16470. (setq org-table-coordinate-overlays nil))
  16471. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  16472. (message "Local setup has been refreshed"))
  16473. (`plain-list
  16474. ;; At a plain list, with a double C-u argument, set
  16475. ;; checkboxes of each item to "[-]", whereas a single one
  16476. ;; will toggle their presence according to the state of the
  16477. ;; first item in the list. Without an argument, repair the
  16478. ;; list.
  16479. (let* ((begin (org-element-property :contents-begin context))
  16480. (struct (org-element-property :structure context))
  16481. (old-struct (copy-tree struct))
  16482. (first-box (save-excursion
  16483. (goto-char begin)
  16484. (looking-at org-list-full-item-re)
  16485. (match-string-no-properties 3)))
  16486. (new-box (cond ((equal arg '(16)) "[-]")
  16487. ((equal arg '(4)) (unless first-box "[ ]"))
  16488. ((equal first-box "[X]") "[ ]")
  16489. (t "[X]"))))
  16490. (cond
  16491. (arg
  16492. (dolist (pos
  16493. (org-list-get-all-items
  16494. begin struct (org-list-prevs-alist struct)))
  16495. (org-list-set-checkbox pos struct new-box)))
  16496. ((and first-box (eq (point) begin))
  16497. ;; For convenience, when point is at bol on the first
  16498. ;; item of the list and no argument is provided, simply
  16499. ;; toggle checkbox of that item, if any.
  16500. (org-list-set-checkbox begin struct new-box)))
  16501. (when (equal
  16502. (org-list-write-struct
  16503. struct (org-list-parents-alist struct) old-struct)
  16504. old-struct)
  16505. (message "Cannot update this checkbox"))
  16506. (org-update-checkbox-count-maybe)))
  16507. ((or `property-drawer `node-property)
  16508. (call-interactively #'org-property-action))
  16509. (`radio-target
  16510. (call-interactively #'org-update-radio-target-regexp))
  16511. (`statistics-cookie
  16512. (call-interactively #'org-update-statistics-cookies))
  16513. ((or `table `table-cell `table-row)
  16514. ;; At a table, recalculate every field and align it. Also
  16515. ;; send the table if necessary. If the table has
  16516. ;; a `table.el' type, just give up. At a table row or cell,
  16517. ;; maybe recalculate line but always align table.
  16518. (if (eq (org-element-property :type context) 'table.el)
  16519. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16520. Use `\\[org-edit-special]' to edit table.el tables"))
  16521. (if (or (eq type 'table)
  16522. ;; Check if point is at a TBLFM line.
  16523. (and (eq type 'table-row)
  16524. (= (point) (org-element-property :end context))))
  16525. (save-excursion
  16526. (if (org-at-TBLFM-p)
  16527. (progn (require 'org-table)
  16528. (org-table-calc-current-TBLFM))
  16529. (goto-char (org-element-property :contents-begin context))
  16530. (org-call-with-arg 'org-table-recalculate (or arg t))
  16531. (orgtbl-send-table 'maybe)))
  16532. (org-table-maybe-eval-formula)
  16533. (cond (arg (call-interactively #'org-table-recalculate))
  16534. ((org-table-maybe-recalculate-line))
  16535. (t (org-table-align))))))
  16536. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16537. (org-timestamp-change 0 'day))
  16538. ((and `nil (guard (org-at-heading-p)))
  16539. ;; When point is on an unsupported object type, we can miss
  16540. ;; the fact that it also is at a heading. Handle it here.
  16541. (call-interactively #'org-set-tags-command))
  16542. ((guard
  16543. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16544. (_
  16545. (user-error
  16546. (substitute-command-keys
  16547. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16548. (defun org-mode-restart ()
  16549. (interactive)
  16550. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16551. (funcall major-mode)
  16552. (hack-local-variables)
  16553. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16554. (org-indent-mode -1))
  16555. (org-reset-file-cache))
  16556. (message "%s restarted" major-mode))
  16557. (defun org-flag-above-first-heading (&optional arg)
  16558. "Hide from bob up to the first heading.
  16559. Move point to the beginning of first heading or end of buffer."
  16560. (goto-char (point-min))
  16561. (unless (org-at-heading-p)
  16562. (outline-next-heading))
  16563. (unless (bobp)
  16564. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16565. (defun org-show-branches-buffer ()
  16566. "Show all branches in the buffer."
  16567. (org-flag-above-first-heading)
  16568. (outline-hide-sublevels 1)
  16569. (unless (eobp)
  16570. (outline-show-branches)
  16571. (while (outline-get-next-sibling)
  16572. (outline-show-branches)))
  16573. (goto-char (point-min)))
  16574. (defun org-kill-note-or-show-branches ()
  16575. "Abort storing current note, or show just branches."
  16576. (interactive)
  16577. (cond (org-finish-function
  16578. (let ((org-note-abort t)) (funcall org-finish-function)))
  16579. ((org-before-first-heading-p)
  16580. (org-show-branches-buffer)
  16581. (org-hide-archived-subtrees (point-min) (point-max)))
  16582. (t
  16583. (let ((beg (progn (org-back-to-heading) (point)))
  16584. (end (save-excursion (org-end-of-subtree t t) (point))))
  16585. (outline-hide-subtree)
  16586. (outline-show-branches)
  16587. (org-hide-archived-subtrees beg end)))))
  16588. (defun org-delete-indentation (&optional arg)
  16589. "Join current line to previous and fix whitespace at join.
  16590. If previous line is a headline add to headline title. Otherwise
  16591. the function calls `delete-indentation'.
  16592. With a non-nil optional argument, join it to the following one."
  16593. (interactive "*P")
  16594. (if (save-excursion
  16595. (beginning-of-line (if arg 1 0))
  16596. (let ((case-fold-search nil))
  16597. (looking-at org-complex-heading-regexp)))
  16598. ;; At headline.
  16599. (let ((tags-column (when (match-beginning 5)
  16600. (save-excursion (goto-char (match-beginning 5))
  16601. (current-column))))
  16602. (string (concat " " (progn (when arg (forward-line 1))
  16603. (org-trim (delete-and-extract-region
  16604. (line-beginning-position)
  16605. (line-end-position)))))))
  16606. (unless (bobp) (delete-region (point) (1- (point))))
  16607. (goto-char (or (match-end 4)
  16608. (match-beginning 5)
  16609. (match-end 0)))
  16610. (skip-chars-backward " \t")
  16611. (save-excursion (insert string))
  16612. ;; Adjust alignment of tags.
  16613. (cond
  16614. ((not tags-column)) ;no tags
  16615. (org-auto-align-tags (org-align-tags))
  16616. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16617. (delete-indentation arg)))
  16618. (defun org-open-line (n)
  16619. "Insert a new row in tables, call `open-line' elsewhere.
  16620. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16621. As a special case, when a document starts with a table, allow to
  16622. call `open-line' on the very first character."
  16623. (interactive "*p")
  16624. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16625. (org-table-insert-row)
  16626. (open-line n)))
  16627. (defun org-return (&optional indent)
  16628. "Goto next table row or insert a newline.
  16629. Calls `org-table-next-row' or `newline', depending on context.
  16630. When optional INDENT argument is non-nil, call
  16631. `newline-and-indent' instead of `newline'.
  16632. When `org-return-follows-link' is non-nil and point is on
  16633. a timestamp or a link, call `org-open-at-point'. However, it
  16634. will not happen if point is in a table or on a \"dead\"
  16635. object (e.g., within a comment). In these case, you need to use
  16636. `org-open-at-point' directly."
  16637. (interactive)
  16638. (let ((context (if org-return-follows-link (org-element-context)
  16639. (org-element-at-point))))
  16640. (cond
  16641. ;; In a table, call `org-table-next-row'. However, before first
  16642. ;; column or after last one, split the table.
  16643. ((or (and (eq 'table (org-element-type context))
  16644. (not (eq 'table.el (org-element-property :type context)))
  16645. (>= (point) (org-element-property :contents-begin context))
  16646. (< (point) (org-element-property :contents-end context)))
  16647. (org-element-lineage context '(table-row table-cell) t))
  16648. (if (or (looking-at-p "[ \t]*$")
  16649. (save-excursion (skip-chars-backward " \t") (bolp)))
  16650. (insert "\n")
  16651. (org-table-justify-field-maybe)
  16652. (call-interactively #'org-table-next-row)))
  16653. ;; On a link or a timestamp, call `org-open-at-point' if
  16654. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16655. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16656. ((and org-return-follows-link
  16657. (or (and (eq 'link (org-element-type context))
  16658. ;; Ensure point is not on the white spaces after
  16659. ;; the link.
  16660. (let ((origin (point)))
  16661. (org-with-point-at (org-element-property :end context)
  16662. (skip-chars-backward " \t")
  16663. (> (point) origin))))
  16664. (org-in-regexp org-ts-regexp-both nil t)
  16665. (org-in-regexp org-tsr-regexp-both nil t)
  16666. (org-in-regexp org-link-any-re nil t)))
  16667. (call-interactively #'org-open-at-point))
  16668. ;; Insert newline in heading, but preserve tags.
  16669. ((and (not (bolp))
  16670. (let ((case-fold-search nil))
  16671. (org-match-line org-complex-heading-regexp)))
  16672. ;; At headline. Split line. However, if point is on keyword,
  16673. ;; priority cookie or tags, do not break any of them: add
  16674. ;; a newline after the headline instead.
  16675. (let ((tags-column (and (match-beginning 5)
  16676. (save-excursion (goto-char (match-beginning 5))
  16677. (current-column))))
  16678. (string
  16679. (when (and (match-end 4) (org-point-in-group (point) 4))
  16680. (delete-and-extract-region (point) (match-end 4)))))
  16681. ;; Adjust tag alignment.
  16682. (cond
  16683. ((not (and tags-column string)))
  16684. (org-auto-align-tags (org-align-tags))
  16685. (t (org--align-tags-here tags-column))) ;preserve tags column
  16686. (end-of-line)
  16687. (org-show-entry)
  16688. (if indent (newline-and-indent) (newline))
  16689. (when string (save-excursion (insert (org-trim string))))))
  16690. ;; In a list, make sure indenting keeps trailing text within.
  16691. ((and indent
  16692. (not (eolp))
  16693. (org-element-lineage context '(item)))
  16694. (let ((trailing-data
  16695. (delete-and-extract-region (point) (line-end-position))))
  16696. (newline-and-indent)
  16697. (save-excursion (insert trailing-data))))
  16698. (t
  16699. ;; Do not auto-fill when point is in an Org property drawer.
  16700. (let ((auto-fill-function (and (not (org-at-property-p))
  16701. auto-fill-function)))
  16702. (if indent
  16703. (newline-and-indent)
  16704. (newline)))))))
  16705. (defun org-return-indent ()
  16706. "Goto next table row or insert a newline and indent.
  16707. Calls `org-table-next-row' or `newline-and-indent', depending on
  16708. context. See the individual commands for more information."
  16709. (interactive)
  16710. (org-return t))
  16711. (defun org-ctrl-c-tab (&optional arg)
  16712. "Toggle columns width in a table, or show children.
  16713. Call `org-table-toggle-column-width' if point is in a table.
  16714. Otherwise, call `org-show-children'. ARG is the level to hide."
  16715. (interactive "p")
  16716. (if (org-at-table-p)
  16717. (call-interactively #'org-table-toggle-column-width)
  16718. (if (org-before-first-heading-p)
  16719. (progn
  16720. (org-flag-above-first-heading)
  16721. (outline-hide-sublevels (or arg 1))
  16722. (goto-char (point-min)))
  16723. (outline-hide-subtree)
  16724. (org-show-children arg))))
  16725. (defun org-ctrl-c-star ()
  16726. "Compute table, or change heading status of lines.
  16727. Calls `org-table-recalculate' or `org-toggle-heading',
  16728. depending on context."
  16729. (interactive)
  16730. (cond
  16731. ((org-at-table-p)
  16732. (call-interactively 'org-table-recalculate))
  16733. (t
  16734. ;; Convert all lines in region to list items
  16735. (call-interactively 'org-toggle-heading))))
  16736. (defun org-ctrl-c-minus ()
  16737. "Insert separator line in table or modify bullet status of line.
  16738. Also turns a plain line or a region of lines into list items.
  16739. Calls `org-table-insert-hline', `org-toggle-item', or
  16740. `org-cycle-list-bullet', depending on context."
  16741. (interactive)
  16742. (cond
  16743. ((org-at-table-p)
  16744. (call-interactively 'org-table-insert-hline))
  16745. ((org-region-active-p)
  16746. (call-interactively 'org-toggle-item))
  16747. ((org-in-item-p)
  16748. (call-interactively 'org-cycle-list-bullet))
  16749. (t
  16750. (call-interactively 'org-toggle-item))))
  16751. (defun org-toggle-heading (&optional nstars)
  16752. "Convert headings to normal text, or items or text to headings.
  16753. If there is no active region, only convert the current line.
  16754. With a `\\[universal-argument]' prefix, convert the whole list at
  16755. point into heading.
  16756. In a region:
  16757. - If the first non blank line is a headline, remove the stars
  16758. from all headlines in the region.
  16759. - If it is a normal line, turn each and every normal line (i.e.,
  16760. not an heading or an item) in the region into headings. If you
  16761. want to convert only the first line of this region, use one
  16762. universal prefix argument.
  16763. - If it is a plain list item, turn all plain list items into headings.
  16764. When converting a line into a heading, the number of stars is chosen
  16765. such that the lines become children of the current entry. However,
  16766. when a numeric prefix argument is given, its value determines the
  16767. number of stars to add."
  16768. (interactive "P")
  16769. (let ((skip-blanks
  16770. (function
  16771. ;; Return beginning of first non-blank line, starting from
  16772. ;; line at POS.
  16773. (lambda (pos)
  16774. (save-excursion
  16775. (goto-char pos)
  16776. (while (org-at-comment-p) (forward-line))
  16777. (skip-chars-forward " \r\t\n")
  16778. (point-at-bol)))))
  16779. beg end toggled)
  16780. ;; Determine boundaries of changes. If a universal prefix has
  16781. ;; been given, put the list in a region. If region ends at a bol,
  16782. ;; do not consider the last line to be in the region.
  16783. (when (and current-prefix-arg (org-at-item-p))
  16784. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16785. (org-mark-element))
  16786. (if (org-region-active-p)
  16787. (setq beg (funcall skip-blanks (region-beginning))
  16788. end (copy-marker (save-excursion
  16789. (goto-char (region-end))
  16790. (if (bolp) (point) (point-at-eol)))))
  16791. (setq beg (funcall skip-blanks (point-at-bol))
  16792. end (copy-marker (point-at-eol))))
  16793. ;; Ensure inline tasks don't count as headings.
  16794. (org-with-limited-levels
  16795. (save-excursion
  16796. (goto-char beg)
  16797. (cond
  16798. ;; Case 1. Started at an heading: de-star headings.
  16799. ((org-at-heading-p)
  16800. (while (< (point) end)
  16801. (when (org-at-heading-p t)
  16802. (looking-at org-outline-regexp) (replace-match "")
  16803. (setq toggled t))
  16804. (forward-line)))
  16805. ;; Case 2. Started at an item: change items into headlines.
  16806. ;; One star will be added by `org-list-to-subtree'.
  16807. ((org-at-item-p)
  16808. (while (< (point) end)
  16809. (when (org-at-item-p)
  16810. ;; Pay attention to cases when region ends before list.
  16811. (let* ((struct (org-list-struct))
  16812. (list-end
  16813. (min (org-list-get-bottom-point struct) (1+ end))))
  16814. (save-restriction
  16815. (narrow-to-region (point) list-end)
  16816. (insert (org-list-to-subtree
  16817. (org-list-to-lisp t)
  16818. (pcase (org-current-level)
  16819. (`nil 1)
  16820. (l (1+ (org-reduced-level l)))))
  16821. "\n")))
  16822. (setq toggled t))
  16823. (forward-line)))
  16824. ;; Case 3. Started at normal text: make every line an heading,
  16825. ;; skipping headlines and items.
  16826. (t (let* ((stars
  16827. (make-string
  16828. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16829. (add-stars
  16830. (cond (nstars "") ; stars from prefix only
  16831. ((equal stars "") "*") ; before first heading
  16832. (org-odd-levels-only "**") ; inside heading, odd
  16833. (t "*"))) ; inside heading, oddeven
  16834. (rpl (concat stars add-stars " "))
  16835. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16836. (while (< (point) (if (equal nstars '(4)) lend end))
  16837. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16838. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16839. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16840. (forward-line)))))))
  16841. (unless toggled (message "Cannot toggle heading from here"))))
  16842. (defun org-meta-return (&optional arg)
  16843. "Insert a new heading or wrap a region in a table.
  16844. Calls `org-insert-heading', `org-insert-item' or
  16845. `org-table-wrap-region', depending on context. When called with
  16846. an argument, unconditionally call `org-insert-heading'."
  16847. (interactive "P")
  16848. (org-check-before-invisible-edit 'insert)
  16849. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16850. (call-interactively (cond (arg #'org-insert-heading)
  16851. ((org-at-table-p) #'org-table-wrap-region)
  16852. ((org-in-item-p) #'org-insert-item)
  16853. (t #'org-insert-heading)))))
  16854. ;;; Menu entries
  16855. (defsubst org-in-subtree-not-table-p ()
  16856. "Are we in a subtree and not in a table?"
  16857. (and (not (org-before-first-heading-p))
  16858. (not (org-at-table-p))))
  16859. ;; Define the Org mode menus
  16860. (defun org-menu-define ()
  16861. "Define Org mode menus"
  16862. (easy-menu-define org-org-menu org-mode-map "Org menu"
  16863. `("Org"
  16864. ("Show/Hide"
  16865. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16866. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16867. ["Sparse Tree..." org-sparse-tree t]
  16868. ["Reveal Context" org-reveal t]
  16869. ["Show All" org-show-all t]
  16870. "--"
  16871. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16872. "--"
  16873. ["New Heading" org-insert-heading t]
  16874. ("Navigate Headings"
  16875. ["Up" outline-up-heading t]
  16876. ["Next" outline-next-visible-heading t]
  16877. ["Previous" outline-previous-visible-heading t]
  16878. ["Next Same Level" outline-forward-same-level t]
  16879. ["Previous Same Level" outline-backward-same-level t]
  16880. "--"
  16881. ["Jump" org-goto t])
  16882. ("Edit Structure"
  16883. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  16884. "--"
  16885. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16886. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16887. "--"
  16888. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16889. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16890. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16891. "--"
  16892. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16893. "--"
  16894. ["Copy visible text" org-copy-visible t]
  16895. "--"
  16896. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16897. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16898. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16899. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16900. "--"
  16901. ["Sort Region/Children" org-sort t]
  16902. "--"
  16903. ["Convert to odd levels" org-convert-to-odd-levels t]
  16904. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16905. ("Editing"
  16906. ["Emphasis..." org-emphasize t]
  16907. ["Edit Source Example" org-edit-special t]
  16908. "--"
  16909. ["Footnote new/jump" org-footnote-action t]
  16910. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16911. ("Archive"
  16912. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16913. "--"
  16914. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16915. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16916. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  16917. )
  16918. "--"
  16919. ("Hyperlinks"
  16920. ["Store Link (Global)" org-store-link t]
  16921. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16922. ["Insert Link" org-insert-link t]
  16923. ["Follow Link" org-open-at-point t]
  16924. "--"
  16925. ["Next link" org-next-link t]
  16926. ["Previous link" org-previous-link t]
  16927. "--"
  16928. ["Descriptive Links"
  16929. org-toggle-link-display
  16930. :style radio
  16931. :selected org-descriptive-links
  16932. ]
  16933. ["Literal Links"
  16934. org-toggle-link-display
  16935. :style radio
  16936. :selected (not org-descriptive-links)])
  16937. "--"
  16938. ("TODO Lists"
  16939. ["TODO/DONE/-" org-todo t]
  16940. ("Select keyword"
  16941. ["Next keyword" org-shiftright (org-at-heading-p)]
  16942. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16943. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16944. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16945. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16946. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16947. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16948. "--"
  16949. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16950. :selected org-enforce-todo-dependencies :style toggle :active t]
  16951. "Settings for tree at point"
  16952. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16953. :selected (org-entry-get nil "ORDERED")
  16954. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16955. ["Do Children parallel" org-toggle-ordered-property :style radio
  16956. :selected (not (org-entry-get nil "ORDERED"))
  16957. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16958. "--"
  16959. ["Set Priority" org-priority t]
  16960. ["Priority Up" org-shiftup t]
  16961. ["Priority Down" org-shiftdown t]
  16962. "--"
  16963. ["Get news from all feeds" org-feed-update-all t]
  16964. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16965. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16966. ("TAGS and Properties"
  16967. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16968. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16969. "--"
  16970. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16971. ["Column view of properties" org-columns t]
  16972. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16973. ("Dates and Scheduling"
  16974. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16975. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16976. ("Change Date"
  16977. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16978. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16979. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16980. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16981. ["Compute Time Range" org-evaluate-time-range t]
  16982. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16983. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16984. "--"
  16985. ["Custom time format" org-toggle-time-stamp-overlays
  16986. :style radio :selected org-display-custom-times]
  16987. "--"
  16988. ["Goto Calendar" org-goto-calendar t]
  16989. ["Date from Calendar" org-date-from-calendar t]
  16990. "--"
  16991. ["Start/Restart Timer" org-timer-start t]
  16992. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16993. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16994. ["Insert Timer String" org-timer t]
  16995. ["Insert Timer Item" org-timer-item t])
  16996. ("Logging work"
  16997. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16998. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16999. ["Clock out" org-clock-out t]
  17000. ["Clock cancel" org-clock-cancel t]
  17001. "--"
  17002. ["Mark as default task" org-clock-mark-default-task t]
  17003. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  17004. ["Goto running clock" org-clock-goto t]
  17005. "--"
  17006. ["Display times" org-clock-display t]
  17007. ["Create clock table" org-clock-report t]
  17008. "--"
  17009. ["Record DONE time"
  17010. (progn (setq org-log-done (not org-log-done))
  17011. (message "Switching to %s will %s record a timestamp"
  17012. (car org-done-keywords)
  17013. (if org-log-done "automatically" "not")))
  17014. :style toggle :selected org-log-done])
  17015. "--"
  17016. ["Agenda Command..." org-agenda t]
  17017. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  17018. ("File List for Agenda")
  17019. ("Special views current file"
  17020. ["TODO Tree" org-show-todo-tree t]
  17021. ["Check Deadlines" org-check-deadlines t]
  17022. ["Tags/Property tree" org-match-sparse-tree t])
  17023. "--"
  17024. ["Export/Publish..." org-export-dispatch t]
  17025. ("LaTeX"
  17026. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  17027. :style toggle :selected org-cdlatex-mode]
  17028. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  17029. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  17030. ["Modify math symbol" org-cdlatex-math-modify
  17031. (org-inside-LaTeX-fragment-p)]
  17032. ["Insert citation" org-reftex-citation t])
  17033. "--"
  17034. ,@(when (featurep 'org-mobile)
  17035. '(("MobileOrg"
  17036. ["Push Files and Views" org-mobile-push t]
  17037. ["Get Captured and Flagged" org-mobile-pull t]
  17038. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  17039. "--"
  17040. ["Setup" (customize-group 'org-mobile) t])
  17041. "--"))
  17042. ("Documentation"
  17043. ["Show Version" org-version t]
  17044. ["Info Documentation" org-info t]
  17045. ["Browse Org News" org-browse-news t])
  17046. ("Customize"
  17047. ["Browse Org Group" org-customize t]
  17048. "--"
  17049. ["Expand This Menu" org-create-customize-menu
  17050. (fboundp 'customize-menu-create)])
  17051. ["Send bug report" org-submit-bug-report t]
  17052. "--"
  17053. ("Refresh/Reload"
  17054. ["Refresh setup current buffer" org-mode-restart t]
  17055. ["Reload Org (after update)" org-reload t]
  17056. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  17057. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu"
  17058. '("Table"
  17059. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  17060. ["Next Field" org-cycle (org-at-table-p)]
  17061. ["Previous Field" org-shifttab (org-at-table-p)]
  17062. ["Next Row" org-return (org-at-table-p)]
  17063. "--"
  17064. ["Blank Field" org-table-blank-field (org-at-table-p)]
  17065. ["Edit Field" org-table-edit-field (org-at-table-p)]
  17066. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  17067. "--"
  17068. ("Column"
  17069. ["Move Column Left" org-metaleft (org-at-table-p)]
  17070. ["Move Column Right" org-metaright (org-at-table-p)]
  17071. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  17072. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  17073. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  17074. ("Row"
  17075. ["Move Row Up" org-metaup (org-at-table-p)]
  17076. ["Move Row Down" org-metadown (org-at-table-p)]
  17077. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  17078. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  17079. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  17080. "--"
  17081. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  17082. ("Rectangle"
  17083. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  17084. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  17085. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  17086. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  17087. "--"
  17088. ("Calculate"
  17089. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  17090. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  17091. ["Edit Formulas" org-edit-special (org-at-table-p)]
  17092. "--"
  17093. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  17094. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  17095. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  17096. "--"
  17097. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  17098. "--"
  17099. ["Sum Column/Rectangle" org-table-sum
  17100. (or (org-at-table-p) (org-region-active-p))]
  17101. ["Which Column?" org-table-current-column (org-at-table-p)])
  17102. ["Debug Formulas"
  17103. org-table-toggle-formula-debugger
  17104. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  17105. ["Show Col/Row Numbers"
  17106. org-table-toggle-coordinate-overlays
  17107. :style toggle
  17108. :selected (bound-and-true-p org-table-overlay-coordinates)]
  17109. "--"
  17110. ["Create" org-table-create (not (org-at-table-p))]
  17111. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  17112. ["Import from File" org-table-import (not (org-at-table-p))]
  17113. ["Export to File" org-table-export (org-at-table-p)]
  17114. "--"
  17115. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  17116. "--"
  17117. ("Plot"
  17118. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  17119. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"]))))
  17120. (defun org-info (&optional node)
  17121. "Read documentation for Org in the info system.
  17122. With optional NODE, go directly to that node."
  17123. (interactive)
  17124. (info (format "(org)%s" (or node ""))))
  17125. (defun org-browse-news ()
  17126. "Browse the news for the latest major release."
  17127. (interactive)
  17128. (browse-url "https://orgmode.org/Changes.html"))
  17129. ;;;###autoload
  17130. (defun org-submit-bug-report ()
  17131. "Submit a bug report on Org via mail.
  17132. Don't hesitate to report any problems or inaccurate documentation.
  17133. If you don't have setup sending mail from (X)Emacs, please copy the
  17134. output buffer into your mail program, as it gives us important
  17135. information about your Org version and configuration."
  17136. (interactive)
  17137. (require 'reporter)
  17138. (defvar reporter-prompt-for-summary-p)
  17139. (org-load-modules-maybe)
  17140. (org-require-autoloaded-modules)
  17141. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  17142. (reporter-submit-bug-report
  17143. "emacs-orgmode@gnu.org"
  17144. (org-version nil 'full)
  17145. (let (list)
  17146. (save-window-excursion
  17147. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  17148. (delete-other-windows)
  17149. (erase-buffer)
  17150. (insert "You are about to submit a bug report to the Org mailing list.
  17151. If your report is about Org installation, please read this section:
  17152. https://orgmode.org/org.html#Installation
  17153. Please read https://orgmode.org/org.html#Feedback on how to make
  17154. a good report, it will help Org contributors fixing your problem.
  17155. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  17156. if the issue you are about to raise has already been dealt with.
  17157. We also would like to add your full Org and Outline configuration
  17158. to the bug report. It will help us debugging the issue.
  17159. *HOWEVER*, some variables you have customized may contain private
  17160. information. The names of customers, colleagues, or friends, might
  17161. appear in the form of file names, tags, todo states or search strings.
  17162. If you answer \"yes\" to the prompt, you might want to check and remove
  17163. such private information before sending the email.")
  17164. (add-text-properties (point-min) (point-max) '(face org-warning))
  17165. (when (yes-or-no-p "Include your Org configuration ")
  17166. (mapatoms
  17167. (lambda (v)
  17168. (and (boundp v)
  17169. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  17170. (or (and (symbol-value v)
  17171. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  17172. (and
  17173. (get v 'custom-type) (get v 'standard-value)
  17174. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  17175. (push v list)))))
  17176. (kill-buffer (get-buffer "*Warn about privacy*"))
  17177. list))
  17178. nil nil
  17179. "Remember to cover the basics, that is, what you expected to happen and
  17180. what in fact did happen. You don't know how to make a good report? See
  17181. https://orgmode.org/manual/Feedback.html#Feedback
  17182. Your bug report will be posted to the Org mailing list.
  17183. ------------------------------------------------------------------------")
  17184. (save-excursion
  17185. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  17186. (replace-match "\\1Bug: \\3 [\\2]")))))
  17187. (defun org-install-agenda-files-menu ()
  17188. (let ((bl (buffer-list)))
  17189. (save-excursion
  17190. (while bl
  17191. (set-buffer (pop bl))
  17192. (when (derived-mode-p 'org-mode) (setq bl nil)))
  17193. (when (derived-mode-p 'org-mode)
  17194. (easy-menu-change
  17195. '("Org") "File List for Agenda"
  17196. (append
  17197. (list
  17198. ["Edit File List" (org-edit-agenda-file-list) t]
  17199. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  17200. ["Remove Current File from List" org-remove-file t]
  17201. ["Cycle through agenda files" org-cycle-agenda-files t]
  17202. ["Occur in all agenda files" org-occur-in-agenda-files t]
  17203. "--")
  17204. (mapcar 'org-file-menu-entry
  17205. ;; Prevent initialization from failing.
  17206. (ignore-errors (org-agenda-files t)))))))))
  17207. ;;;; Documentation
  17208. (defun org-require-autoloaded-modules ()
  17209. (interactive)
  17210. (mapc #'require
  17211. '(org-agenda org-archive org-attach org-clock org-colview org-id
  17212. org-table org-timer)))
  17213. ;;;###autoload
  17214. (defun org-reload (&optional uncompiled)
  17215. "Reload all Org Lisp files.
  17216. With prefix arg UNCOMPILED, load the uncompiled versions."
  17217. (interactive "P")
  17218. (require 'loadhist)
  17219. (let* ((org-dir (org-find-library-dir "org"))
  17220. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  17221. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  17222. (remove-re (format "\\`%s\\'"
  17223. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  17224. (feats (delete-dups
  17225. (mapcar 'file-name-sans-extension
  17226. (mapcar 'file-name-nondirectory
  17227. (delq nil
  17228. (mapcar 'feature-file
  17229. features))))))
  17230. (lfeat (append
  17231. (sort
  17232. (setq feats
  17233. (delq nil (mapcar
  17234. (lambda (f)
  17235. (if (and (string-match feature-re f)
  17236. (not (string-match remove-re f)))
  17237. f nil))
  17238. feats)))
  17239. 'string-lessp)
  17240. (list "org-version" "org")))
  17241. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  17242. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  17243. load-uncore load-misses)
  17244. (setq load-misses
  17245. (delq 't
  17246. (mapcar (lambda (f)
  17247. (or (org-load-noerror-mustsuffix (concat org-dir f))
  17248. (and (string= org-dir contrib-dir)
  17249. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  17250. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  17251. (add-to-list 'load-uncore f 'append)
  17252. 't)
  17253. f))
  17254. lfeat)))
  17255. (when load-uncore
  17256. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  17257. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  17258. (if load-misses
  17259. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  17260. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  17261. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  17262. ;;;###autoload
  17263. (defun org-customize ()
  17264. "Call the customize function with org as argument."
  17265. (interactive)
  17266. (org-load-modules-maybe)
  17267. (org-require-autoloaded-modules)
  17268. (customize-browse 'org))
  17269. (defun org-create-customize-menu ()
  17270. "Create a full customization menu for Org mode, insert it into the menu."
  17271. (interactive)
  17272. (org-load-modules-maybe)
  17273. (org-require-autoloaded-modules)
  17274. (if (fboundp 'customize-menu-create)
  17275. (progn
  17276. (easy-menu-change
  17277. '("Org") "Customize"
  17278. `(["Browse Org group" org-customize t]
  17279. "--"
  17280. ,(customize-menu-create 'org)
  17281. ["Set" Custom-set t]
  17282. ["Save" Custom-save t]
  17283. ["Reset to Current" Custom-reset-current t]
  17284. ["Reset to Saved" Custom-reset-saved t]
  17285. ["Reset to Standard Settings" Custom-reset-standard t]))
  17286. (message "\"Org\"-menu now contains full customization menu"))
  17287. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  17288. ;;;; Miscellaneous stuff
  17289. ;;; Generally useful functions
  17290. (defun org-in-clocktable-p ()
  17291. "Check if the cursor is in a clocktable."
  17292. (let ((pos (point)) start)
  17293. (save-excursion
  17294. (end-of-line 1)
  17295. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  17296. (setq start (match-beginning 0))
  17297. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  17298. (>= (match-end 0) pos)
  17299. start))))
  17300. (defun org-in-verbatim-emphasis ()
  17301. (save-match-data
  17302. (and (org-in-regexp org-verbatim-re 2)
  17303. (>= (point) (match-beginning 3))
  17304. (<= (point) (match-end 4)))))
  17305. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  17306. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  17307. (if (and marker (marker-buffer marker)
  17308. (buffer-live-p (marker-buffer marker)))
  17309. (progn
  17310. (pop-to-buffer-same-window (marker-buffer marker))
  17311. (when (or (> marker (point-max)) (< marker (point-min)))
  17312. (widen))
  17313. (goto-char marker)
  17314. (org-show-context 'org-goto))
  17315. (if bookmark
  17316. (bookmark-jump bookmark)
  17317. (error "Cannot find location"))))
  17318. (defun org-quote-csv-field (s)
  17319. "Quote field for inclusion in CSV material."
  17320. (if (string-match "[\",]" s)
  17321. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  17322. s))
  17323. (defun org-force-self-insert (N)
  17324. "Needed to enforce self-insert under remapping."
  17325. (interactive "p")
  17326. (self-insert-command N))
  17327. (defun org-quote-vert (s)
  17328. "Replace \"|\" with \"\\vert\"."
  17329. (while (string-match "|" s)
  17330. (setq s (replace-match "\\vert" t t s)))
  17331. s)
  17332. (defun org-uuidgen-p (s)
  17333. "Is S an ID created by UUIDGEN?"
  17334. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  17335. (defun org-in-src-block-p (&optional inside)
  17336. "Whether point is in a code source block.
  17337. When INSIDE is non-nil, don't consider we are within a source
  17338. block when point is at #+BEGIN_SRC or #+END_SRC."
  17339. (let ((case-fold-search t))
  17340. (or (and (eq (get-char-property (point) 'src-block) t))
  17341. (and (not inside)
  17342. (save-match-data
  17343. (save-excursion
  17344. (beginning-of-line)
  17345. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  17346. (defun org-context ()
  17347. "Return a list of contexts of the current cursor position.
  17348. If several contexts apply, all are returned.
  17349. Each context entry is a list with a symbol naming the context, and
  17350. two positions indicating start and end of the context. Possible
  17351. contexts are:
  17352. :headline anywhere in a headline
  17353. :headline-stars on the leading stars in a headline
  17354. :todo-keyword on a TODO keyword (including DONE) in a headline
  17355. :tags on the TAGS in a headline
  17356. :priority on the priority cookie in a headline
  17357. :item on the first line of a plain list item
  17358. :item-bullet on the bullet/number of a plain list item
  17359. :checkbox on the checkbox in a plain list item
  17360. :table in an Org table
  17361. :table-special on a special filed in a table
  17362. :table-table in a table.el table
  17363. :clocktable in a clocktable
  17364. :src-block in a source block
  17365. :link on a hyperlink
  17366. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  17367. :latex-fragment on a LaTeX fragment
  17368. :latex-preview on a LaTeX fragment with overlaid preview image
  17369. This function expects the position to be visible because it uses font-lock
  17370. faces as a help to recognize the following contexts: :table-special, :link,
  17371. and :keyword."
  17372. (let* ((f (get-text-property (point) 'face))
  17373. (faces (if (listp f) f (list f)))
  17374. (case-fold-search t)
  17375. (p (point)) clist o)
  17376. ;; First the large context
  17377. (cond
  17378. ((org-at-heading-p t)
  17379. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  17380. (when (progn
  17381. (beginning-of-line 1)
  17382. (looking-at org-todo-line-tags-regexp))
  17383. (push (org-point-in-group p 1 :headline-stars) clist)
  17384. (push (org-point-in-group p 2 :todo-keyword) clist)
  17385. (push (org-point-in-group p 4 :tags) clist))
  17386. (goto-char p)
  17387. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  17388. (when (looking-at "\\[#[A-Z0-9]\\]")
  17389. (push (org-point-in-group p 0 :priority) clist)))
  17390. ((org-at-item-p)
  17391. (push (org-point-in-group p 2 :item-bullet) clist)
  17392. (push (list :item (point-at-bol)
  17393. (save-excursion (org-end-of-item) (point)))
  17394. clist)
  17395. (and (org-at-item-checkbox-p)
  17396. (push (org-point-in-group p 0 :checkbox) clist)))
  17397. ((org-at-table-p)
  17398. (push (list :table (org-table-begin) (org-table-end)) clist)
  17399. (when (memq 'org-formula faces)
  17400. (push (list :table-special
  17401. (previous-single-property-change p 'face)
  17402. (next-single-property-change p 'face)) clist)))
  17403. ((org-at-table-p 'any)
  17404. (push (list :table-table) clist)))
  17405. (goto-char p)
  17406. (let ((case-fold-search t))
  17407. ;; New the "medium" contexts: clocktables, source blocks
  17408. (cond ((org-in-clocktable-p)
  17409. (push (list :clocktable
  17410. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  17411. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  17412. (match-beginning 1))
  17413. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  17414. (match-end 0))) clist))
  17415. ((org-in-src-block-p)
  17416. (push (list :src-block
  17417. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  17418. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  17419. (match-beginning 1))
  17420. (and (search-forward "#+END_SRC" nil t)
  17421. (match-beginning 0))) clist))))
  17422. (goto-char p)
  17423. ;; Now the small context
  17424. (cond
  17425. ((org-at-timestamp-p)
  17426. (push (org-point-in-group p 0 :timestamp) clist))
  17427. ((memq 'org-link faces)
  17428. (push (list :link
  17429. (previous-single-property-change p 'face)
  17430. (next-single-property-change p 'face)) clist))
  17431. ((memq 'org-special-keyword faces)
  17432. (push (list :keyword
  17433. (previous-single-property-change p 'face)
  17434. (next-single-property-change p 'face)) clist))
  17435. ((setq o (cl-some
  17436. (lambda (o)
  17437. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  17438. o))
  17439. (overlays-at (point))))
  17440. (push (list :latex-fragment
  17441. (overlay-start o) (overlay-end o)) clist)
  17442. (push (list :latex-preview
  17443. (overlay-start o) (overlay-end o)) clist))
  17444. ((org-inside-LaTeX-fragment-p)
  17445. ;; FIXME: positions wrong.
  17446. (push (list :latex-fragment (point) (point)) clist)))
  17447. (setq clist (nreverse (delq nil clist)))
  17448. clist))
  17449. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  17450. "Non-nil when point is between matches of START-RE and END-RE.
  17451. Also return a non-nil value when point is on one of the matches.
  17452. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  17453. buffer positions. Default values are the positions of headlines
  17454. surrounding the point.
  17455. The functions returns a cons cell whose car (resp. cdr) is the
  17456. position before START-RE (resp. after END-RE)."
  17457. (save-match-data
  17458. (let ((pos (point))
  17459. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  17460. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  17461. beg end)
  17462. (save-excursion
  17463. ;; Point is on a block when on START-RE or if START-RE can be
  17464. ;; found before it...
  17465. (and (or (org-in-regexp start-re)
  17466. (re-search-backward start-re limit-up t))
  17467. (setq beg (match-beginning 0))
  17468. ;; ... and END-RE after it...
  17469. (goto-char (match-end 0))
  17470. (re-search-forward end-re limit-down t)
  17471. (> (setq end (match-end 0)) pos)
  17472. ;; ... without another START-RE in-between.
  17473. (goto-char (match-beginning 0))
  17474. (not (re-search-backward start-re (1+ beg) t))
  17475. ;; Return value.
  17476. (cons beg end))))))
  17477. (defun org-in-block-p (names)
  17478. "Non-nil when point belongs to a block whose name belongs to NAMES.
  17479. NAMES is a list of strings containing names of blocks.
  17480. Return first block name matched, or nil. Beware that in case of
  17481. nested blocks, the returned name may not belong to the closest
  17482. block from point."
  17483. (save-match-data
  17484. (catch 'exit
  17485. (let ((case-fold-search t)
  17486. (lim-up (save-excursion (outline-previous-heading)))
  17487. (lim-down (save-excursion (outline-next-heading))))
  17488. (dolist (name names)
  17489. (let ((n (regexp-quote name)))
  17490. (when (org-between-regexps-p
  17491. (concat "^[ \t]*#\\+begin_" n)
  17492. (concat "^[ \t]*#\\+end_" n)
  17493. lim-up lim-down)
  17494. (throw 'exit n)))))
  17495. nil)))
  17496. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  17497. "Call `multi-occur' with buffers for all agenda files."
  17498. (interactive "sOrg-files matching: ")
  17499. (let* ((files (org-agenda-files))
  17500. (tnames (mapcar #'file-truename files))
  17501. (extra org-agenda-text-search-extra-files))
  17502. (when (eq (car extra) 'agenda-archives)
  17503. (setq extra (cdr extra))
  17504. (setq files (org-add-archive-files files)))
  17505. (dolist (f extra)
  17506. (unless (member (file-truename f) tnames)
  17507. (unless (member f files) (setq files (append files (list f))))
  17508. (setq tnames (append tnames (list (file-truename f))))))
  17509. (multi-occur
  17510. (mapcar (lambda (x)
  17511. (with-current-buffer
  17512. ;; FIXME: Why not just (find-file-noselect x)?
  17513. ;; Is it to avoid the "revert buffer" prompt?
  17514. (or (get-file-buffer x) (find-file-noselect x))
  17515. (widen)
  17516. (current-buffer)))
  17517. files)
  17518. regexp)))
  17519. (add-hook 'occur-mode-find-occurrence-hook
  17520. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17521. (defun org-occur-link-in-agenda-files ()
  17522. "Create a link and search for it in the agendas.
  17523. The link is not stored in `org-stored-links', it is just created
  17524. for the search purpose."
  17525. (interactive)
  17526. (let ((link (condition-case nil
  17527. (org-store-link nil)
  17528. (error "Unable to create a link to here"))))
  17529. (org-occur-in-agenda-files (regexp-quote link))))
  17530. (defun org-back-over-empty-lines ()
  17531. "Move backwards over whitespace, to the beginning of the first empty line.
  17532. Returns the number of empty lines passed."
  17533. (let ((pos (point)))
  17534. (if (cdr (assq 'heading org-blank-before-new-entry))
  17535. (skip-chars-backward " \t\n\r")
  17536. (unless (eobp)
  17537. (forward-line -1)))
  17538. (beginning-of-line 2)
  17539. (goto-char (min (point) pos))
  17540. (count-lines (point) pos)))
  17541. ;;; TODO: Only called once, from ox-odt which should probably use
  17542. ;;; org-export-inline-image-p or something.
  17543. (defun org-file-image-p (file)
  17544. "Return non-nil if FILE is an image."
  17545. (save-match-data
  17546. (string-match (image-file-name-regexp) file)))
  17547. (defun org-get-cursor-date (&optional with-time)
  17548. "Return the date at cursor in as a time.
  17549. This works in the calendar and in the agenda, anywhere else it just
  17550. returns the current time.
  17551. If WITH-TIME is non-nil, returns the time of the event at point (in
  17552. the agenda) or the current time of the day; otherwise returns the
  17553. earliest time on the cursor date that Org treats as that date
  17554. (bearing in mind `org-extend-today-until')."
  17555. (let (date day defd tp hod mod)
  17556. (when with-time
  17557. (setq tp (get-text-property (point) 'time))
  17558. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  17559. (setq hod (string-to-number (match-string 1 tp))
  17560. mod (string-to-number (match-string 2 tp))))
  17561. (or tp (let ((now (decode-time)))
  17562. (setq hod (nth 2 now)
  17563. mod (nth 1 now)))))
  17564. (cond
  17565. ((eq major-mode 'calendar-mode)
  17566. (setq date (calendar-cursor-to-date)
  17567. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17568. (nth 1 date) (nth 0 date) (nth 2 date))))
  17569. ((eq major-mode 'org-agenda-mode)
  17570. (setq day (get-text-property (point) 'day))
  17571. (when day
  17572. (setq date (calendar-gregorian-from-absolute day)
  17573. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17574. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17575. (or defd (current-time))))
  17576. (defun org-mark-subtree (&optional up)
  17577. "Mark the current subtree.
  17578. This puts point at the start of the current subtree, and mark at
  17579. the end. If a numeric prefix UP is given, move up into the
  17580. hierarchy of headlines by UP levels before marking the subtree."
  17581. (interactive "P")
  17582. (org-with-limited-levels
  17583. (cond ((org-at-heading-p) (beginning-of-line))
  17584. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17585. (t (outline-previous-visible-heading 1))))
  17586. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17587. (if (called-interactively-p 'any)
  17588. (call-interactively 'org-mark-element)
  17589. (org-mark-element)))
  17590. ;;; Indentation
  17591. (defvar org-element-greater-elements)
  17592. (defun org--get-expected-indentation (element contentsp)
  17593. "Expected indentation column for current line, according to ELEMENT.
  17594. ELEMENT is an element containing point. CONTENTSP is non-nil
  17595. when indentation is to be computed according to contents of
  17596. ELEMENT."
  17597. (let ((type (org-element-type element))
  17598. (start (org-element-property :begin element))
  17599. (post-affiliated (org-element-property :post-affiliated element)))
  17600. (org-with-wide-buffer
  17601. (cond
  17602. (contentsp
  17603. (cl-case type
  17604. ((diary-sexp footnote-definition) 0)
  17605. ((headline inlinetask nil)
  17606. (if (not org-adapt-indentation) 0
  17607. (let ((level (org-current-level)))
  17608. (if level (1+ level) 0))))
  17609. ((item plain-list) (org-list-item-body-column post-affiliated))
  17610. (t
  17611. (goto-char start)
  17612. (current-indentation))))
  17613. ((memq type '(headline inlinetask nil))
  17614. (if (org-match-line "[ \t]*$")
  17615. (org--get-expected-indentation element t)
  17616. 0))
  17617. ((memq type '(diary-sexp footnote-definition)) 0)
  17618. ;; First paragraph of a footnote definition or an item.
  17619. ;; Indent like parent.
  17620. ((< (line-beginning-position) start)
  17621. (org--get-expected-indentation
  17622. (org-element-property :parent element) t))
  17623. ;; At first line: indent according to previous sibling, if any,
  17624. ;; ignoring footnote definitions and inline tasks, or parent's
  17625. ;; contents.
  17626. ((= (line-beginning-position) start)
  17627. (catch 'exit
  17628. (while t
  17629. (if (= (point-min) start) (throw 'exit 0)
  17630. (goto-char (1- start))
  17631. (let* ((previous (org-element-at-point))
  17632. (parent previous))
  17633. (while (and parent (<= (org-element-property :end parent) start))
  17634. (setq previous parent
  17635. parent (org-element-property :parent parent)))
  17636. (cond
  17637. ((not previous) (throw 'exit 0))
  17638. ((> (org-element-property :end previous) start)
  17639. (throw 'exit (org--get-expected-indentation previous t)))
  17640. ((memq (org-element-type previous)
  17641. '(footnote-definition inlinetask))
  17642. (setq start (org-element-property :begin previous)))
  17643. (t (goto-char (org-element-property :begin previous))
  17644. (throw 'exit
  17645. (if (bolp) (current-indentation)
  17646. ;; At first paragraph in an item or
  17647. ;; a footnote definition.
  17648. (org--get-expected-indentation
  17649. (org-element-property :parent previous) t))))))))))
  17650. ;; Otherwise, move to the first non-blank line above.
  17651. (t
  17652. (beginning-of-line)
  17653. (let ((pos (point)))
  17654. (skip-chars-backward " \r\t\n")
  17655. (cond
  17656. ;; Two blank lines end a footnote definition or a plain
  17657. ;; list. When we indent an empty line after them, the
  17658. ;; containing list or footnote definition is over, so it
  17659. ;; qualifies as a previous sibling. Therefore, we indent
  17660. ;; like its first line.
  17661. ((and (memq type '(footnote-definition plain-list))
  17662. (> (count-lines (point) pos) 2))
  17663. (goto-char start)
  17664. (current-indentation))
  17665. ;; Line above is the first one of a paragraph at the
  17666. ;; beginning of an item or a footnote definition. Indent
  17667. ;; like parent.
  17668. ((< (line-beginning-position) start)
  17669. (org--get-expected-indentation
  17670. (org-element-property :parent element) t))
  17671. ;; Line above is the beginning of an element, i.e., point
  17672. ;; was originally on the blank lines between element's start
  17673. ;; and contents.
  17674. ((= (line-beginning-position) post-affiliated)
  17675. (org--get-expected-indentation element t))
  17676. ;; POS is after contents in a greater element. Indent like
  17677. ;; the beginning of the element.
  17678. ((and (memq type org-element-greater-elements)
  17679. (let ((cend (org-element-property :contents-end element)))
  17680. (and cend (<= cend pos))))
  17681. ;; As a special case, if point is at the end of a footnote
  17682. ;; definition or an item, indent like the very last element
  17683. ;; within. If that last element is an item, indent like
  17684. ;; its contents.
  17685. (if (memq type '(footnote-definition item plain-list))
  17686. (let ((last (org-element-at-point)))
  17687. (goto-char pos)
  17688. (org--get-expected-indentation
  17689. last (eq (org-element-type last) 'item)))
  17690. (goto-char start)
  17691. (current-indentation)))
  17692. ;; In any other case, indent like the current line.
  17693. (t (current-indentation)))))))))
  17694. (defun org--align-node-property ()
  17695. "Align node property at point.
  17696. Alignment is done according to `org-property-format', which see."
  17697. (when (save-excursion
  17698. (beginning-of-line)
  17699. (looking-at org-property-re))
  17700. (replace-match
  17701. (concat (match-string 4)
  17702. (org-trim
  17703. (format org-property-format (match-string 1) (match-string 3))))
  17704. t t)))
  17705. (defun org-indent-line ()
  17706. "Indent line depending on context.
  17707. Indentation is done according to the following rules:
  17708. - Footnote definitions, diary sexps, headlines and inline tasks
  17709. have to start at column 0.
  17710. - On the very first line of an element, consider, in order, the
  17711. next rules until one matches:
  17712. 1. If there's a sibling element before, ignoring footnote
  17713. definitions and inline tasks, indent like its first line.
  17714. 2. If element has a parent, indent like its contents. More
  17715. precisely, if parent is an item, indent after the bullet.
  17716. Else, indent like parent's first line.
  17717. 3. Otherwise, indent relatively to current level, if
  17718. `org-adapt-indentation' is non-nil, or to left margin.
  17719. - On a blank line at the end of an element, indent according to
  17720. the type of the element. More precisely
  17721. 1. If element is a plain list, an item, or a footnote
  17722. definition, indent like the very last element within.
  17723. 2. If element is a paragraph, indent like its last non blank
  17724. line.
  17725. 3. Otherwise, indent like its very first line.
  17726. - In the code part of a source block, use language major mode
  17727. to indent current line if `org-src-tab-acts-natively' is
  17728. non-nil. If it is nil, do nothing.
  17729. - Otherwise, indent like the first non-blank line above.
  17730. The function doesn't indent an item as it could break the whole
  17731. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17732. `\\[org-shiftmetaright]'.
  17733. Also align node properties according to `org-property-format'."
  17734. (interactive)
  17735. (cond
  17736. ((org-at-heading-p) 'noindent)
  17737. (t
  17738. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17739. (type (org-element-type element)))
  17740. (cond ((and (memq type '(plain-list item))
  17741. (= (line-beginning-position)
  17742. (org-element-property :post-affiliated element)))
  17743. 'noindent)
  17744. ((and (eq type 'latex-environment)
  17745. (>= (point) (org-element-property :post-affiliated element))
  17746. (< (point) (org-with-wide-buffer
  17747. (goto-char (org-element-property :end element))
  17748. (skip-chars-backward " \r\t\n")
  17749. (line-beginning-position 2))))
  17750. 'noindent)
  17751. ((and (eq type 'src-block)
  17752. org-src-tab-acts-natively
  17753. (> (line-beginning-position)
  17754. (org-element-property :post-affiliated element))
  17755. (< (line-beginning-position)
  17756. (org-with-wide-buffer
  17757. (goto-char (org-element-property :end element))
  17758. (skip-chars-backward " \r\t\n")
  17759. (line-beginning-position))))
  17760. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17761. (t
  17762. (let ((column (org--get-expected-indentation element nil)))
  17763. ;; Preserve current column.
  17764. (if (<= (current-column) (current-indentation))
  17765. (indent-line-to column)
  17766. (save-excursion (indent-line-to column))))
  17767. ;; Align node property. Also preserve current column.
  17768. (when (eq type 'node-property)
  17769. (let ((column (current-column)))
  17770. (org--align-node-property)
  17771. (org-move-to-column column)))))))))
  17772. (defun org-indent-region (start end)
  17773. "Indent each non-blank line in the region.
  17774. Called from a program, START and END specify the region to
  17775. indent. The function will not indent contents of example blocks,
  17776. verse blocks and export blocks as leading white spaces are
  17777. assumed to be significant there."
  17778. (interactive "r")
  17779. (save-window-excursion
  17780. (goto-char start)
  17781. (skip-chars-forward " \r\t\n")
  17782. (unless (eobp) (beginning-of-line))
  17783. (let ((indent-to
  17784. (lambda (ind pos)
  17785. ;; Set IND as indentation for all lines between point and
  17786. ;; POS. Blank lines are ignored. Leave point after POS
  17787. ;; once done.
  17788. (let ((limit (copy-marker pos)))
  17789. (while (< (point) limit)
  17790. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17791. (forward-line))
  17792. (set-marker limit nil))))
  17793. (end (copy-marker end)))
  17794. (while (< (point) end)
  17795. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17796. (let* ((element (org-element-at-point))
  17797. (type (org-element-type element))
  17798. (element-end (copy-marker (org-element-property :end element)))
  17799. (ind (org--get-expected-indentation element nil)))
  17800. (cond
  17801. ;; Element indented as a single block. Example blocks
  17802. ;; preserving indentation are a special case since the
  17803. ;; "contents" must not be indented whereas the block
  17804. ;; boundaries can.
  17805. ((or (memq type '(export-block latex-environment))
  17806. (and (eq type 'example-block)
  17807. (not
  17808. (or org-src-preserve-indentation
  17809. (org-element-property :preserve-indent element)))))
  17810. (let ((offset (- ind (current-indentation))))
  17811. (unless (zerop offset)
  17812. (indent-rigidly (org-element-property :begin element)
  17813. (org-element-property :end element)
  17814. offset)))
  17815. (goto-char element-end))
  17816. ;; Elements indented line wise. Be sure to exclude
  17817. ;; example blocks (preserving indentation) and source
  17818. ;; blocks from this category as they are treated
  17819. ;; specially later.
  17820. ((or (memq type '(paragraph table table-row))
  17821. (not (or (org-element-property :contents-begin element)
  17822. (memq type '(example-block src-block)))))
  17823. (when (eq type 'node-property)
  17824. (org--align-node-property)
  17825. (beginning-of-line))
  17826. (funcall indent-to ind (min element-end end)))
  17827. ;; Elements consisting of three parts: before the
  17828. ;; contents, the contents, and after the contents. The
  17829. ;; contents are treated specially, according to the
  17830. ;; element type, or not indented at all. Other parts are
  17831. ;; indented as a single block.
  17832. (t
  17833. (let* ((post (copy-marker
  17834. (org-element-property :post-affiliated element)))
  17835. (cbeg
  17836. (copy-marker
  17837. (cond
  17838. ((not (org-element-property :contents-begin element))
  17839. ;; Fake contents for source blocks.
  17840. (org-with-wide-buffer
  17841. (goto-char post)
  17842. (line-beginning-position 2)))
  17843. ((memq type '(footnote-definition item plain-list))
  17844. ;; Contents in these elements could start on
  17845. ;; the same line as the beginning of the
  17846. ;; element. Make sure we start indenting
  17847. ;; from the second line.
  17848. (org-with-wide-buffer
  17849. (goto-char post)
  17850. (end-of-line)
  17851. (skip-chars-forward " \r\t\n")
  17852. (if (eobp) (point) (line-beginning-position))))
  17853. (t (org-element-property :contents-begin element)))))
  17854. (cend (copy-marker
  17855. (or (org-element-property :contents-end element)
  17856. ;; Fake contents for source blocks.
  17857. (org-with-wide-buffer
  17858. (goto-char element-end)
  17859. (skip-chars-backward " \r\t\n")
  17860. (line-beginning-position)))
  17861. t)))
  17862. ;; Do not change items indentation individually as it
  17863. ;; might break the list as a whole. On the other
  17864. ;; hand, when at a plain list, indent it as a whole.
  17865. (cond ((eq type 'plain-list)
  17866. (let ((offset (- ind (current-indentation))))
  17867. (unless (zerop offset)
  17868. (indent-rigidly (org-element-property :begin element)
  17869. (org-element-property :end element)
  17870. offset))
  17871. (goto-char cbeg)))
  17872. ((eq type 'item) (goto-char cbeg))
  17873. (t (funcall indent-to ind (min cbeg end))))
  17874. (when (< (point) end)
  17875. (cl-case type
  17876. ((example-block verse-block))
  17877. (src-block
  17878. ;; In a source block, indent source code
  17879. ;; according to language major mode, but only if
  17880. ;; `org-src-tab-acts-natively' is non-nil.
  17881. (when (and (< (point) end) org-src-tab-acts-natively)
  17882. (ignore-errors
  17883. (org-babel-do-in-edit-buffer
  17884. (indent-region (point-min) (point-max))))))
  17885. (t (org-indent-region (point) (min cend end))))
  17886. (goto-char (min cend end))
  17887. (when (< (point) end)
  17888. (funcall indent-to ind (min element-end end))))
  17889. (set-marker post nil)
  17890. (set-marker cbeg nil)
  17891. (set-marker cend nil))))
  17892. (set-marker element-end nil))))
  17893. (set-marker end nil))))
  17894. (defun org-indent-drawer ()
  17895. "Indent the drawer at point."
  17896. (interactive)
  17897. (unless (save-excursion
  17898. (beginning-of-line)
  17899. (looking-at-p org-drawer-regexp))
  17900. (user-error "Not at a drawer"))
  17901. (let ((element (org-element-at-point)))
  17902. (unless (memq (org-element-type element) '(drawer property-drawer))
  17903. (user-error "Not at a drawer"))
  17904. (org-with-wide-buffer
  17905. (org-indent-region (org-element-property :begin element)
  17906. (org-element-property :end element))))
  17907. (message "Drawer at point indented"))
  17908. (defun org-indent-block ()
  17909. "Indent the block at point."
  17910. (interactive)
  17911. (unless (save-excursion
  17912. (beginning-of-line)
  17913. (let ((case-fold-search t))
  17914. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17915. (user-error "Not at a block"))
  17916. (let ((element (org-element-at-point)))
  17917. (unless (memq (org-element-type element)
  17918. '(comment-block center-block dynamic-block example-block
  17919. export-block quote-block special-block
  17920. src-block verse-block))
  17921. (user-error "Not at a block"))
  17922. (org-with-wide-buffer
  17923. (org-indent-region (org-element-property :begin element)
  17924. (org-element-property :end element))))
  17925. (message "Block at point indented"))
  17926. ;;; Filling
  17927. ;; We use our own fill-paragraph and auto-fill functions.
  17928. ;; `org-fill-paragraph' relies on adaptive filling and context
  17929. ;; checking. Appropriate `fill-prefix' is computed with
  17930. ;; `org-adaptive-fill-function'.
  17931. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17932. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17933. ;; `org-adaptive-fill-function' value. Internally,
  17934. ;; `org-comment-line-break-function' breaks the line.
  17935. ;; `org-setup-filling' installs filling and auto-filling related
  17936. ;; variables during `org-mode' initialization.
  17937. (defun org-setup-filling ()
  17938. (require 'org-element)
  17939. ;; Prevent auto-fill from inserting unwanted new items.
  17940. (when (boundp 'fill-nobreak-predicate)
  17941. (setq-local
  17942. fill-nobreak-predicate
  17943. (org-uniquify
  17944. (append fill-nobreak-predicate
  17945. '(org-fill-line-break-nobreak-p
  17946. org-fill-n-macro-as-item-nobreak-p
  17947. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17948. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17949. (setq-local paragraph-start paragraph-ending)
  17950. (setq-local paragraph-separate paragraph-ending))
  17951. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17952. (setq-local auto-fill-inhibit-regexp nil)
  17953. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17954. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17955. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17956. (defun org-fill-line-break-nobreak-p ()
  17957. "Non-nil when a new line at point would create an Org line break."
  17958. (save-excursion
  17959. (skip-chars-backward " \t")
  17960. (skip-chars-backward "\\\\")
  17961. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17962. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17963. "Non-nil when a new line at point would split a timestamp."
  17964. (and (org-at-timestamp-p 'lax)
  17965. (not (looking-at org-ts-regexp-both))))
  17966. (defun org-fill-n-macro-as-item-nobreak-p ()
  17967. "Non-nil when a new line at point would create a new list."
  17968. ;; During export, a "n" macro followed by a dot or a closing
  17969. ;; parenthesis can end up being parsed as a new list item.
  17970. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17971. (defun org-adaptive-fill-function ()
  17972. "Compute a fill prefix for the current line.
  17973. Return fill prefix, as a string, or nil if current line isn't
  17974. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17975. matches in paragraphs or comments, use it."
  17976. (org-with-wide-buffer
  17977. (unless (org-at-heading-p)
  17978. (let* ((p (line-beginning-position))
  17979. (element (save-excursion
  17980. (beginning-of-line)
  17981. (org-element-at-point)))
  17982. (type (org-element-type element))
  17983. (post-affiliated (org-element-property :post-affiliated element)))
  17984. (unless (< p post-affiliated)
  17985. (cl-case type
  17986. (comment
  17987. (save-excursion
  17988. (beginning-of-line)
  17989. (looking-at "[ \t]*")
  17990. (concat (match-string 0) "# ")))
  17991. (footnote-definition "")
  17992. ((item plain-list)
  17993. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17994. (paragraph
  17995. ;; Fill prefix is usually the same as the current line,
  17996. ;; unless the paragraph is at the beginning of an item.
  17997. (let ((parent (org-element-property :parent element)))
  17998. (save-excursion
  17999. (beginning-of-line)
  18000. (cond ((eq (org-element-type parent) 'item)
  18001. (make-string (org-list-item-body-column
  18002. (org-element-property :begin parent))
  18003. ?\s))
  18004. ((and adaptive-fill-regexp
  18005. ;; Locally disable
  18006. ;; `adaptive-fill-function' to let
  18007. ;; `fill-context-prefix' handle
  18008. ;; `adaptive-fill-regexp' variable.
  18009. (let (adaptive-fill-function)
  18010. (fill-context-prefix
  18011. post-affiliated
  18012. (org-element-property :end element)))))
  18013. ((looking-at "[ \t]+") (match-string 0))
  18014. (t "")))))
  18015. (comment-block
  18016. ;; Only fill contents if P is within block boundaries.
  18017. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  18018. (forward-line)
  18019. (point)))
  18020. (cend (save-excursion
  18021. (goto-char (org-element-property :end element))
  18022. (skip-chars-backward " \r\t\n")
  18023. (line-beginning-position))))
  18024. (when (and (>= p cbeg) (< p cend))
  18025. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  18026. (match-string 0)
  18027. ""))))))))))
  18028. (defun org-fill-element (&optional justify)
  18029. "Fill element at point, when applicable.
  18030. This function only applies to comment blocks, comments, example
  18031. blocks and paragraphs. Also, as a special case, re-align table
  18032. when point is at one.
  18033. If JUSTIFY is non-nil (interactively, with prefix argument),
  18034. justify as well. If `sentence-end-double-space' is non-nil, then
  18035. period followed by one space does not end a sentence, so don't
  18036. break a line there. The variable `fill-column' controls the
  18037. width for filling.
  18038. For convenience, when point is at a plain list, an item or
  18039. a footnote definition, try to fill the first paragraph within."
  18040. (with-syntax-table org-mode-transpose-word-syntax-table
  18041. ;; Move to end of line in order to get the first paragraph within
  18042. ;; a plain list or a footnote definition.
  18043. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  18044. ;; First check if point is in a blank line at the beginning of
  18045. ;; the buffer. In that case, ignore filling.
  18046. (cl-case (org-element-type element)
  18047. ;; Use major mode filling function is source blocks.
  18048. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  18049. ;; Align Org tables, leave table.el tables as-is.
  18050. (table-row (org-table-align) t)
  18051. (table
  18052. (when (eq (org-element-property :type element) 'org)
  18053. (save-excursion
  18054. (goto-char (org-element-property :post-affiliated element))
  18055. (org-table-align)))
  18056. t)
  18057. (paragraph
  18058. ;; Paragraphs may contain `line-break' type objects.
  18059. (let ((beg (max (point-min)
  18060. (org-element-property :contents-begin element)))
  18061. (end (min (point-max)
  18062. (org-element-property :contents-end element))))
  18063. ;; Do nothing if point is at an affiliated keyword.
  18064. (if (< (line-end-position) beg) t
  18065. ;; Fill paragraph, taking line breaks into account.
  18066. (save-excursion
  18067. (goto-char beg)
  18068. (let ((cuts (list beg)))
  18069. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  18070. (when (eq 'line-break
  18071. (org-element-type
  18072. (save-excursion (backward-char)
  18073. (org-element-context))))
  18074. (push (point) cuts)))
  18075. (dolist (c (delq end cuts))
  18076. (fill-region-as-paragraph c end justify)
  18077. (setq end c))))
  18078. t)))
  18079. ;; Contents of `comment-block' type elements should be
  18080. ;; filled as plain text, but only if point is within block
  18081. ;; markers.
  18082. (comment-block
  18083. (let* ((case-fold-search t)
  18084. (beg (save-excursion
  18085. (goto-char (org-element-property :begin element))
  18086. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  18087. (forward-line)
  18088. (point)))
  18089. (end (save-excursion
  18090. (goto-char (org-element-property :end element))
  18091. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  18092. (line-beginning-position))))
  18093. (if (or (< (point) beg) (> (point) end)) t
  18094. (fill-region-as-paragraph
  18095. (save-excursion (end-of-line)
  18096. (re-search-backward "^[ \t]*$" beg 'move)
  18097. (line-beginning-position))
  18098. (save-excursion (beginning-of-line)
  18099. (re-search-forward "^[ \t]*$" end 'move)
  18100. (line-beginning-position))
  18101. justify))))
  18102. ;; Fill comments.
  18103. (comment
  18104. (let ((begin (org-element-property :post-affiliated element))
  18105. (end (org-element-property :end element)))
  18106. (when (and (>= (point) begin) (<= (point) end))
  18107. (let ((begin (save-excursion
  18108. (end-of-line)
  18109. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  18110. (progn (forward-line) (point))
  18111. begin)))
  18112. (end (save-excursion
  18113. (end-of-line)
  18114. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  18115. (1- (line-beginning-position))
  18116. (skip-chars-backward " \r\t\n")
  18117. (line-end-position)))))
  18118. ;; Do not fill comments when at a blank line.
  18119. (when (> end begin)
  18120. (let ((fill-prefix
  18121. (save-excursion
  18122. (beginning-of-line)
  18123. (looking-at "[ \t]*#")
  18124. (let ((comment-prefix (match-string 0)))
  18125. (goto-char (match-end 0))
  18126. (if (looking-at adaptive-fill-regexp)
  18127. (concat comment-prefix (match-string 0))
  18128. (concat comment-prefix " "))))))
  18129. (save-excursion
  18130. (fill-region-as-paragraph begin end justify))))))
  18131. t))
  18132. ;; Ignore every other element.
  18133. (otherwise t)))))
  18134. (defun org-fill-paragraph (&optional justify region)
  18135. "Fill element at point, when applicable.
  18136. This function only applies to comment blocks, comments, example
  18137. blocks and paragraphs. Also, as a special case, re-align table
  18138. when point is at one.
  18139. For convenience, when point is at a plain list, an item or
  18140. a footnote definition, try to fill the first paragraph within.
  18141. If JUSTIFY is non-nil (interactively, with prefix argument),
  18142. justify as well. If `sentence-end-double-space' is non-nil, then
  18143. period followed by one space does not end a sentence, so don't
  18144. break a line there. The variable `fill-column' controls the
  18145. width for filling.
  18146. The REGION argument is non-nil if called interactively; in that
  18147. case, if Transient Mark mode is enabled and the mark is active,
  18148. fill each of the elements in the active region, instead of just
  18149. filling the current element."
  18150. (interactive (progn
  18151. (barf-if-buffer-read-only)
  18152. (list (when current-prefix-arg 'full) t)))
  18153. (let ((hash (and (not (buffer-modified-p))
  18154. (org-buffer-hash))))
  18155. (cond
  18156. ((and region transient-mark-mode mark-active
  18157. (not (eq (region-beginning) (region-end))))
  18158. (let ((origin (point-marker))
  18159. (start (region-beginning)))
  18160. (unwind-protect
  18161. (progn
  18162. (goto-char (region-end))
  18163. (while (> (point) start)
  18164. (org-backward-paragraph)
  18165. (org-fill-element justify)))
  18166. (goto-char origin)
  18167. (set-marker origin nil))))
  18168. (t (org-fill-element justify)))
  18169. ;; If we didn't change anything in the buffer (and the buffer was
  18170. ;; previously unmodified), then flip the modification status back
  18171. ;; to "unchanged".
  18172. (when (and hash (equal hash (org-buffer-hash)))
  18173. (set-buffer-modified-p nil))))
  18174. (defun org-auto-fill-function ()
  18175. "Auto-fill function."
  18176. ;; Check if auto-filling is meaningful.
  18177. (let ((fc (current-fill-column)))
  18178. (when (and fc (> (current-column) fc))
  18179. (let* ((fill-prefix (org-adaptive-fill-function))
  18180. ;; Enforce empty fill prefix, if required. Otherwise, it
  18181. ;; will be computed again.
  18182. (adaptive-fill-mode (not (equal fill-prefix ""))))
  18183. (when fill-prefix (do-auto-fill))))))
  18184. (defun org-comment-line-break-function (&optional soft)
  18185. "Break line at point and indent, continuing comment if within one.
  18186. The inserted newline is marked hard if variable
  18187. `use-hard-newlines' is true, unless optional argument SOFT is
  18188. non-nil."
  18189. (if soft (insert-and-inherit ?\n) (newline 1))
  18190. (save-excursion (forward-char -1) (delete-horizontal-space))
  18191. (delete-horizontal-space)
  18192. (indent-to-left-margin)
  18193. (insert-before-markers-and-inherit fill-prefix))
  18194. ;;; Fixed Width Areas
  18195. (defun org-toggle-fixed-width ()
  18196. "Toggle fixed-width markup.
  18197. Add or remove fixed-width markup on current line, whenever it
  18198. makes sense. Return an error otherwise.
  18199. If a region is active and if it contains only fixed-width areas
  18200. or blank lines, remove all fixed-width markup in it. If the
  18201. region contains anything else, convert all non-fixed-width lines
  18202. to fixed-width ones.
  18203. Blank lines at the end of the region are ignored unless the
  18204. region only contains such lines."
  18205. (interactive)
  18206. (if (not (org-region-active-p))
  18207. ;; No region:
  18208. ;;
  18209. ;; Remove fixed width marker only in a fixed-with element.
  18210. ;;
  18211. ;; Add fixed width maker in paragraphs, in blank lines after
  18212. ;; elements or at the beginning of a headline or an inlinetask,
  18213. ;; and before any one-line elements (e.g., a clock).
  18214. (progn
  18215. (beginning-of-line)
  18216. (let* ((element (org-element-at-point))
  18217. (type (org-element-type element)))
  18218. (cond
  18219. ((and (eq type 'fixed-width)
  18220. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  18221. (replace-match
  18222. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  18223. ((and (memq type '(babel-call clock comment diary-sexp headline
  18224. horizontal-rule keyword paragraph
  18225. planning))
  18226. (<= (org-element-property :post-affiliated element) (point)))
  18227. (skip-chars-forward " \t")
  18228. (insert ": "))
  18229. ((and (looking-at-p "[ \t]*$")
  18230. (or (eq type 'inlinetask)
  18231. (save-excursion
  18232. (skip-chars-forward " \r\t\n")
  18233. (<= (org-element-property :end element) (point)))))
  18234. (delete-region (point) (line-end-position))
  18235. (org-indent-line)
  18236. (insert ": "))
  18237. (t (user-error "Cannot insert a fixed-width line here")))))
  18238. ;; Region active.
  18239. (let* ((begin (save-excursion
  18240. (goto-char (region-beginning))
  18241. (line-beginning-position)))
  18242. (end (copy-marker
  18243. (save-excursion
  18244. (goto-char (region-end))
  18245. (unless (eolp) (beginning-of-line))
  18246. (if (save-excursion (re-search-backward "\\S-" begin t))
  18247. (progn (skip-chars-backward " \r\t\n") (point))
  18248. (point)))))
  18249. (all-fixed-width-p
  18250. (catch 'not-all-p
  18251. (save-excursion
  18252. (goto-char begin)
  18253. (skip-chars-forward " \r\t\n")
  18254. (when (eobp) (throw 'not-all-p nil))
  18255. (while (< (point) end)
  18256. (let ((element (org-element-at-point)))
  18257. (if (eq (org-element-type element) 'fixed-width)
  18258. (goto-char (org-element-property :end element))
  18259. (throw 'not-all-p nil))))
  18260. t))))
  18261. (if all-fixed-width-p
  18262. (save-excursion
  18263. (goto-char begin)
  18264. (while (< (point) end)
  18265. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  18266. (replace-match
  18267. "" nil nil nil
  18268. (if (= (line-end-position) (match-end 0)) 0 1)))
  18269. (forward-line)))
  18270. (let ((min-ind (point-max)))
  18271. ;; Find minimum indentation across all lines.
  18272. (save-excursion
  18273. (goto-char begin)
  18274. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  18275. (setq min-ind 0)
  18276. (catch 'zerop
  18277. (while (< (point) end)
  18278. (unless (looking-at-p "[ \t]*$")
  18279. (let ((ind (current-indentation)))
  18280. (setq min-ind (min min-ind ind))
  18281. (when (zerop ind) (throw 'zerop t))))
  18282. (forward-line)))))
  18283. ;; Loop over all lines and add fixed-width markup everywhere
  18284. ;; but in fixed-width lines.
  18285. (save-excursion
  18286. (goto-char begin)
  18287. (while (< (point) end)
  18288. (cond
  18289. ((org-at-heading-p)
  18290. (insert ": ")
  18291. (forward-line)
  18292. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  18293. (insert ":")
  18294. (forward-line)))
  18295. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  18296. (let* ((element (org-element-at-point))
  18297. (element-end (org-element-property :end element)))
  18298. (if (eq (org-element-type element) 'fixed-width)
  18299. (progn (goto-char element-end)
  18300. (skip-chars-backward " \r\t\n")
  18301. (forward-line))
  18302. (let ((limit (min end element-end)))
  18303. (while (< (point) limit)
  18304. (org-move-to-column min-ind t)
  18305. (insert ": ")
  18306. (forward-line))))))
  18307. (t
  18308. (org-move-to-column min-ind t)
  18309. (insert ": ")
  18310. (forward-line)))))))
  18311. (set-marker end nil))))
  18312. ;;; Blocks
  18313. (defun org-block-map (function &optional start end)
  18314. "Call FUNCTION at the head of all source blocks in the current buffer.
  18315. Optional arguments START and END can be used to limit the range."
  18316. (let ((start (or start (point-min)))
  18317. (end (or end (point-max))))
  18318. (save-excursion
  18319. (goto-char start)
  18320. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  18321. (save-excursion
  18322. (save-match-data
  18323. (goto-char (match-beginning 0))
  18324. (funcall function)))))))
  18325. (defun org-next-block (arg &optional backward block-regexp)
  18326. "Jump to the next block.
  18327. With a prefix argument ARG, jump forward ARG many blocks.
  18328. When BACKWARD is non-nil, jump to the previous block.
  18329. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  18330. Match data is set according to this regexp when the function
  18331. returns.
  18332. Return point at beginning of the opening line of found block.
  18333. Throw an error if no block is found."
  18334. (interactive "p")
  18335. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  18336. (case-fold-search t)
  18337. (search-fn (if backward #'re-search-backward #'re-search-forward))
  18338. (count (or arg 1))
  18339. (origin (point))
  18340. last-element)
  18341. (if backward (beginning-of-line) (end-of-line))
  18342. (while (and (> count 0) (funcall search-fn re nil t))
  18343. (let ((element (save-excursion
  18344. (goto-char (match-beginning 0))
  18345. (save-match-data (org-element-at-point)))))
  18346. (when (and (memq (org-element-type element)
  18347. '(center-block comment-block dynamic-block
  18348. example-block export-block quote-block
  18349. special-block src-block verse-block))
  18350. (<= (match-beginning 0)
  18351. (org-element-property :post-affiliated element)))
  18352. (setq last-element element)
  18353. (cl-decf count))))
  18354. (if (= count 0)
  18355. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  18356. (save-match-data (org-show-context)))
  18357. (goto-char origin)
  18358. (user-error "No %s code blocks" (if backward "previous" "further")))))
  18359. (defun org-previous-block (arg &optional block-regexp)
  18360. "Jump to the previous block.
  18361. With a prefix argument ARG, jump backward ARG many source blocks.
  18362. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  18363. (interactive "p")
  18364. (org-next-block arg t block-regexp))
  18365. ;;; Comments
  18366. ;; Org comments syntax is quite complex. It requires the entire line
  18367. ;; to be just a comment. Also, even with the right syntax at the
  18368. ;; beginning of line, some elements (e.g., verse-block or
  18369. ;; example-block) don't accept comments. Usual Emacs comment commands
  18370. ;; cannot cope with those requirements. Therefore, Org replaces them.
  18371. ;; Org still relies on `comment-dwim', but cannot trust
  18372. ;; `comment-only-p'. So, `comment-region-function' and
  18373. ;; `uncomment-region-function' both point
  18374. ;; to`org-comment-or-uncomment-region'. Eventually,
  18375. ;; `org-insert-comment' takes care of insertion of comments at the
  18376. ;; beginning of line.
  18377. ;; `org-setup-comments-handling' install comments related variables
  18378. ;; during `org-mode' initialization.
  18379. (defun org-setup-comments-handling ()
  18380. (interactive)
  18381. (setq-local comment-use-syntax nil)
  18382. (setq-local comment-start "# ")
  18383. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  18384. (setq-local comment-insert-comment-function 'org-insert-comment)
  18385. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  18386. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  18387. (defun org-insert-comment ()
  18388. "Insert an empty comment above current line.
  18389. If the line is empty, insert comment at its beginning. When
  18390. point is within a source block, comment according to the related
  18391. major mode."
  18392. (if (let ((element (org-element-at-point)))
  18393. (and (eq (org-element-type element) 'src-block)
  18394. (< (save-excursion
  18395. (goto-char (org-element-property :post-affiliated element))
  18396. (line-end-position))
  18397. (point))
  18398. (> (save-excursion
  18399. (goto-char (org-element-property :end element))
  18400. (skip-chars-backward " \r\t\n")
  18401. (line-beginning-position))
  18402. (point))))
  18403. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  18404. (beginning-of-line)
  18405. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  18406. (open-line 1))
  18407. (org-indent-line)
  18408. (insert "# ")))
  18409. (defvar comment-empty-lines) ; From newcomment.el.
  18410. (defun org-comment-or-uncomment-region (beg end &rest _)
  18411. "Comment or uncomment each non-blank line in the region.
  18412. Uncomment each non-blank line between BEG and END if it only
  18413. contains commented lines. Otherwise, comment them. If region is
  18414. strictly within a source block, use appropriate comment syntax."
  18415. (if (let ((element (org-element-at-point)))
  18416. (and (eq (org-element-type element) 'src-block)
  18417. (< (save-excursion
  18418. (goto-char (org-element-property :post-affiliated element))
  18419. (line-end-position))
  18420. beg)
  18421. (>= (save-excursion
  18422. (goto-char (org-element-property :end element))
  18423. (skip-chars-backward " \r\t\n")
  18424. (line-beginning-position))
  18425. end)))
  18426. ;; Translate region boundaries for the Org buffer to the source
  18427. ;; buffer.
  18428. (let ((offset (- end beg)))
  18429. (save-excursion
  18430. (goto-char beg)
  18431. (org-babel-do-in-edit-buffer
  18432. (comment-or-uncomment-region (point) (+ offset (point))))))
  18433. (save-restriction
  18434. ;; Restrict region
  18435. (narrow-to-region (save-excursion (goto-char beg)
  18436. (skip-chars-forward " \r\t\n" end)
  18437. (line-beginning-position))
  18438. (save-excursion (goto-char end)
  18439. (skip-chars-backward " \r\t\n" beg)
  18440. (line-end-position)))
  18441. (let ((uncommentp
  18442. ;; UNCOMMENTP is non-nil when every non blank line between
  18443. ;; BEG and END is a comment.
  18444. (save-excursion
  18445. (goto-char (point-min))
  18446. (while (and (not (eobp))
  18447. (let ((element (org-element-at-point)))
  18448. (and (eq (org-element-type element) 'comment)
  18449. (goto-char (min (point-max)
  18450. (org-element-property
  18451. :end element)))))))
  18452. (eobp))))
  18453. (if uncommentp
  18454. ;; Only blank lines and comments in region: uncomment it.
  18455. (save-excursion
  18456. (goto-char (point-min))
  18457. (while (not (eobp))
  18458. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  18459. (replace-match "" nil nil nil 1))
  18460. (forward-line)))
  18461. ;; Comment each line in region.
  18462. (let ((min-indent (point-max)))
  18463. ;; First find the minimum indentation across all lines.
  18464. (save-excursion
  18465. (goto-char (point-min))
  18466. (while (and (not (eobp)) (not (zerop min-indent)))
  18467. (unless (looking-at "[ \t]*$")
  18468. (setq min-indent (min min-indent (current-indentation))))
  18469. (forward-line)))
  18470. ;; Then loop over all lines.
  18471. (save-excursion
  18472. (goto-char (point-min))
  18473. (while (not (eobp))
  18474. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18475. ;; Don't get fooled by invisible text (e.g. link path)
  18476. ;; when moving to column MIN-INDENT.
  18477. (let ((buffer-invisibility-spec nil))
  18478. (org-move-to-column min-indent t))
  18479. (insert comment-start))
  18480. (forward-line)))))))))
  18481. (defun org-comment-dwim (_arg)
  18482. "Call the comment command you mean.
  18483. Call `org-toggle-comment' if on a heading, otherwise call
  18484. `comment-dwim', within a source edit buffer if needed."
  18485. (interactive "*P")
  18486. (cond ((org-at-heading-p)
  18487. (call-interactively #'org-toggle-comment))
  18488. ((org-in-src-block-p)
  18489. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18490. (t (call-interactively #'comment-dwim))))
  18491. ;;; Timestamps API
  18492. ;; This section contains tools to operate on, or create, timestamp
  18493. ;; objects, as returned by, e.g. `org-element-context'.
  18494. (defun org-timestamp-from-string (s)
  18495. "Convert Org timestamp S, as a string, into a timestamp object.
  18496. Return nil if S is not a valid timestamp string."
  18497. (when (org-string-nw-p s)
  18498. (with-temp-buffer
  18499. (save-excursion (insert s))
  18500. (org-element-timestamp-parser))))
  18501. (defun org-timestamp-from-time (time &optional with-time inactive)
  18502. "Convert a time value into a timestamp object.
  18503. TIME is an Emacs internal time representation, as returned, e.g.,
  18504. by `current-time'.
  18505. When optional argument WITH-TIME is non-nil, return a timestamp
  18506. object with a time part, i.e., with hours and minutes.
  18507. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18508. return an active timestamp."
  18509. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18510. (org-element-create 'timestamp
  18511. (list :type (if inactive 'inactive 'active)
  18512. :year-start year
  18513. :month-start month
  18514. :day-start day
  18515. :hour-start (and with-time hour)
  18516. :minute-start (and with-time minute)))))
  18517. (defun org-timestamp-to-time (timestamp &optional end)
  18518. "Convert TIMESTAMP object into an Emacs internal time value.
  18519. Use end of date range or time range when END is non-nil.
  18520. Otherwise, use its start."
  18521. (apply #'encode-time 0
  18522. (mapcar
  18523. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18524. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18525. '(:minute-start :hour-start :day-start :month-start
  18526. :year-start)))))
  18527. (defun org-timestamp-has-time-p (timestamp)
  18528. "Non-nil when TIMESTAMP has a time specified."
  18529. (org-element-property :hour-start timestamp))
  18530. (defun org-timestamp-format (timestamp format &optional end utc)
  18531. "Format a TIMESTAMP object into a string.
  18532. FORMAT is a format specifier to be passed to
  18533. `format-time-string'.
  18534. When optional argument END is non-nil, use end of date-range or
  18535. time-range, if possible.
  18536. When optional argument UTC is non-nil, time is be expressed as
  18537. Universal Time."
  18538. (format-time-string format (org-timestamp-to-time timestamp end)
  18539. (and utc t)))
  18540. (defun org-timestamp-split-range (timestamp &optional end)
  18541. "Extract a TIMESTAMP object from a date or time range.
  18542. END, when non-nil, means extract the end of the range.
  18543. Otherwise, extract its start.
  18544. Return a new timestamp object."
  18545. (let ((type (org-element-property :type timestamp)))
  18546. (if (memq type '(active inactive diary)) timestamp
  18547. (let ((split-ts (org-element-copy timestamp)))
  18548. ;; Set new type.
  18549. (org-element-put-property
  18550. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18551. ;; Copy start properties over end properties if END is
  18552. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18553. (let ((p-alist '((:minute-start . :minute-end)
  18554. (:hour-start . :hour-end)
  18555. (:day-start . :day-end)
  18556. (:month-start . :month-end)
  18557. (:year-start . :year-end))))
  18558. (dolist (p-cell p-alist)
  18559. (org-element-put-property
  18560. split-ts
  18561. (funcall (if end #'car #'cdr) p-cell)
  18562. (org-element-property
  18563. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18564. ;; Eventually refresh `:raw-value'.
  18565. (org-element-put-property split-ts :raw-value nil)
  18566. (org-element-put-property
  18567. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18568. (defun org-timestamp-translate (timestamp &optional boundary)
  18569. "Translate TIMESTAMP object to custom format.
  18570. Format string is defined in `org-time-stamp-custom-formats',
  18571. which see.
  18572. When optional argument BOUNDARY is non-nil, it is either the
  18573. symbol `start' or `end'. In this case, only translate the
  18574. starting or ending part of TIMESTAMP if it is a date or time
  18575. range. Otherwise, translate both parts.
  18576. Return timestamp as-is if `org-display-custom-times' is nil or if
  18577. it has a `diary' type."
  18578. (let ((type (org-element-property :type timestamp)))
  18579. (if (or (not org-display-custom-times) (eq type 'diary))
  18580. (org-element-interpret-data timestamp)
  18581. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18582. org-time-stamp-custom-formats)))
  18583. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18584. (concat (org-timestamp-format timestamp fmt)
  18585. "--"
  18586. (org-timestamp-format timestamp fmt t))
  18587. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18588. ;;; Other stuff
  18589. (defvar reftex-docstruct-symbol)
  18590. (defvar org--rds)
  18591. (defun org-reftex-citation ()
  18592. "Use reftex-citation to insert a citation into the buffer.
  18593. This looks for a line like
  18594. #+BIBLIOGRAPHY: foo plain option:-d
  18595. and derives from it that foo.bib is the bibliography file relevant
  18596. for this document. It then installs the necessary environment for RefTeX
  18597. to work in this buffer and calls `reftex-citation' to insert a citation
  18598. into the buffer.
  18599. Export of such citations to both LaTeX and HTML is handled by the contributed
  18600. package ox-bibtex by Taru Karttunen."
  18601. (interactive)
  18602. (let ((reftex-docstruct-symbol 'org--rds)
  18603. org--rds bib)
  18604. (org-with-wide-buffer
  18605. (let ((case-fold-search t)
  18606. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18607. (if (not (save-excursion
  18608. (or (re-search-forward re nil t)
  18609. (re-search-backward re nil t))))
  18610. (user-error "No bibliography defined in file")
  18611. (setq bib (concat (match-string 1) ".bib")
  18612. org--rds (list (list 'bib bib))))))
  18613. (call-interactively 'reftex-citation)))
  18614. ;;;; Functions extending outline functionality
  18615. (defun org-beginning-of-line (&optional n)
  18616. "Go to the beginning of the current visible line.
  18617. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18618. symbol `reversed', on the first attempt move to where the
  18619. headline text starts, and only move to beginning of line when the
  18620. cursor is already before the start of the text of the headline.
  18621. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18622. start of the text on the second attempt.
  18623. With argument N not nil or 1, move forward N - 1 lines first."
  18624. (interactive "^p")
  18625. (let ((origin (point))
  18626. (special (pcase org-special-ctrl-a/e
  18627. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18628. deactivate-mark)
  18629. ;; First move to a visible line.
  18630. (if (bound-and-true-p visual-line-mode)
  18631. (beginning-of-visual-line n)
  18632. (move-beginning-of-line n)
  18633. ;; `move-beginning-of-line' may leave point after invisible
  18634. ;; characters if line starts with such of these (e.g., with
  18635. ;; a link at column 0). Really move to the beginning of the
  18636. ;; current visible line.
  18637. (beginning-of-line))
  18638. (cond
  18639. ;; No special behavior. Point is already at the beginning of
  18640. ;; a line, logical or visual.
  18641. ((not special))
  18642. ;; `beginning-of-visual-line' left point before logical beginning
  18643. ;; of line: point is at the beginning of a visual line. Bail
  18644. ;; out.
  18645. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18646. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18647. ;; At a headline, special position is before the title, but
  18648. ;; after any TODO keyword or priority cookie.
  18649. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18650. (line-end-position)))
  18651. (bol (point)))
  18652. (if (eq special 'reversed)
  18653. (when (and (= origin bol) (eq last-command this-command))
  18654. (goto-char refpos))
  18655. (when (or (> origin refpos) (= origin bol))
  18656. (goto-char refpos)))))
  18657. ((and (looking-at org-list-full-item-re)
  18658. (memq (org-element-type (save-match-data (org-element-at-point)))
  18659. '(item plain-list)))
  18660. ;; Set special position at first white space character after
  18661. ;; bullet, and check-box, if any.
  18662. (let ((after-bullet
  18663. (let ((box (match-end 3)))
  18664. (cond ((not box) (match-end 1))
  18665. ((eq (char-after box) ?\s) (1+ box))
  18666. (t box)))))
  18667. (if (eq special 'reversed)
  18668. (when (and (= (point) origin) (eq last-command this-command))
  18669. (goto-char after-bullet))
  18670. (when (or (> origin after-bullet) (= (point) origin))
  18671. (goto-char after-bullet)))))
  18672. ;; No special context. Point is already at beginning of line.
  18673. (t nil))))
  18674. (defun org-end-of-line (&optional n)
  18675. "Go to the end of the line, but before ellipsis, if any.
  18676. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18677. symbol `reversed', ignore tags on the first attempt, and only
  18678. move to after the tags when the cursor is already beyond the end
  18679. of the headline.
  18680. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18681. on the second attempt.
  18682. With argument N not nil or 1, move forward N - 1 lines first."
  18683. (interactive "^p")
  18684. (let ((origin (point))
  18685. (special (pcase org-special-ctrl-a/e
  18686. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18687. deactivate-mark)
  18688. ;; First move to a visible line.
  18689. (if (bound-and-true-p visual-line-mode)
  18690. (beginning-of-visual-line n)
  18691. (move-beginning-of-line n))
  18692. (cond
  18693. ;; At a headline, with tags.
  18694. ((and special
  18695. (save-excursion
  18696. (beginning-of-line)
  18697. (let ((case-fold-search nil))
  18698. (looking-at org-complex-heading-regexp)))
  18699. (match-end 5))
  18700. (let ((tags (save-excursion
  18701. (goto-char (match-beginning 5))
  18702. (skip-chars-backward " \t")
  18703. (point)))
  18704. (visual-end (and (bound-and-true-p visual-line-mode)
  18705. (save-excursion
  18706. (end-of-visual-line)
  18707. (point)))))
  18708. ;; If `end-of-visual-line' brings us before end of line or
  18709. ;; even tags, i.e., the headline spans over multiple visual
  18710. ;; lines, move there.
  18711. (cond ((and visual-end
  18712. (< visual-end tags)
  18713. (<= origin visual-end))
  18714. (goto-char visual-end))
  18715. ((eq special 'reversed)
  18716. (if (and (= origin (line-end-position))
  18717. (eq this-command last-command))
  18718. (goto-char tags)
  18719. (end-of-line)))
  18720. (t
  18721. (if (or (< origin tags) (= origin (line-end-position)))
  18722. (goto-char tags)
  18723. (end-of-line))))))
  18724. ((bound-and-true-p visual-line-mode)
  18725. (let ((bol (line-beginning-position)))
  18726. (end-of-visual-line)
  18727. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18728. ;; end of a line, backtrack and use `end-of-line' instead.
  18729. (when (/= bol (line-beginning-position))
  18730. (goto-char bol)
  18731. (end-of-line))))
  18732. (t (end-of-line)))))
  18733. (defun org-backward-sentence (&optional _arg)
  18734. "Go to beginning of sentence, or beginning of table field.
  18735. This will call `backward-sentence' or `org-table-beginning-of-field',
  18736. depending on context."
  18737. (interactive)
  18738. (let* ((element (org-element-at-point))
  18739. (contents-begin (org-element-property :contents-begin element))
  18740. (table (org-element-lineage element '(table) t)))
  18741. (if (and table
  18742. (> (point) contents-begin)
  18743. (<= (point) (org-element-property :contents-end table)))
  18744. (call-interactively #'org-table-beginning-of-field)
  18745. (save-restriction
  18746. (when (and contents-begin
  18747. (< (point-min) contents-begin)
  18748. (> (point) contents-begin))
  18749. (narrow-to-region contents-begin
  18750. (org-element-property :contents-end element)))
  18751. (call-interactively #'backward-sentence)))))
  18752. (defun org-forward-sentence (&optional _arg)
  18753. "Go to end of sentence, or end of table field.
  18754. This will call `forward-sentence' or `org-table-end-of-field',
  18755. depending on context."
  18756. (interactive)
  18757. (if (and (org-at-heading-p)
  18758. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18759. (save-restriction
  18760. (narrow-to-region (line-beginning-position) (line-end-position))
  18761. (call-interactively #'forward-sentence))
  18762. (let* ((element (org-element-at-point))
  18763. (contents-end (org-element-property :contents-end element))
  18764. (table (org-element-lineage element '(table) t)))
  18765. (if (and table
  18766. (>= (point) (org-element-property :contents-begin table))
  18767. (< (point) contents-end))
  18768. (call-interactively #'org-table-end-of-field)
  18769. (save-restriction
  18770. (when (and contents-end
  18771. (> (point-max) contents-end)
  18772. ;; Skip blank lines between elements.
  18773. (< (org-element-property :end element)
  18774. (save-excursion (goto-char contents-end)
  18775. (skip-chars-forward " \r\t\n"))))
  18776. (narrow-to-region (org-element-property :contents-begin element)
  18777. contents-end))
  18778. ;; End of heading is considered as the end of a sentence.
  18779. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18780. (call-interactively #'forward-sentence)))))))
  18781. (defun org-kill-line (&optional _arg)
  18782. "Kill line, to tags or end of line."
  18783. (interactive)
  18784. (cond
  18785. ((or (not org-special-ctrl-k)
  18786. (bolp)
  18787. (not (org-at-heading-p)))
  18788. (when (and (get-char-property (line-end-position) 'invisible)
  18789. org-ctrl-k-protect-subtree
  18790. (or (eq org-ctrl-k-protect-subtree 'error)
  18791. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18792. (user-error
  18793. (substitute-command-keys
  18794. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18795. (call-interactively
  18796. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18797. ((org-match-line org-tag-line-re)
  18798. (let ((end (save-excursion
  18799. (goto-char (match-beginning 1))
  18800. (skip-chars-backward " \t")
  18801. (point))))
  18802. (if (<= end (point)) ;on tags part
  18803. (kill-region (point) (line-end-position))
  18804. (kill-region (point) end)))
  18805. (org-align-tags))
  18806. (t (kill-region (point) (line-end-position)))))
  18807. (defun org-yank (&optional arg)
  18808. "Yank. If the kill is a subtree, treat it specially.
  18809. This command will look at the current kill and check if is a single
  18810. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18811. cursor is at the beginning of a line or after the stars of a currently
  18812. empty headline, then the yank is handled specially. How exactly depends
  18813. on the value of the following variables.
  18814. `org-yank-folded-subtrees'
  18815. By default, this variable is non-nil, which results in
  18816. subtree(s) being folded after insertion, except if doing so
  18817. would swallow text after the yanked text.
  18818. `org-yank-adjusted-subtrees'
  18819. When non-nil (the default value is nil), the subtree will be
  18820. promoted or demoted in order to fit into the local outline tree
  18821. structure, which means that the level will be adjusted so that it
  18822. becomes the smaller one of the two *visible* surrounding headings.
  18823. Any prefix to this command will cause `yank' to be called directly with
  18824. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18825. will just
  18826. plainly yank the text as it is.
  18827. \[1] The test checks if the first non-white line is a heading
  18828. and if there are no other headings with fewer stars."
  18829. (interactive "P")
  18830. (org-yank-generic 'yank arg))
  18831. (defun org-yank-generic (command arg)
  18832. "Perform some yank-like command.
  18833. This function implements the behavior described in the `org-yank'
  18834. documentation. However, it has been generalized to work for any
  18835. interactive command with similar behavior."
  18836. ;; pretend to be command COMMAND
  18837. (setq this-command command)
  18838. (if arg
  18839. (call-interactively command)
  18840. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18841. (and (org-kill-is-subtree-p)
  18842. (or (bolp)
  18843. (and (looking-at "[ \t]*$")
  18844. (string-match
  18845. "\\`\\*+\\'"
  18846. (buffer-substring (point-at-bol) (point)))))))
  18847. swallowp)
  18848. (cond
  18849. ((and subtreep org-yank-folded-subtrees)
  18850. (let ((beg (point))
  18851. end)
  18852. (if (and subtreep org-yank-adjusted-subtrees)
  18853. (org-paste-subtree nil nil 'for-yank)
  18854. (call-interactively command))
  18855. (setq end (point))
  18856. (goto-char beg)
  18857. (when (and (bolp) subtreep
  18858. (not (setq swallowp
  18859. (org-yank-folding-would-swallow-text beg end))))
  18860. (org-with-limited-levels
  18861. (or (looking-at org-outline-regexp)
  18862. (re-search-forward org-outline-regexp-bol end t))
  18863. (while (and (< (point) end) (looking-at org-outline-regexp))
  18864. (org-flag-subtree t)
  18865. (org-cycle-show-empty-lines 'folded)
  18866. (condition-case nil
  18867. (outline-forward-same-level 1)
  18868. (error (goto-char end))))))
  18869. (when swallowp
  18870. (message
  18871. "Inserted text not folded because that would swallow text"))
  18872. (goto-char end)
  18873. (skip-chars-forward " \t\n\r")
  18874. (beginning-of-line 1)
  18875. (push-mark beg 'nomsg)))
  18876. ((and subtreep org-yank-adjusted-subtrees)
  18877. (let ((beg (point-at-bol)))
  18878. (org-paste-subtree nil nil 'for-yank)
  18879. (push-mark beg 'nomsg)))
  18880. (t
  18881. (call-interactively command))))))
  18882. (defun org-yank-folding-would-swallow-text (beg end)
  18883. "Would hide-subtree at BEG swallow any text after END?"
  18884. (let (level)
  18885. (org-with-limited-levels
  18886. (save-excursion
  18887. (goto-char beg)
  18888. (when (or (looking-at org-outline-regexp)
  18889. (re-search-forward org-outline-regexp-bol end t))
  18890. (setq level (org-outline-level)))
  18891. (goto-char end)
  18892. (skip-chars-forward " \t\r\n\v\f")
  18893. (not (or (eobp)
  18894. (and (bolp) (looking-at-p org-outline-regexp)
  18895. (<= (org-outline-level) level))))))))
  18896. (defun org-back-to-heading (&optional invisible-ok)
  18897. "Call `outline-back-to-heading', but provide a better error message."
  18898. (condition-case nil
  18899. (outline-back-to-heading invisible-ok)
  18900. (error
  18901. (user-error "Before first headline at position %d in buffer %s"
  18902. (point) (current-buffer)))))
  18903. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18904. "Go back to heading or first point in buffer.
  18905. If point is before first heading go to first point in buffer
  18906. instead of back to heading."
  18907. (condition-case nil
  18908. (outline-back-to-heading invisible-ok)
  18909. (error
  18910. (goto-char (point-min)))))
  18911. (defun org-before-first-heading-p ()
  18912. "Before first heading?"
  18913. (org-with-limited-levels
  18914. (save-excursion
  18915. (end-of-line)
  18916. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18917. (defun org-at-heading-p (&optional _)
  18918. "Non-nil when on a headline."
  18919. (outline-on-heading-p t))
  18920. (defun org-in-commented-heading-p (&optional no-inheritance)
  18921. "Non-nil if point is under a commented heading.
  18922. This function also checks ancestors of the current headline,
  18923. unless optional argument NO-INHERITANCE is non-nil."
  18924. (cond
  18925. ((org-before-first-heading-p) nil)
  18926. ((let ((headline (nth 4 (org-heading-components))))
  18927. (and headline
  18928. (let ((case-fold-search nil))
  18929. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18930. headline)))))
  18931. (no-inheritance nil)
  18932. (t
  18933. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18934. (defun org-at-comment-p nil
  18935. "Return t if cursor is in a commented line."
  18936. (save-excursion
  18937. (save-match-data
  18938. (beginning-of-line)
  18939. (looking-at "^[ \t]*# "))))
  18940. (defun org-at-keyword-p nil
  18941. "Return t if cursor is at a keyword-line."
  18942. (save-excursion
  18943. (move-beginning-of-line 1)
  18944. (looking-at org-keyword-regexp)))
  18945. (defun org-at-drawer-p nil
  18946. "Return t if cursor is at a drawer keyword."
  18947. (save-excursion
  18948. (move-beginning-of-line 1)
  18949. (looking-at org-drawer-regexp)))
  18950. (defun org-at-block-p nil
  18951. "Return t if cursor is at a block keyword."
  18952. (save-excursion
  18953. (move-beginning-of-line 1)
  18954. (looking-at org-block-regexp)))
  18955. (defun org-point-at-end-of-empty-headline ()
  18956. "If point is at the end of an empty headline, return t, else nil.
  18957. If the heading only contains a TODO keyword, it is still still considered
  18958. empty."
  18959. (let ((case-fold-search nil))
  18960. (and (looking-at "[ \t]*$")
  18961. org-todo-line-regexp
  18962. (save-excursion
  18963. (beginning-of-line)
  18964. (looking-at org-todo-line-regexp)
  18965. (string= (match-string 3) "")))))
  18966. (defun org-at-heading-or-item-p ()
  18967. (or (org-at-heading-p) (org-at-item-p)))
  18968. (defun org-up-heading-all (arg)
  18969. "Move to the heading line of which the present line is a subheading.
  18970. This function considers both visible and invisible heading lines.
  18971. With argument, move up ARG levels."
  18972. (outline-up-heading arg t))
  18973. (defun org-up-heading-safe ()
  18974. "Move to the heading line of which the present line is a subheading.
  18975. This version will not throw an error. It will return the level of the
  18976. headline found, or nil if no higher level is found.
  18977. Also, this function will be a lot faster than `outline-up-heading',
  18978. because it relies on stars being the outline starters. This can really
  18979. make a significant difference in outlines with very many siblings."
  18980. (when (ignore-errors (org-back-to-heading t))
  18981. (let ((level-up (1- (funcall outline-level))))
  18982. (and (> level-up 0)
  18983. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  18984. (funcall outline-level)))))
  18985. (defun org-up-heading-or-point-min ()
  18986. "Move to the heading line of which the present is a subheading, or point-min.
  18987. This version is needed to make point-min behave like a virtual
  18988. heading of level 0 for property-inheritance. It will return the
  18989. level of the headline found (down to 0) or nil if already at a
  18990. point before the first headline or at point-min."
  18991. (when (ignore-errors (org-back-to-heading t))
  18992. (if (< 1 (funcall outline-level))
  18993. (org-up-heading-safe)
  18994. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18995. (defun org-first-sibling-p ()
  18996. "Is this heading the first child of its parents?"
  18997. (interactive)
  18998. (let ((re org-outline-regexp-bol)
  18999. level l)
  19000. (unless (org-at-heading-p t)
  19001. (user-error "Not at a heading"))
  19002. (setq level (funcall outline-level))
  19003. (save-excursion
  19004. (if (not (re-search-backward re nil t))
  19005. t
  19006. (setq l (funcall outline-level))
  19007. (< l level)))))
  19008. (defun org-goto-sibling (&optional previous)
  19009. "Goto the next sibling, even if it is invisible.
  19010. When PREVIOUS is set, go to the previous sibling instead. Returns t
  19011. when a sibling was found. When none is found, return nil and don't
  19012. move point."
  19013. (let ((fun (if previous 're-search-backward 're-search-forward))
  19014. (pos (point))
  19015. (re org-outline-regexp-bol)
  19016. level l)
  19017. (when (ignore-errors (org-back-to-heading t))
  19018. (setq level (funcall outline-level))
  19019. (catch 'exit
  19020. (or previous (forward-char 1))
  19021. (while (funcall fun re nil t)
  19022. (setq l (funcall outline-level))
  19023. (when (< l level) (goto-char pos) (throw 'exit nil))
  19024. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  19025. (goto-char pos)
  19026. nil))))
  19027. (defun org-show-siblings ()
  19028. "Show all siblings of the current headline."
  19029. (save-excursion
  19030. (while (org-goto-sibling) (org-flag-heading nil)))
  19031. (save-excursion
  19032. (while (org-goto-sibling 'previous)
  19033. (org-flag-heading nil))))
  19034. (defun org-goto-first-child ()
  19035. "Goto the first child, even if it is invisible.
  19036. Return t when a child was found. Otherwise don't move point and
  19037. return nil."
  19038. (let (level (pos (point)) (re org-outline-regexp-bol))
  19039. (when (ignore-errors (org-back-to-heading t))
  19040. (setq level (outline-level))
  19041. (forward-char 1)
  19042. (if (and (re-search-forward re nil t) (> (outline-level) level))
  19043. (progn (goto-char (match-beginning 0)) t)
  19044. (goto-char pos) nil))))
  19045. (defun org-show-hidden-entry ()
  19046. "Show an entry where even the heading is hidden."
  19047. (save-excursion
  19048. (org-show-entry)))
  19049. (defun org-flag-heading (flag &optional entry)
  19050. "Flag the current heading. FLAG non-nil means make invisible.
  19051. When ENTRY is non-nil, show the entire entry."
  19052. (save-excursion
  19053. (org-back-to-heading t)
  19054. ;; Check if we should show the entire entry
  19055. (if (not entry)
  19056. (org-flag-region
  19057. (line-end-position 0) (line-end-position) flag 'outline)
  19058. (org-show-entry)
  19059. (save-excursion
  19060. (and (outline-next-heading)
  19061. (org-flag-heading nil))))))
  19062. (defun org-get-next-sibling ()
  19063. "Move to next heading of the same level, and return point.
  19064. If there is no such heading, return nil.
  19065. This is like outline-next-sibling, but invisible headings are ok."
  19066. (let ((level (funcall outline-level)))
  19067. (outline-next-heading)
  19068. (while (and (not (eobp)) (> (funcall outline-level) level))
  19069. (outline-next-heading))
  19070. (unless (or (eobp) (< (funcall outline-level) level))
  19071. (point))))
  19072. (defun org-get-last-sibling ()
  19073. "Move to previous heading of the same level, and return point.
  19074. If there is no such heading, return nil."
  19075. (let ((opoint (point))
  19076. (level (funcall outline-level)))
  19077. (outline-previous-heading)
  19078. (when (and (/= (point) opoint) (outline-on-heading-p t))
  19079. (while (and (> (funcall outline-level) level)
  19080. (not (bobp)))
  19081. (outline-previous-heading))
  19082. (unless (< (funcall outline-level) level)
  19083. (point)))))
  19084. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  19085. "Goto to the end of a subtree."
  19086. ;; This contains an exact copy of the original function, but it uses
  19087. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  19088. ;; trees and before first headline. And is uses an invisible-ok argument.
  19089. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  19090. ;; Furthermore, when used inside Org, finding the end of a large subtree
  19091. ;; with many children and grandchildren etc, this can be much faster
  19092. ;; than the outline version.
  19093. (org-back-to-heading-or-point-min invisible-ok)
  19094. (let ((first t)
  19095. (level (funcall outline-level)))
  19096. (cond ((= level 0)
  19097. (goto-char (point-max)))
  19098. ((and (derived-mode-p 'org-mode) (< level 1000))
  19099. ;; A true heading (not a plain list item), in Org
  19100. ;; This means we can easily find the end by looking
  19101. ;; only for the right number of stars. Using a regexp to do
  19102. ;; this is so much faster than using a Lisp loop.
  19103. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  19104. (forward-char 1)
  19105. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  19106. (t
  19107. ;; something else, do it the slow way
  19108. (while (and (not (eobp))
  19109. (or first (> (funcall outline-level) level)))
  19110. (setq first nil)
  19111. (outline-next-heading))))
  19112. (unless to-heading
  19113. (when (memq (preceding-char) '(?\n ?\^M))
  19114. ;; Go to end of line before heading
  19115. (forward-char -1)
  19116. (when (memq (preceding-char) '(?\n ?\^M))
  19117. ;; leave blank line before heading
  19118. (forward-char -1)))))
  19119. (point))
  19120. (defun org-end-of-meta-data (&optional full)
  19121. "Skip planning line and properties drawer in current entry.
  19122. When optional argument FULL is non-nil, also skip empty lines,
  19123. clocking lines and regular drawers at the beginning of the
  19124. entry."
  19125. (org-back-to-heading t)
  19126. (forward-line)
  19127. (when (looking-at-p org-planning-line-re) (forward-line))
  19128. (when (looking-at org-property-drawer-re)
  19129. (goto-char (match-end 0))
  19130. (forward-line))
  19131. (when (and full (not (org-at-heading-p)))
  19132. (catch 'exit
  19133. (let ((end (save-excursion (outline-next-heading) (point)))
  19134. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  19135. (while (not (eobp))
  19136. (cond ((looking-at-p org-drawer-regexp)
  19137. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  19138. (forward-line)
  19139. (throw 'exit t)))
  19140. ((looking-at-p re) (forward-line))
  19141. (t (throw 'exit t))))))))
  19142. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  19143. "Move forward to the ARG'th subheading at same level as this one.
  19144. Stop at the first and last subheadings of a superior heading.
  19145. Normally this only looks at visible headings, but when INVISIBLE-OK is
  19146. non-nil it will also look at invisible ones."
  19147. (interactive "p")
  19148. (let ((backward? (and arg (< arg 0))))
  19149. (if (org-before-first-heading-p)
  19150. (if backward? (goto-char (point-min)) (outline-next-heading))
  19151. (org-back-to-heading invisible-ok)
  19152. (unless backward? (end-of-line)) ;do not match current headline
  19153. (let ((level (- (match-end 0) (match-beginning 0) 1))
  19154. (f (if backward? #'re-search-backward #'re-search-forward))
  19155. (count (if arg (abs arg) 1))
  19156. (result (point)))
  19157. (while (and (> count 0)
  19158. (funcall f org-outline-regexp-bol nil 'move))
  19159. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  19160. (cond ((< l level) (setq count 0))
  19161. ((and (= l level)
  19162. (or invisible-ok
  19163. (not (org-invisible-p
  19164. (line-beginning-position)))))
  19165. (cl-decf count)
  19166. (when (= l level) (setq result (point)))))))
  19167. (goto-char result))
  19168. (beginning-of-line))))
  19169. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  19170. "Move backward to the ARG'th subheading at same level as this one.
  19171. Stop at the first and last subheadings of a superior heading."
  19172. (interactive "p")
  19173. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  19174. (defun org-next-visible-heading (arg)
  19175. "Move to the next visible heading.
  19176. This function wraps `outline-next-visible-heading' with
  19177. `org-with-limited-levels' in order to skip over inline tasks and
  19178. respect customization of `org-odd-levels-only'."
  19179. (interactive "p")
  19180. (org-with-limited-levels
  19181. (outline-next-visible-heading arg)))
  19182. (defun org-previous-visible-heading (arg)
  19183. "Move to the previous visible heading.
  19184. This function wraps `outline-previous-visible-heading' with
  19185. `org-with-limited-levels' in order to skip over inline tasks and
  19186. respect customization of `org-odd-levels-only'."
  19187. (interactive "p")
  19188. (org-with-limited-levels
  19189. (outline-previous-visible-heading arg)))
  19190. (defun org-forward-paragraph ()
  19191. "Move forward to beginning of next paragraph or equivalent.
  19192. The function moves point to the beginning of the next visible
  19193. structural element, which can be a paragraph, a table, a list
  19194. item, etc. It also provides some special moves for convenience:
  19195. - On an affiliated keyword, jump to the beginning of the
  19196. relative element.
  19197. - On an item or a footnote definition, move to the second
  19198. element inside, if any.
  19199. - On a table or a property drawer, jump after it.
  19200. - On a verse or source block, stop after blank lines."
  19201. (interactive)
  19202. (unless (eobp)
  19203. (let* ((deactivate-mark nil)
  19204. (element (org-element-at-point))
  19205. (type (org-element-type element))
  19206. (post-affiliated (org-element-property :post-affiliated element))
  19207. (contents-begin (org-element-property :contents-begin element))
  19208. (contents-end (org-element-property :contents-end element))
  19209. (end (let ((end (org-element-property :end element)) (parent element))
  19210. (while (and (setq parent (org-element-property :parent parent))
  19211. (= (org-element-property :contents-end parent) end))
  19212. (setq end (org-element-property :end parent)))
  19213. end)))
  19214. (cond ((not element)
  19215. (skip-chars-forward " \r\t\n")
  19216. (or (eobp) (beginning-of-line)))
  19217. ;; On affiliated keywords, move to element's beginning.
  19218. ((< (point) post-affiliated)
  19219. (goto-char post-affiliated))
  19220. ;; At a table row, move to the end of the table. Similarly,
  19221. ;; at a node property, move to the end of the property
  19222. ;; drawer.
  19223. ((memq type '(node-property table-row))
  19224. (goto-char (org-element-property
  19225. :end (org-element-property :parent element))))
  19226. ((memq type '(property-drawer table)) (goto-char end))
  19227. ;; Consider blank lines as separators in verse and source
  19228. ;; blocks to ease editing.
  19229. ((memq type '(src-block verse-block))
  19230. (when (eq type 'src-block)
  19231. (setq contents-end
  19232. (save-excursion (goto-char end)
  19233. (skip-chars-backward " \r\t\n")
  19234. (line-beginning-position))))
  19235. (beginning-of-line)
  19236. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  19237. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  19238. (goto-char end)
  19239. (skip-chars-forward " \r\t\n")
  19240. (if (= (point) contents-end) (goto-char end)
  19241. (beginning-of-line))))
  19242. ;; With no contents, just skip element.
  19243. ((not contents-begin) (goto-char end))
  19244. ;; If contents are invisible, skip the element altogether.
  19245. ((org-invisible-p (line-end-position))
  19246. (cl-case type
  19247. (headline
  19248. (org-with-limited-levels (outline-next-visible-heading 1)))
  19249. ;; At a plain list, make sure we move to the next item
  19250. ;; instead of skipping the whole list.
  19251. (plain-list (forward-char)
  19252. (org-forward-paragraph))
  19253. (otherwise (goto-char end))))
  19254. ((>= (point) contents-end) (goto-char end))
  19255. ((>= (point) contents-begin)
  19256. ;; This can only happen on paragraphs and plain lists.
  19257. (cl-case type
  19258. (paragraph (goto-char end))
  19259. ;; At a plain list, try to move to second element in
  19260. ;; first item, if possible.
  19261. (plain-list (end-of-line)
  19262. (org-forward-paragraph))))
  19263. ;; When contents start on the middle of a line (e.g. in
  19264. ;; items and footnote definitions), try to reach first
  19265. ;; element starting after current line.
  19266. ((> (line-end-position) contents-begin)
  19267. (end-of-line)
  19268. (org-forward-paragraph))
  19269. (t (goto-char contents-begin))))))
  19270. (defun org-backward-paragraph ()
  19271. "Move backward to start of previous paragraph or equivalent.
  19272. The function moves point to the beginning of the current
  19273. structural element, which can be a paragraph, a table, a list
  19274. item, etc., or to the beginning of the previous visible one if
  19275. point is already there. It also provides some special moves for
  19276. convenience:
  19277. - On an affiliated keyword, jump to the first one.
  19278. - On a table or a property drawer, move to its beginning.
  19279. - On comment, example, export, src and verse blocks, stop
  19280. before blank lines."
  19281. (interactive)
  19282. (unless (bobp)
  19283. (let* ((deactivate-mark nil)
  19284. (element (org-element-at-point))
  19285. (type (org-element-type element))
  19286. (contents-end (org-element-property :contents-end element))
  19287. (post-affiliated (org-element-property :post-affiliated element))
  19288. (begin (org-element-property :begin element))
  19289. (special? ;blocks handled specially
  19290. (memq type '(comment-block example-block export-block src-block
  19291. verse-block)))
  19292. (contents-begin
  19293. (if special?
  19294. ;; These types have no proper contents. Fake line
  19295. ;; below the block opening line as contents beginning.
  19296. (save-excursion (goto-char begin) (line-beginning-position 2))
  19297. (org-element-property :contents-begin element))))
  19298. (cond
  19299. ((not element) (goto-char (point-min)))
  19300. ((= (point) begin)
  19301. (backward-char)
  19302. (org-backward-paragraph))
  19303. ((<= (point) post-affiliated) (goto-char begin))
  19304. ;; Special behavior: on a table or a property drawer, move to
  19305. ;; its beginning.
  19306. ((memq type '(node-property table-row))
  19307. (goto-char (org-element-property
  19308. :post-affiliated (org-element-property :parent element))))
  19309. (special?
  19310. (if (<= (point) contents-begin) (goto-char post-affiliated)
  19311. ;; Inside a verse block, see blank lines as paragraph
  19312. ;; separators.
  19313. (let ((origin (point)))
  19314. (skip-chars-backward " \r\t\n" contents-begin)
  19315. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  19316. (skip-chars-forward " \r\t\n" origin)
  19317. (if (= (point) origin) (goto-char contents-begin)
  19318. (beginning-of-line))))))
  19319. ((eq type 'paragraph) (goto-char contents-begin)
  19320. ;; When at first paragraph in an item or a footnote definition,
  19321. ;; move directly to beginning of line.
  19322. (let ((parent-contents
  19323. (org-element-property
  19324. :contents-begin (org-element-property :parent element))))
  19325. (when (and parent-contents (= parent-contents contents-begin))
  19326. (beginning-of-line))))
  19327. ;; At the end of a greater element, move to the beginning of
  19328. ;; the last element within.
  19329. ((and contents-end (>= (point) contents-end))
  19330. (goto-char (1- contents-end))
  19331. (org-backward-paragraph))
  19332. (t (goto-char (or post-affiliated begin))))
  19333. ;; Ensure we never leave point invisible.
  19334. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  19335. (defun org-forward-element ()
  19336. "Move forward by one element.
  19337. Move to the next element at the same level, when possible."
  19338. (interactive)
  19339. (cond ((eobp) (user-error "Cannot move further down"))
  19340. ((org-with-limited-levels (org-at-heading-p))
  19341. (let ((origin (point)))
  19342. (goto-char (org-end-of-subtree nil t))
  19343. (unless (org-with-limited-levels (org-at-heading-p))
  19344. (goto-char origin)
  19345. (user-error "Cannot move further down"))))
  19346. (t
  19347. (let* ((elem (org-element-at-point))
  19348. (end (org-element-property :end elem))
  19349. (parent (org-element-property :parent elem)))
  19350. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19351. (goto-char (org-element-property :end parent)))
  19352. ((integer-or-marker-p end) (goto-char end))
  19353. (t (message "No element at point")))))))
  19354. (defun org-backward-element ()
  19355. "Move backward by one element.
  19356. Move to the previous element at the same level, when possible."
  19357. (interactive)
  19358. (cond ((bobp) (user-error "Cannot move further up"))
  19359. ((org-with-limited-levels (org-at-heading-p))
  19360. ;; At a headline, move to the previous one, if any, or stay
  19361. ;; here.
  19362. (let ((origin (point)))
  19363. (org-with-limited-levels (org-backward-heading-same-level 1))
  19364. ;; When current headline has no sibling above, move to its
  19365. ;; parent.
  19366. (when (= (point) origin)
  19367. (or (org-with-limited-levels (org-up-heading-safe))
  19368. (progn (goto-char origin)
  19369. (user-error "Cannot move further up"))))))
  19370. (t
  19371. (let* ((elem (org-element-at-point))
  19372. (beg (org-element-property :begin elem)))
  19373. (cond
  19374. ;; Move to beginning of current element if point isn't
  19375. ;; there already.
  19376. ((null beg) (message "No element at point"))
  19377. ((/= (point) beg) (goto-char beg))
  19378. (t (goto-char beg)
  19379. (skip-chars-backward " \r\t\n")
  19380. (unless (bobp)
  19381. (let ((prev (org-element-at-point)))
  19382. (goto-char (org-element-property :begin prev))
  19383. (while (and (setq prev (org-element-property :parent prev))
  19384. (<= (org-element-property :end prev) beg))
  19385. (goto-char (org-element-property :begin prev)))))))))))
  19386. (defun org-up-element ()
  19387. "Move to upper element."
  19388. (interactive)
  19389. (if (org-with-limited-levels (org-at-heading-p))
  19390. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19391. (let* ((elem (org-element-at-point))
  19392. (parent (org-element-property :parent elem)))
  19393. (if parent (goto-char (org-element-property :begin parent))
  19394. (if (org-with-limited-levels (org-before-first-heading-p))
  19395. (user-error "No surrounding element")
  19396. (org-with-limited-levels (org-back-to-heading)))))))
  19397. (defun org-down-element ()
  19398. "Move to inner element."
  19399. (interactive)
  19400. (let ((element (org-element-at-point)))
  19401. (cond
  19402. ((memq (org-element-type element) '(plain-list table))
  19403. (goto-char (org-element-property :contents-begin element))
  19404. (forward-char))
  19405. ((memq (org-element-type element) org-element-greater-elements)
  19406. ;; If contents are hidden, first disclose them.
  19407. (when (org-invisible-p (line-end-position)) (org-cycle))
  19408. (goto-char (or (org-element-property :contents-begin element)
  19409. (user-error "No content for this element"))))
  19410. (t (user-error "No inner element")))))
  19411. (defun org-drag-element-backward ()
  19412. "Move backward element at point."
  19413. (interactive)
  19414. (let ((elem (or (org-element-at-point)
  19415. (user-error "No element at point"))))
  19416. (if (eq (org-element-type elem) 'headline)
  19417. ;; Preserve point when moving a whole tree, even if point was
  19418. ;; on blank lines below the headline.
  19419. (let ((offset (skip-chars-backward " \t\n")))
  19420. (unwind-protect (org-move-subtree-up)
  19421. (forward-char (- offset))))
  19422. (let ((prev-elem
  19423. (save-excursion
  19424. (goto-char (org-element-property :begin elem))
  19425. (skip-chars-backward " \r\t\n")
  19426. (unless (bobp)
  19427. (let* ((beg (org-element-property :begin elem))
  19428. (prev (org-element-at-point))
  19429. (up prev))
  19430. (while (and (setq up (org-element-property :parent up))
  19431. (<= (org-element-property :end up) beg))
  19432. (setq prev up))
  19433. prev)))))
  19434. ;; Error out if no previous element or previous element is
  19435. ;; a parent of the current one.
  19436. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19437. (user-error "Cannot drag element backward")
  19438. (let ((pos (point)))
  19439. (org-element-swap-A-B prev-elem elem)
  19440. (goto-char (+ (org-element-property :begin prev-elem)
  19441. (- pos (org-element-property :begin elem))))))))))
  19442. (defun org-drag-element-forward ()
  19443. "Move forward element at point."
  19444. (interactive)
  19445. (let* ((pos (point))
  19446. (elem (or (org-element-at-point)
  19447. (user-error "No element at point"))))
  19448. (when (= (point-max) (org-element-property :end elem))
  19449. (user-error "Cannot drag element forward"))
  19450. (goto-char (org-element-property :end elem))
  19451. (let ((next-elem (org-element-at-point)))
  19452. (when (or (org-element-nested-p elem next-elem)
  19453. (and (eq (org-element-type next-elem) 'headline)
  19454. (not (eq (org-element-type elem) 'headline))))
  19455. (goto-char pos)
  19456. (user-error "Cannot drag element forward"))
  19457. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19458. ;; body's length (without final blanks) and by the length of
  19459. ;; blanks between ELEM and NEXT-ELEM.
  19460. (let ((size-next (- (save-excursion
  19461. (goto-char (org-element-property :end next-elem))
  19462. (skip-chars-backward " \r\t\n")
  19463. (forward-line)
  19464. ;; Small correction if buffer doesn't end
  19465. ;; with a newline character.
  19466. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19467. (org-element-property :begin next-elem)))
  19468. (size-blank (- (org-element-property :end elem)
  19469. (save-excursion
  19470. (goto-char (org-element-property :end elem))
  19471. (skip-chars-backward " \r\t\n")
  19472. (forward-line)
  19473. (point)))))
  19474. (org-element-swap-A-B elem next-elem)
  19475. (goto-char (+ pos size-next size-blank))))))
  19476. (defun org-drag-line-forward (arg)
  19477. "Drag the line at point ARG lines forward."
  19478. (interactive "p")
  19479. (dotimes (_ (abs arg))
  19480. (let ((c (current-column)))
  19481. (if (< 0 arg)
  19482. (progn
  19483. (beginning-of-line 2)
  19484. (transpose-lines 1)
  19485. (beginning-of-line 0))
  19486. (transpose-lines 1)
  19487. (beginning-of-line -1))
  19488. (org-move-to-column c))))
  19489. (defun org-drag-line-backward (arg)
  19490. "Drag the line at point ARG lines backward."
  19491. (interactive "p")
  19492. (org-drag-line-forward (- arg)))
  19493. (defun org-mark-element ()
  19494. "Put point at beginning of this element, mark at end.
  19495. Interactively, if this command is repeated or (in Transient Mark
  19496. mode) if the mark is active, it marks the next element after the
  19497. ones already marked."
  19498. (interactive)
  19499. (let (deactivate-mark)
  19500. (if (and (called-interactively-p 'any)
  19501. (or (and (eq last-command this-command) (mark t))
  19502. (and transient-mark-mode mark-active)))
  19503. (set-mark
  19504. (save-excursion
  19505. (goto-char (mark))
  19506. (goto-char (org-element-property :end (org-element-at-point)))))
  19507. (let ((element (org-element-at-point)))
  19508. (end-of-line)
  19509. (push-mark (org-element-property :end element) t t)
  19510. (goto-char (org-element-property :begin element))))))
  19511. (defun org-narrow-to-element ()
  19512. "Narrow buffer to current element."
  19513. (interactive)
  19514. (let ((elem (org-element-at-point)))
  19515. (cond
  19516. ((eq (car elem) 'headline)
  19517. (narrow-to-region
  19518. (org-element-property :begin elem)
  19519. (org-element-property :end elem)))
  19520. ((memq (car elem) org-element-greater-elements)
  19521. (narrow-to-region
  19522. (org-element-property :contents-begin elem)
  19523. (org-element-property :contents-end elem)))
  19524. (t
  19525. (narrow-to-region
  19526. (org-element-property :begin elem)
  19527. (org-element-property :end elem))))))
  19528. (defun org-transpose-element ()
  19529. "Transpose current and previous elements, keeping blank lines between.
  19530. Point is moved after both elements."
  19531. (interactive)
  19532. (org-skip-whitespace)
  19533. (let ((end (org-element-property :end (org-element-at-point))))
  19534. (org-drag-element-backward)
  19535. (goto-char end)))
  19536. (defun org-unindent-buffer ()
  19537. "Un-indent the visible part of the buffer.
  19538. Relative indentation (between items, inside blocks, etc.) isn't
  19539. modified."
  19540. (interactive)
  19541. (unless (eq major-mode 'org-mode)
  19542. (user-error "Cannot un-indent a buffer not in Org mode"))
  19543. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19544. (unindent-tree
  19545. (lambda (contents)
  19546. (dolist (element (reverse contents))
  19547. (if (memq (org-element-type element) '(headline section))
  19548. (funcall unindent-tree (org-element-contents element))
  19549. (save-excursion
  19550. (save-restriction
  19551. (narrow-to-region
  19552. (org-element-property :begin element)
  19553. (org-element-property :end element))
  19554. (org-do-remove-indentation))))))))
  19555. (funcall unindent-tree (org-element-contents parse-tree))))
  19556. (defun org-make-options-regexp (kwds &optional extra)
  19557. "Make a regular expression for keyword lines.
  19558. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19559. when non-nil, is a regexp matching keywords names."
  19560. (concat "^[ \t]*#\\+\\("
  19561. (regexp-opt kwds)
  19562. (and extra (concat (and kwds "\\|") extra))
  19563. "\\):[ \t]*\\(.*\\)"))
  19564. ;;; Conveniently switch to Info nodes
  19565. (defun org-info-find-node (&optional nodename)
  19566. "Find Info documentation NODENAME or Org documentation according context.
  19567. Started from `gnus-info-find-node'."
  19568. (interactive)
  19569. (Info-goto-node
  19570. (or nodename
  19571. (let ((default-org-info-node "(org) Top"))
  19572. (cond
  19573. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19574. ((eq 'org-mode major-mode)
  19575. (let* ((context (org-element-at-point))
  19576. (element-info-nodes ; compare to `org-element-all-elements'.
  19577. `((babel-call . "(org) Evaluating Code Blocks")
  19578. (center-block . "(org) Paragraphs")
  19579. (clock . ,default-org-info-node)
  19580. (comment . "(org) Comment Lines")
  19581. (comment-block . "(org) Comment Lines")
  19582. (diary-sexp . ,default-org-info-node)
  19583. (drawer . "(org) Drawers")
  19584. (dynamic-block . "(org) Dynamic Blocks")
  19585. (example-block . "(org) Literal Examples")
  19586. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19587. (fixed-width . ,default-org-info-node)
  19588. (footnote-definition . "(org) Creating Footnotes")
  19589. (headline . "(org) Document Structure")
  19590. (horizontal-rule . "(org) Built-in Table Editor")
  19591. (inlinetask . ,default-org-info-node)
  19592. (item . "(org) Plain Lists")
  19593. (keyword . "(org) Per-file keywords")
  19594. (latex-environment . "(org) LaTeX Export")
  19595. (node-property . "(org) Properties and Columns")
  19596. (paragraph . "(org) Paragraphs")
  19597. (plain-list . "(org) Plain Lists")
  19598. (planning . "(org) Deadlines and Scheduling")
  19599. (property-drawer . "(org) Properties and Columns")
  19600. (quote-block . "(org) Paragraphs")
  19601. (section . ,default-org-info-node)
  19602. (special-block . ,default-org-info-node)
  19603. (src-block . "(org) Working with Source Code")
  19604. (table . "(org) Tables")
  19605. (table-row . "(org) Tables")
  19606. (verse-block . "(org) Paragraphs"))))
  19607. (or (cdr (assoc (car context) element-info-nodes))
  19608. default-org-info-node)))
  19609. (t default-org-info-node))))))
  19610. ;;; Finish up
  19611. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19612. (lambda () (add-hook 'change-major-mode-hook
  19613. 'org-show-all 'append 'local)))
  19614. (provide 'org)
  19615. (run-hooks 'org-load-hook)
  19616. ;;; org.el ends here