org.el 801 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220
  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.1
  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-attach-dir "org-attach"
  111. (&optional create-if-not-exists-p no-fs-check))
  112. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  113. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  114. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  115. (declare-function org-clock-auto-clockout "org-clock" ())
  116. (declare-function org-clock-cancel "org-clock" ())
  117. (declare-function org-clock-display "org-clock" (&optional arg))
  118. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  119. (declare-function org-clock-goto "org-clock" (&optional select))
  120. (declare-function org-clock-in "org-clock" (&optional select start-time))
  121. (declare-function org-clock-in-last "org-clock" (&optional arg))
  122. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  123. (declare-function org-clock-out-if-current "org-clock" ())
  124. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  125. (declare-function org-clock-report "org-clock" (&optional arg))
  126. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  127. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  128. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  129. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  130. (declare-function org-clock-update-time-maybe "org-clock" ())
  131. (declare-function org-clocking-buffer "org-clock" ())
  132. (declare-function org-clocktable-shift "org-clock" (dir n))
  133. (declare-function org-columns-quit "org-colview" ())
  134. (declare-function org-columns-insert-dblock "org-colview" ())
  135. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  136. (declare-function org-element-at-point "org-element" ())
  137. (declare-function org-element-cache-refresh "org-element" (pos))
  138. (declare-function org-element-cache-reset "org-element" (&optional all))
  139. (declare-function org-element-contents "org-element" (element))
  140. (declare-function org-element-context "org-element" (&optional element))
  141. (declare-function org-element-copy "org-element" (datum))
  142. (declare-function org-element-create "org-element" (type &optional props &rest children))
  143. (declare-function org-element-interpret-data "org-element" (data))
  144. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  145. (declare-function org-element-link-parser "org-element" ())
  146. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  147. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  148. (declare-function org-element-property "org-element" (property element))
  149. (declare-function org-element-put-property "org-element" (element property value))
  150. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  151. (declare-function org-element-timestamp-parser "org-element" ())
  152. (declare-function org-element-type "org-element" (element))
  153. (declare-function org-export-dispatch "ox" (&optional arg))
  154. (declare-function org-export-get-backend "ox" (name))
  155. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  156. (declare-function org-feed-goto-inbox "org-feed" (feed))
  157. (declare-function org-feed-update-all "org-feed" ())
  158. (declare-function org-goto "org-goto" (&optional alternative-interface))
  159. (declare-function org-id-find-id-file "org-id" (id))
  160. (declare-function org-id-get-create "org-id" (&optional force))
  161. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  162. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  163. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  164. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  165. (declare-function org-num-mode "org-num" (&optional arg))
  166. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  167. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  168. (declare-function org-timer "org-timer" (&optional restart no-insert))
  169. (declare-function org-timer-item "org-timer" (&optional arg))
  170. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  171. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  172. (declare-function org-timer-start "org-timer" (&optional offset))
  173. (declare-function org-timer-stop "org-timer" ())
  174. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  175. (declare-function org-update-radio-target-regexp "ol" ())
  176. (defvar ffap-url-regexp)
  177. (defvar org-element-paragraph-separate)
  178. (defvar org-indent-indentation-per-level)
  179. (defvar org-radio-target-regexp)
  180. (defvar org-target-link-regexp)
  181. (defvar org-target-regexp)
  182. (defvar org-id-overriding-file-name)
  183. ;; load languages based on value of `org-babel-load-languages'
  184. (defvar org-babel-load-languages)
  185. ;;;###autoload
  186. (defun org-babel-do-load-languages (sym value)
  187. "Load the languages defined in `org-babel-load-languages'."
  188. (set-default sym value)
  189. (dolist (pair org-babel-load-languages)
  190. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  191. (if active
  192. (require (intern (concat "ob-" lang)))
  193. (fmakunbound
  194. (intern (concat "org-babel-execute:" lang)))
  195. (fmakunbound
  196. (intern (concat "org-babel-expand-body:" lang)))))))
  197. ;;;###autoload
  198. (defun org-babel-load-file (file &optional compile)
  199. "Load Emacs Lisp source code blocks in the Org FILE.
  200. This function exports the source code using `org-babel-tangle'
  201. and then loads the resulting file using `load-file'. With
  202. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  203. byte-compiled before it is loaded."
  204. (interactive "fFile to load: \nP")
  205. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  206. ;; Tangle only if the Org file is newer than the Elisp file.
  207. (unless (org-file-newer-than-p
  208. tangled-file
  209. (file-attribute-modification-time
  210. (file-attributes (file-truename file))))
  211. (org-babel-tangle-file file tangled-file "emacs-lisp\\|elisp"))
  212. (if compile
  213. (progn
  214. (byte-compile-file tangled-file)
  215. (load tangled-file)
  216. (message "Compiled and loaded %s" tangled-file))
  217. (load-file tangled-file)
  218. (message "Loaded %s" tangled-file))))
  219. (defcustom org-babel-load-languages '((emacs-lisp . t))
  220. "Languages which can be evaluated in Org buffers.
  221. \\<org-mode-map>
  222. This list can be used to load support for any of the languages
  223. below. Each language will depend on a different set of system
  224. executables and/or Emacs modes.
  225. When a language is \"loaded\", code blocks in that language can
  226. be evaluated with `org-babel-execute-src-block', which is bound
  227. by default to \\[org-ctrl-c-ctrl-c].
  228. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  229. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  230. default, only Emacs Lisp is loaded, since it has no specific
  231. requirement."
  232. :group 'org-babel
  233. :set 'org-babel-do-load-languages
  234. :version "24.1"
  235. :type '(alist :tag "Babel Languages"
  236. :key-type
  237. (choice
  238. (const :tag "Awk" awk)
  239. (const :tag "C" C)
  240. (const :tag "R" R)
  241. (const :tag "Asymptote" asymptote)
  242. (const :tag "Calc" calc)
  243. (const :tag "Clojure" clojure)
  244. (const :tag "CSS" css)
  245. (const :tag "Ditaa" ditaa)
  246. (const :tag "Dot" dot)
  247. (const :tag "Ebnf2ps" ebnf2ps)
  248. (const :tag "Emacs Lisp" emacs-lisp)
  249. (const :tag "Forth" forth)
  250. (const :tag "Fortran" fortran)
  251. (const :tag "Gnuplot" gnuplot)
  252. (const :tag "Haskell" haskell)
  253. (const :tag "hledger" hledger)
  254. (const :tag "IO" io)
  255. (const :tag "J" J)
  256. (const :tag "Java" java)
  257. (const :tag "Javascript" js)
  258. (const :tag "LaTeX" latex)
  259. (const :tag "Ledger" ledger)
  260. (const :tag "Lilypond" lilypond)
  261. (const :tag "Lisp" lisp)
  262. (const :tag "Makefile" makefile)
  263. (const :tag "Maxima" maxima)
  264. (const :tag "Matlab" matlab)
  265. (const :tag "Mscgen" mscgen)
  266. (const :tag "Ocaml" ocaml)
  267. (const :tag "Octave" octave)
  268. (const :tag "Org" org)
  269. (const :tag "Perl" perl)
  270. (const :tag "Pico Lisp" picolisp)
  271. (const :tag "PlantUML" plantuml)
  272. (const :tag "Python" python)
  273. (const :tag "Ruby" ruby)
  274. (const :tag "Sass" sass)
  275. (const :tag "Scala" scala)
  276. (const :tag "Scheme" scheme)
  277. (const :tag "Screen" screen)
  278. (const :tag "Shell Script" shell)
  279. (const :tag "Shen" shen)
  280. (const :tag "Sql" sql)
  281. (const :tag "Sqlite" sqlite)
  282. (const :tag "Stan" stan)
  283. (const :tag "Vala" vala))
  284. :value-type (boolean :tag "Activate" :value t)))
  285. ;;;; Customization variables
  286. (defcustom org-clone-delete-id nil
  287. "Remove ID property of clones of a subtree.
  288. When non-nil, clones of a subtree don't inherit the ID property.
  289. Otherwise they inherit the ID property with a new unique
  290. identifier."
  291. :type 'boolean
  292. :version "24.1"
  293. :group 'org-id)
  294. ;;; Version
  295. (org-check-version)
  296. ;;;###autoload
  297. (defun org-version (&optional here full message)
  298. "Show the Org version.
  299. Interactively, or when MESSAGE is non-nil, show it in echo area.
  300. With prefix argument, or when HERE is non-nil, insert it at point.
  301. In non-interactive uses, a reduced version string is output unless
  302. FULL is given."
  303. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  304. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  305. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  306. (load-suffixes (list ".el"))
  307. (org-install-dir
  308. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  309. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  310. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  311. (let* ((load-suffixes save-load-suffixes)
  312. (release (org-release))
  313. (git-version (org-git-version))
  314. (version (format "Org mode version %s (%s @ %s)"
  315. release
  316. git-version
  317. (if org-install-dir
  318. (if (string= org-dir org-install-dir)
  319. org-install-dir
  320. (concat "mixed installation! "
  321. org-install-dir
  322. " and "
  323. org-dir))
  324. "org-loaddefs.el can not be found!")))
  325. (version1 (if full version release)))
  326. (when here (insert version1))
  327. (when message (message "%s" version1))
  328. version1)))
  329. (defconst org-version (org-version))
  330. ;;; Syntax Constants
  331. ;;;; Comments
  332. (defconst org-comment-regexp
  333. (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
  334. "Regular expression for comment lines.")
  335. ;;;; Keyword
  336. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  337. "Regular expression for keyword-lines.")
  338. ;;;; Block
  339. (defconst org-block-regexp
  340. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  341. "Regular expression for hiding blocks.")
  342. (defconst org-dblock-start-re
  343. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  344. "Matches the start line of a dynamic block, with parameters.")
  345. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  346. "Matches the end of a dynamic block.")
  347. ;;;; Timestamp
  348. (defconst org-ts--internal-regexp
  349. (rx (seq
  350. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  351. (optional " " (*? nonl))))
  352. "Regular expression matching the innards of a time stamp.")
  353. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  354. "Regular expression for fast time stamp matching.")
  355. (defconst org-ts-regexp-inactive
  356. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  357. "Regular expression for fast inactive time stamp matching.")
  358. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  359. "Regular expression for fast time stamp matching.")
  360. (defconst org-ts-regexp0
  361. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  362. "Regular expression matching time strings for analysis.
  363. This one does not require the space after the date, so it can be used
  364. on a string that terminates immediately after the date.")
  365. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  366. "Regular expression matching time strings for analysis.")
  367. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  368. "Regular expression matching time stamps, with groups.")
  369. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  370. "Regular expression matching time stamps (also [..]), with groups.")
  371. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  372. "Regular expression matching a time stamp range.")
  373. (defconst org-tr-regexp-both
  374. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  375. "Regular expression matching a time stamp range.")
  376. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  377. org-ts-regexp "\\)?")
  378. "Regular expression matching a time stamp or time stamp range.")
  379. (defconst org-tsr-regexp-both
  380. (concat org-ts-regexp-both "\\(--?-?"
  381. org-ts-regexp-both "\\)?")
  382. "Regular expression matching a time stamp or time stamp range.
  383. The time stamps may be either active or inactive.")
  384. (defconst org-repeat-re
  385. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  386. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  387. "Regular expression for specifying repeated events.
  388. After a match, group 1 contains the repeat expression.")
  389. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  390. "Formats for `format-time-string' which are used for time stamps.")
  391. ;;;; Clock and Planning
  392. (defconst org-clock-string "CLOCK:"
  393. "String used as prefix for timestamps clocking work hours on an item.")
  394. (defvar org-closed-string "CLOSED:"
  395. "String used as the prefix for timestamps logging closing a TODO entry.")
  396. (defvar org-deadline-string "DEADLINE:"
  397. "String to mark deadline entries.
  398. \\<org-mode-map>
  399. A deadline is this string, followed by a time stamp. It must be
  400. a word, terminated by a colon. You can insert a schedule keyword
  401. and a timestamp with `\\[org-deadline]'.")
  402. (defvar org-scheduled-string "SCHEDULED:"
  403. "String to mark scheduled TODO entries.
  404. \\<org-mode-map>
  405. A schedule is this string, followed by a time stamp. It must be
  406. a word, terminated by a colon. You can insert a schedule keyword
  407. and a timestamp with `\\[org-schedule]'.")
  408. (defconst org-ds-keyword-length
  409. (+ 2
  410. (apply #'max
  411. (mapcar #'length
  412. (list org-deadline-string org-scheduled-string
  413. org-clock-string org-closed-string))))
  414. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  415. (defconst org-planning-line-re
  416. (concat "^[ \t]*"
  417. (regexp-opt
  418. (list org-closed-string org-deadline-string org-scheduled-string)
  419. t))
  420. "Matches a line with planning info.
  421. Matched keyword is in group 1.")
  422. (defconst org-clock-line-re
  423. (concat "^[ \t]*" org-clock-string)
  424. "Matches a line with clock info.")
  425. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  426. "Matches the DEADLINE keyword.")
  427. (defconst org-deadline-time-regexp
  428. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  429. "Matches the DEADLINE keyword together with a time stamp.")
  430. (defconst org-deadline-time-hour-regexp
  431. (concat "\\<" org-deadline-string
  432. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  433. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  434. (defconst org-deadline-line-regexp
  435. (concat "\\<\\(" org-deadline-string "\\).*")
  436. "Matches the DEADLINE keyword and the rest of the line.")
  437. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  438. "Matches the SCHEDULED keyword.")
  439. (defconst org-scheduled-time-regexp
  440. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  441. "Matches the SCHEDULED keyword together with a time stamp.")
  442. (defconst org-scheduled-time-hour-regexp
  443. (concat "\\<" org-scheduled-string
  444. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  445. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  446. (defconst org-closed-time-regexp
  447. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  448. "Matches the CLOSED keyword together with a time stamp.")
  449. (defconst org-keyword-time-regexp
  450. (concat "\\<"
  451. (regexp-opt
  452. (list org-scheduled-string org-deadline-string org-closed-string
  453. org-clock-string)
  454. t)
  455. " *[[<]\\([^]>]+\\)[]>]")
  456. "Matches any of the 4 keywords, together with the time stamp.")
  457. (defconst org-keyword-time-not-clock-regexp
  458. (concat
  459. "\\<"
  460. (regexp-opt
  461. (list org-scheduled-string org-deadline-string org-closed-string) t)
  462. " *[[<]\\([^]>]+\\)[]>]")
  463. "Matches any of the 3 keywords, together with the time stamp.")
  464. (defconst org-all-time-keywords
  465. (mapcar (lambda (w) (substring w 0 -1))
  466. (list org-scheduled-string org-deadline-string
  467. org-clock-string org-closed-string))
  468. "List of time keywords.")
  469. ;;;; Drawer
  470. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  471. "Matches first or last line of a hidden block.
  472. Group 1 contains drawer's name or \"END\".")
  473. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  474. "Regular expression matching the first line of a property drawer.")
  475. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  476. "Regular expression matching the last line of a property drawer.")
  477. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  478. "Regular expression matching the first line of a clock drawer.")
  479. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  480. "Regular expression matching the last line of a clock drawer.")
  481. (defconst org-logbook-drawer-re
  482. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  483. (*? (0+ nonl) "\n")
  484. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  485. "Matches an entire LOGBOOK drawer.")
  486. (defconst org-property-drawer-re
  487. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  488. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  489. "[ \t]*:END:[ \t]*$")
  490. "Matches an entire property drawer.")
  491. (defconst org-clock-drawer-re
  492. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  493. org-clock-drawer-end-re "\\)\n?")
  494. "Matches an entire clock drawer.")
  495. ;;;; Headline
  496. (defconst org-heading-keyword-regexp-format
  497. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  498. "Printf format for a regexp matching a headline with some keyword.
  499. This regexp will match the headline of any node which has the
  500. exact keyword that is put into the format. The keyword isn't in
  501. any group by default, but the stars and the body are.")
  502. (defconst org-heading-keyword-maybe-regexp-format
  503. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  504. "Printf format for a regexp matching a headline, possibly with some keyword.
  505. This regexp can match any headline with the specified keyword, or
  506. without a keyword. The keyword isn't in any group by default,
  507. but the stars and the body are.")
  508. (defconst org-archive-tag "ARCHIVE"
  509. "The tag that marks a subtree as archived.
  510. An archived subtree does not open during visibility cycling, and does
  511. not contribute to the agenda listings.")
  512. (defconst org-tag-re "[[:alnum:]_@#%]+"
  513. "Regexp matching a single tag.")
  514. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  515. "Regexp matching the tag group at the end of a line, with leading spaces.
  516. Tags are stored in match group 1. Match group 2 stores the tags
  517. without the enclosing colons.")
  518. (defconst org-tag-line-re
  519. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  520. "Regexp matching tags in a headline.
  521. Tags are stored in match group 1. Match group 2 stores the tags
  522. without the enclosing colons.")
  523. (eval-and-compile
  524. (defconst org-comment-string "COMMENT"
  525. "Entries starting with this keyword will never be exported.
  526. \\<org-mode-map>
  527. An entry can be toggled between COMMENT and normal with
  528. `\\[org-toggle-comment]'."))
  529. ;;;; LaTeX Environments and Fragments
  530. (defconst org-latex-regexps
  531. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  532. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  533. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  534. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  535. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  536. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  537. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  538. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  539. "Regular expressions for matching embedded LaTeX.")
  540. ;;;; Node Property
  541. (defconst org-effort-property "Effort"
  542. "The property that is being used to keep track of effort estimates.
  543. Effort estimates given in this property need to be in the format
  544. defined in org-duration.el.")
  545. ;;; The custom variables
  546. (defgroup org nil
  547. "Outline-based notes management and organizer."
  548. :tag "Org"
  549. :group 'outlines
  550. :group 'calendar)
  551. (defcustom org-mode-hook nil
  552. "Mode hook for Org mode, run after the mode was turned on."
  553. :group 'org
  554. :type 'hook)
  555. (defcustom org-load-hook nil
  556. "Hook that is run after org.el has been loaded."
  557. :group 'org
  558. :type 'hook)
  559. (defcustom org-log-buffer-setup-hook nil
  560. "Hook that is run after an Org log buffer is created."
  561. :group 'org
  562. :version "24.1"
  563. :type 'hook)
  564. (defvar org-modules) ; defined below
  565. (defvar org-modules-loaded nil
  566. "Have the modules been loaded already?")
  567. ;;;###autoload
  568. (defun org-load-modules-maybe (&optional force)
  569. "Load all extensions listed in `org-modules'."
  570. (when (or force (not org-modules-loaded))
  571. (dolist (ext org-modules)
  572. (condition-case nil (require ext)
  573. (error (message "Problems while trying to load feature `%s'" ext))))
  574. (setq org-modules-loaded t)))
  575. (defun org-set-modules (var value)
  576. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  577. (set var value)
  578. (when (featurep 'org)
  579. (org-load-modules-maybe 'force)
  580. (org-element-cache-reset 'all)))
  581. (defcustom org-modules '(ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  582. "Modules that should always be loaded together with org.el.
  583. If a description starts with <C>, the file is not part of Emacs
  584. and loading it will require that you have downloaded and properly
  585. installed the Org mode distribution.
  586. You can also use this system to load external packages (i.e. neither Org
  587. core modules, nor modules from the CONTRIB directory). Just add symbols
  588. to the end of the list. If the package is called org-xyz.el, then you need
  589. to add the symbol `xyz', and the package must have a call to:
  590. (provide \\='org-xyz)
  591. For export specific modules, see also `org-export-backends'."
  592. :group 'org
  593. :set 'org-set-modules
  594. :version "26.1"
  595. :package-version '(Org . "9.2")
  596. :type
  597. '(set :greedy t
  598. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  599. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  600. (const :tag " crypt: Encryption of subtrees" org-crypt)
  601. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  602. (const :tag " docview: Links to Docview buffers" ol-docview)
  603. (const :tag " eww: Store link to URL of Eww" ol-eww)
  604. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  605. (const :tag " habit: Track your consistency with habits" org-habit)
  606. (const :tag " id: Global IDs for identifying entries" org-id)
  607. (const :tag " info: Links to Info nodes" ol-info)
  608. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  609. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  610. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  611. (const :tag " mouse: Additional mouse support" org-mouse)
  612. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  613. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  614. (const :tag " tempo: Fast completion for structures" org-tempo)
  615. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  616. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  617. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  618. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  619. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  620. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  621. (const :tag "C collector: Collect properties into tables" org-collector)
  622. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  623. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  624. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  625. (const :tag "C eval: Include command output as text" org-eval)
  626. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  627. (const :tag "C git-link: Links to specific file version" ol-git-link)
  628. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  629. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  630. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  631. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  632. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  633. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  634. (const :tag "C man: Links to man pages in Org mode" ol-man)
  635. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  636. (const :tag "C notify: Notifications for Org mode" org-notify)
  637. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  638. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  639. (const :tag "C registry: A registry for Org links" org-registry)
  640. (const :tag "C screen: Visit screen sessions through links" org-screen)
  641. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  642. (const :tag "C secretary: Team management with Org" org-secretary)
  643. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  644. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  645. (const :tag "C track: Keep up with Org mode development" org-track)
  646. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  647. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  648. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  649. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  650. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  651. (defvar org-export-registered-backends) ; From ox.el.
  652. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  653. (declare-function org-export-backend-name "ox" (backend) t)
  654. (defcustom org-export-backends '(ascii html icalendar latex odt)
  655. "List of export back-ends that should be always available.
  656. If a description starts with <C>, the file is not part of Emacs
  657. and loading it will require that you have downloaded and properly
  658. installed the Org mode distribution.
  659. Unlike to `org-modules', libraries in this list will not be
  660. loaded along with Org, but only once the export framework is
  661. needed.
  662. This variable needs to be set before org.el is loaded. If you
  663. need to make a change while Emacs is running, use the customize
  664. interface or run the following code, where VAL stands for the new
  665. value of the variable, after updating it:
  666. (progn
  667. (setq org-export-registered-backends
  668. (cl-remove-if-not
  669. (lambda (backend)
  670. (let ((name (org-export-backend-name backend)))
  671. (or (memq name val)
  672. (catch \\='parentp
  673. (dolist (b val)
  674. (and (org-export-derived-backend-p b name)
  675. (throw \\='parentp t)))))))
  676. org-export-registered-backends))
  677. (let ((new-list (mapcar #\\='org-export-backend-name
  678. org-export-registered-backends)))
  679. (dolist (backend val)
  680. (cond
  681. ((not (load (format \"ox-%s\" backend) t t))
  682. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  683. backend))
  684. ((not (memq backend new-list)) (push backend new-list))))
  685. (set-default \\='org-export-backends new-list)))
  686. Adding a back-end to this list will also pull the back-end it
  687. depends on, if any."
  688. :group 'org
  689. :group 'org-export
  690. :version "26.1"
  691. :package-version '(Org . "9.0")
  692. :initialize 'custom-initialize-set
  693. :set (lambda (var val)
  694. (if (not (featurep 'ox)) (set-default var val)
  695. ;; Any back-end not required anymore (not present in VAL and not
  696. ;; a parent of any back-end in the new value) is removed from the
  697. ;; list of registered back-ends.
  698. (setq org-export-registered-backends
  699. (cl-remove-if-not
  700. (lambda (backend)
  701. (let ((name (org-export-backend-name backend)))
  702. (or (memq name val)
  703. (catch 'parentp
  704. (dolist (b val)
  705. (and (org-export-derived-backend-p b name)
  706. (throw 'parentp t)))))))
  707. org-export-registered-backends))
  708. ;; Now build NEW-LIST of both new back-ends and required
  709. ;; parents.
  710. (let ((new-list (mapcar #'org-export-backend-name
  711. org-export-registered-backends)))
  712. (dolist (backend val)
  713. (cond
  714. ((not (load (format "ox-%s" backend) t t))
  715. (message "Problems while trying to load export back-end `%s'"
  716. backend))
  717. ((not (memq backend new-list)) (push backend new-list))))
  718. ;; Set VAR to that list with fixed dependencies.
  719. (set-default var new-list))))
  720. :type '(set :greedy t
  721. (const :tag " ascii Export buffer to ASCII format" ascii)
  722. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  723. (const :tag " html Export buffer to HTML format" html)
  724. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  725. (const :tag " latex Export buffer to LaTeX format" latex)
  726. (const :tag " man Export buffer to MAN format" man)
  727. (const :tag " md Export buffer to Markdown format" md)
  728. (const :tag " odt Export buffer to ODT format" odt)
  729. (const :tag " org Export buffer to Org format" org)
  730. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  731. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  732. (const :tag "C deck Export buffer to deck.js presentations" deck)
  733. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  734. (const :tag "C groff Export buffer to Groff format" groff)
  735. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  736. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  737. (const :tag "C s5 Export buffer to s5 presentations" s5)
  738. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  739. (eval-after-load 'ox
  740. '(dolist (backend org-export-backends)
  741. (condition-case nil (require (intern (format "ox-%s" backend)))
  742. (error (message "Problems while trying to load export back-end `%s'"
  743. backend)))))
  744. (defcustom org-support-shift-select nil
  745. "Non-nil means make shift-cursor commands select text when possible.
  746. \\<org-mode-map>
  747. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  748. start selecting a region, or enlarge regions started in this way.
  749. In Org mode, in special contexts, these same keys are used for
  750. other purposes, important enough to compete with shift selection.
  751. Org tries to balance these needs by supporting `shift-select-mode'
  752. outside these special contexts, under control of this variable.
  753. The default of this variable is nil, to avoid confusing behavior. Shifted
  754. cursor keys will then execute Org commands in the following contexts:
  755. - on a headline, changing TODO state (left/right) and priority (up/down)
  756. - on a time stamp, changing the time
  757. - in a plain list item, changing the bullet type
  758. - in a property definition line, switching between allowed values
  759. - in the BEGIN line of a clock table (changing the time block).
  760. - in a table, moving the cell in the specified direction.
  761. Outside these contexts, the commands will throw an error.
  762. When this variable is t and the cursor is not in a special
  763. context, Org mode will support shift-selection for making and
  764. enlarging regions. To make this more effective, the bullet
  765. cycling will no longer happen anywhere in an item line, but only
  766. if the cursor is exactly on the bullet.
  767. If you set this variable to the symbol `always', then the keys
  768. will not be special in headlines, property lines, item lines, and
  769. table cells, to make shift selection work there as well. If this is
  770. what you want, you can use the following alternative commands:
  771. `\\[org-todo]' and `\\[org-priority]' \
  772. to change TODO state and priority,
  773. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  774. can be used to switch TODO sets,
  775. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  776. and properties can be edited by hand or in column view.
  777. However, when the cursor is on a timestamp, shift-cursor commands
  778. will still edit the time stamp - this is just too good to give up."
  779. :group 'org
  780. :type '(choice
  781. (const :tag "Never" nil)
  782. (const :tag "When outside special context" t)
  783. (const :tag "Everywhere except timestamps" always)))
  784. (defcustom org-loop-over-headlines-in-active-region t
  785. "Shall some commands act upon headlines in the active region?
  786. When set to t, some commands will be performed in all headlines
  787. within the active region.
  788. When set to `start-level', some commands will be performed in all
  789. headlines within the active region, provided that these headlines
  790. are of the same level than the first one.
  791. When set to a string, those commands will be performed on the
  792. matching headlines within the active region. Such string must be
  793. a tags/property/todo match as it is used in the agenda tags view.
  794. The list of commands is: `org-schedule', `org-deadline',
  795. `org-todo', `org-set-tags-command', `org-archive-subtree',
  796. `org-archive-set-tag', `org-toggle-archive-tag' and
  797. `org-archive-to-archive-sibling'. The archiving commands skip
  798. already archived entries.
  799. See `org-agenda-loop-over-headlines-in-active-region' for the
  800. equivalent option for agenda views."
  801. :type '(choice (const :tag "Don't loop" nil)
  802. (const :tag "All headlines in active region" t)
  803. (const :tag "In active region, headlines at the same level than the first one" start-level)
  804. (string :tag "Tags/Property/Todo matcher"))
  805. :package-version '(Org . "9.4")
  806. :group 'org-todo
  807. :group 'org-archive)
  808. (defcustom org-startup-folded 'showeverything
  809. "Non-nil means entering Org mode will switch to OVERVIEW.
  810. This can also be configured on a per-file basis by adding one of
  811. the following lines anywhere in the buffer:
  812. #+STARTUP: fold (or `overview', this is equivalent)
  813. #+STARTUP: nofold (or `showall', this is equivalent)
  814. #+STARTUP: content
  815. #+STARTUP: showeverything
  816. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  817. to ignore this option when Org opens agenda files for the first
  818. time."
  819. :group 'org-startup
  820. :package-version '(Org . "9.4")
  821. :type '(choice
  822. (const :tag "nofold: show all" nil)
  823. (const :tag "fold: overview" t)
  824. (const :tag "content: all headlines" content)
  825. (const :tag "show everything, even drawers" showeverything)))
  826. (defcustom org-startup-truncated t
  827. "Non-nil means entering Org mode will set `truncate-lines'.
  828. This is useful since some lines containing links can be very long and
  829. uninteresting. Also tables look terrible when wrapped.
  830. The variable `org-startup-truncated' allows to configure
  831. truncation for Org mode different to the other modes that use the
  832. variable `truncate-lines' and as a shortcut instead of putting
  833. the variable `truncate-lines' into the `org-mode-hook'. If one
  834. wants to configure truncation for Org mode not statically but
  835. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  836. the variable `truncate-lines' has to be used because in such a
  837. case it is too late to set the variable `org-startup-truncated'."
  838. :group 'org-startup
  839. :type 'boolean)
  840. (defcustom org-startup-indented nil
  841. "Non-nil means turn on `org-indent-mode' on startup.
  842. This can also be configured on a per-file basis by adding one of
  843. the following lines anywhere in the buffer:
  844. #+STARTUP: indent
  845. #+STARTUP: noindent"
  846. :group 'org-structure
  847. :type '(choice
  848. (const :tag "Not" nil)
  849. (const :tag "Globally (slow on startup in large files)" t)))
  850. (defcustom org-startup-numerated nil
  851. "Non-nil means turn on `org-num-mode' on startup.
  852. This can also be configured on a per-file basis by adding one of
  853. the following lines anywhere in the buffer:
  854. #+STARTUP: num
  855. #+STARTUP: nonum"
  856. :group 'org-structure
  857. :package-version '(Org . "9.4")
  858. :type '(choice
  859. (const :tag "Not" nil)
  860. (const :tag "Globally" t)))
  861. (defcustom org-use-sub-superscripts t
  862. "Non-nil means interpret \"_\" and \"^\" for display.
  863. If you want to control how Org exports those characters, see
  864. `org-export-with-sub-superscripts'.
  865. When this option is turned on, you can use TeX-like syntax for
  866. sub- and superscripts within the buffer. Several characters after
  867. \"_\" or \"^\" will be considered as a single item - so grouping
  868. with {} is normally not needed. For example, the following things
  869. will be parsed as single sub- or superscripts:
  870. 10^24 or 10^tau several digits will be considered 1 item.
  871. 10^-12 or 10^-tau a leading sign with digits or a word
  872. x^2-y^3 will be read as x^2 - y^3, because items are
  873. terminated by almost any nonword/nondigit char.
  874. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  875. Still, ambiguity is possible. So when in doubt, use {} to enclose
  876. the sub/superscript. If you set this variable to the symbol `{}',
  877. the braces are *required* in order to trigger interpretations as
  878. sub/superscript. This can be helpful in documents that need \"_\"
  879. frequently in plain text."
  880. :group 'org-startup
  881. :version "24.4"
  882. :package-version '(Org . "8.0")
  883. :type '(choice
  884. (const :tag "Always interpret" t)
  885. (const :tag "Only with braces" {})
  886. (const :tag "Never interpret" nil)))
  887. (defcustom org-startup-with-beamer-mode nil
  888. "Non-nil means turn on `org-beamer-mode' on startup.
  889. This can also be configured on a per-file basis by adding one of
  890. the following lines anywhere in the buffer:
  891. #+STARTUP: beamer"
  892. :group 'org-startup
  893. :version "24.1"
  894. :type 'boolean)
  895. (defcustom org-startup-align-all-tables nil
  896. "Non-nil means align all tables when visiting a file.
  897. This can also be configured on a per-file basis by adding one of
  898. the following lines anywhere in the buffer:
  899. #+STARTUP: align
  900. #+STARTUP: noalign"
  901. :group 'org-startup
  902. :type 'boolean)
  903. (defcustom org-startup-shrink-all-tables nil
  904. "Non-nil means shrink all table columns with a width cookie.
  905. This can also be configured on a per-file basis by adding one of
  906. the following lines anywhere in the buffer:
  907. #+STARTUP: shrink"
  908. :group 'org-startup
  909. :type 'boolean
  910. :version "27.1"
  911. :package-version '(Org . "9.2")
  912. :safe #'booleanp)
  913. (defcustom org-startup-with-inline-images nil
  914. "Non-nil means show inline images when loading a new Org file.
  915. This can also be configured on a per-file basis by adding one of
  916. the following lines anywhere in the buffer:
  917. #+STARTUP: inlineimages
  918. #+STARTUP: noinlineimages"
  919. :group 'org-startup
  920. :version "24.1"
  921. :type 'boolean)
  922. (defcustom org-startup-with-latex-preview nil
  923. "Non-nil means preview LaTeX fragments when loading a new Org file.
  924. This can also be configured on a per-file basis by adding one of
  925. the following lines anywhere in the buffer:
  926. #+STARTUP: latexpreview
  927. #+STARTUP: nolatexpreview"
  928. :group 'org-startup
  929. :version "24.4"
  930. :package-version '(Org . "8.0")
  931. :type 'boolean)
  932. (defcustom org-insert-mode-line-in-empty-file nil
  933. "Non-nil means insert the first line setting Org mode in empty files.
  934. When the function `org-mode' is called interactively in an empty file, this
  935. normally means that the file name does not automatically trigger Org mode.
  936. To ensure that the file will always be in Org mode in the future, a
  937. line enforcing Org mode will be inserted into the buffer, if this option
  938. has been set."
  939. :group 'org-startup
  940. :type 'boolean)
  941. (defcustom org-ellipsis nil
  942. "The ellipsis to use in the Org mode outline.
  943. When nil, just use the standard three dots. When a non-empty string,
  944. use that string instead.
  945. The change affects only Org mode (which will then use its own display table).
  946. Changing this requires executing `\\[org-mode]' in a buffer to become
  947. effective. It cannot be set as a local variable."
  948. :group 'org-startup
  949. :type '(choice (const :tag "Default" nil)
  950. (string :tag "String" :value "...#")))
  951. (defvar org-display-table nil
  952. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  953. (defcustom org-directory "~/org"
  954. "Directory with Org files.
  955. This is just a default location to look for Org files. There is no need
  956. at all to put your files into this directory. It is used in the
  957. following situations:
  958. 1. When a capture template specifies a target file that is not an
  959. absolute path. The path will then be interpreted relative to
  960. `org-directory'
  961. 2. When the value of variable `org-agenda-files' is a single file, any
  962. relative paths in this file will be taken as relative to
  963. `org-directory'."
  964. :group 'org-refile
  965. :group 'org-capture
  966. :type 'directory)
  967. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  968. "Default target for storing notes.
  969. Used as a fall back file for org-capture.el, for templates that
  970. do not specify a target file."
  971. :group 'org-refile
  972. :group 'org-capture
  973. :type 'file)
  974. (defcustom org-reverse-note-order nil
  975. "Non-nil means store new notes at the beginning of a file or entry.
  976. When nil, new notes will be filed to the end of a file or entry.
  977. This can also be a list with cons cells of regular expressions that
  978. are matched against file names, and values."
  979. :group 'org-capture
  980. :group 'org-refile
  981. :type '(choice
  982. (const :tag "Reverse always" t)
  983. (const :tag "Reverse never" nil)
  984. (repeat :tag "By file name regexp"
  985. (cons regexp boolean))))
  986. (defgroup org-keywords nil
  987. "Keywords in Org mode."
  988. :tag "Org Keywords"
  989. :group 'org)
  990. (defcustom org-closed-keep-when-no-todo nil
  991. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  992. :group 'org-todo
  993. :group 'org-keywords
  994. :version "24.4"
  995. :package-version '(Org . "8.0")
  996. :type 'boolean)
  997. (defgroup org-structure nil
  998. "Options concerning the general structure of Org files."
  999. :tag "Org Structure"
  1000. :group 'org)
  1001. (defgroup org-reveal-location nil
  1002. "Options about how to make context of a location visible."
  1003. :tag "Org Reveal Location"
  1004. :group 'org-structure)
  1005. (defcustom org-show-context-detail '((agenda . local)
  1006. (bookmark-jump . lineage)
  1007. (isearch . lineage)
  1008. (default . ancestors))
  1009. "Alist between context and visibility span when revealing a location.
  1010. \\<org-mode-map>Some actions may move point into invisible
  1011. locations. As a consequence, Org always exposes a neighborhood
  1012. around point. How much is shown depends on the initial action,
  1013. or context. Valid contexts are
  1014. agenda when exposing an entry from the agenda
  1015. org-goto when using the command `org-goto' (`\\[org-goto]')
  1016. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1017. tags-tree when constructing a sparse tree based on tags matches
  1018. link-search when exposing search matches associated with a link
  1019. mark-goto when exposing the jump goal of a mark
  1020. bookmark-jump when exposing a bookmark location
  1021. isearch when exiting from an incremental search
  1022. default default for all contexts not set explicitly
  1023. Allowed visibility spans are
  1024. minimal show current headline; if point is not on headline,
  1025. also show entry
  1026. local show current headline, entry and next headline
  1027. ancestors show current headline and its direct ancestors; if
  1028. point is not on headline, also show entry
  1029. lineage show current headline, its direct ancestors and all
  1030. their children; if point is not on headline, also show
  1031. entry and first child
  1032. tree show current headline, its direct ancestors and all
  1033. their children; if point is not on headline, also show
  1034. entry and all children
  1035. canonical show current headline, its direct ancestors along with
  1036. their entries and children; if point is not located on
  1037. the headline, also show current entry and all children
  1038. As special cases, a nil or t value means show all contexts in
  1039. `minimal' or `canonical' view, respectively.
  1040. Some views can make displayed information very compact, but also
  1041. make it harder to edit the location of the match. In such
  1042. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1043. more context."
  1044. :group 'org-reveal-location
  1045. :version "26.1"
  1046. :package-version '(Org . "9.0")
  1047. :type '(choice
  1048. (const :tag "Canonical" t)
  1049. (const :tag "Minimal" nil)
  1050. (repeat :greedy t :tag "Individual contexts"
  1051. (cons
  1052. (choice :tag "Context"
  1053. (const agenda)
  1054. (const org-goto)
  1055. (const occur-tree)
  1056. (const tags-tree)
  1057. (const link-search)
  1058. (const mark-goto)
  1059. (const bookmark-jump)
  1060. (const isearch)
  1061. (const default))
  1062. (choice :tag "Detail level"
  1063. (const minimal)
  1064. (const local)
  1065. (const ancestors)
  1066. (const lineage)
  1067. (const tree)
  1068. (const canonical))))))
  1069. (defcustom org-indirect-buffer-display 'other-window
  1070. "How should indirect tree buffers be displayed?
  1071. This applies to indirect buffers created with the commands
  1072. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1073. Valid values are:
  1074. current-window Display in the current window
  1075. other-window Just display in another window.
  1076. dedicated-frame Create one new frame, and re-use it each time.
  1077. new-frame Make a new frame each time. Note that in this case
  1078. previously-made indirect buffers are kept, and you need to
  1079. kill these buffers yourself."
  1080. :group 'org-structure
  1081. :group 'org-agenda-windows
  1082. :type '(choice
  1083. (const :tag "In current window" current-window)
  1084. (const :tag "In current frame, other window" other-window)
  1085. (const :tag "Each time a new frame" new-frame)
  1086. (const :tag "One dedicated frame" dedicated-frame)))
  1087. (defconst org-file-apps-gnu
  1088. '((remote . emacs)
  1089. (system . mailcap)
  1090. (t . mailcap))
  1091. "Default file applications on a UNIX or GNU/Linux system.
  1092. See `org-file-apps'.")
  1093. (defconst org-file-apps-macos
  1094. '((remote . emacs)
  1095. (system . "open %s")
  1096. ("ps.gz" . "gv %s")
  1097. ("eps.gz" . "gv %s")
  1098. ("dvi" . "xdvi %s")
  1099. ("fig" . "xfig %s")
  1100. (t . "open %s"))
  1101. "Default file applications on a macOS system.
  1102. The system \"open\" is known as a default, but we use X11 applications
  1103. for some files for which the OS does not have a good default.
  1104. See `org-file-apps'.")
  1105. (defconst org-file-apps-windowsnt
  1106. (list '(remote . emacs)
  1107. (cons 'system (lambda (file _path)
  1108. (with-no-warnings (w32-shell-execute "open" file))))
  1109. (cons t (lambda (file _path)
  1110. (with-no-warnings (w32-shell-execute "open" file)))))
  1111. "Default file applications on a Windows NT system.
  1112. The system \"open\" is used for most files.
  1113. See `org-file-apps'.")
  1114. (defcustom org-file-apps
  1115. '((auto-mode . emacs)
  1116. (directory . emacs)
  1117. ("\\.mm\\'" . default)
  1118. ("\\.x?html?\\'" . default)
  1119. ("\\.pdf\\'" . default))
  1120. "Applications for opening `file:path' items in a document.
  1121. \\<org-mode-map>
  1122. Org mode uses system defaults for different file types, but you
  1123. can use this variable to set the application for a given file
  1124. extension. The entries in this list are cons cells where the car
  1125. identifies files and the cdr the corresponding command.
  1126. Possible values for the file identifier are:
  1127. \"string\" A string as a file identifier can be interpreted in different
  1128. ways, depending on its contents:
  1129. - Alphanumeric characters only:
  1130. Match links with this file extension.
  1131. Example: (\"pdf\" . \"evince %s\")
  1132. to open PDFs with evince.
  1133. - Regular expression: Match links where the
  1134. filename matches the regexp. If you want to
  1135. use groups here, use shy groups.
  1136. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1137. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1138. to open *.html and *.xhtml with firefox.
  1139. - Regular expression which contains (non-shy) groups:
  1140. Match links where the whole link, including \"::\", and
  1141. anything after that, matches the regexp.
  1142. In a custom command string, %1, %2, etc. are replaced with
  1143. the parts of the link that were matched by the groups.
  1144. For backwards compatibility, if a command string is given
  1145. that does not use any of the group matches, this case is
  1146. handled identically to the second one (i.e. match against
  1147. file name only).
  1148. In a custom function, you can access the group matches with
  1149. (match-string n link).
  1150. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1151. \"evince -p %1 %s\")
  1152. to open [[file:document.pdf::5]] with evince at page 5.
  1153. `directory' Matches a directory
  1154. `remote' Matches a remote file, accessible through tramp or efs.
  1155. Remote files most likely should be visited through Emacs
  1156. because external applications cannot handle such paths.
  1157. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1158. so all files Emacs knows how to handle. Using this with
  1159. command `emacs' will open most files in Emacs. Beware that this
  1160. will also open html files inside Emacs, unless you add
  1161. (\"html\" . default) to the list as well.
  1162. `system' The system command to open files, like `open' on Windows
  1163. and macOS, and mailcap under GNU/Linux. This is the command
  1164. that will be selected if you call `org-open-at-point' with a
  1165. double prefix argument (`\\[universal-argument] \
  1166. \\[universal-argument] \\[org-open-at-point]').
  1167. t Default for files not matched by any of the other options.
  1168. Possible values for the command are:
  1169. `emacs' The file will be visited by the current Emacs process.
  1170. `default' Use the default application for this file type, which is the
  1171. association for t in the list, most likely in the system-specific
  1172. part. This can be used to overrule an unwanted setting in the
  1173. system-specific variable.
  1174. `system' Use the system command for opening files, like \"open\".
  1175. This command is specified by the entry whose car is `system'.
  1176. Most likely, the system-specific version of this variable
  1177. does define this command, but you can overrule/replace it
  1178. here.
  1179. `mailcap' Use command specified in the mailcaps.
  1180. string A command to be executed by a shell; %s will be replaced
  1181. by the path to the file.
  1182. function A Lisp function, which will be called with two arguments:
  1183. the file path and the original link string, without the
  1184. \"file:\" prefix.
  1185. For more examples, see the system specific constants
  1186. `org-file-apps-macos'
  1187. `org-file-apps-windowsnt'
  1188. `org-file-apps-gnu'."
  1189. :group 'org
  1190. :package-version '(Org . "9.4")
  1191. :type '(repeat
  1192. (cons (choice :value ""
  1193. (string :tag "Extension")
  1194. (const :tag "System command to open files" system)
  1195. (const :tag "Default for unrecognized files" t)
  1196. (const :tag "Remote file" remote)
  1197. (const :tag "Links to a directory" directory)
  1198. (const :tag "Any files that have Emacs modes"
  1199. auto-mode))
  1200. (choice :value ""
  1201. (const :tag "Visit with Emacs" emacs)
  1202. (const :tag "Use default" default)
  1203. (const :tag "Use the system command" system)
  1204. (string :tag "Command")
  1205. (function :tag "Function")))))
  1206. (defcustom org-open-non-existing-files nil
  1207. "Non-nil means `org-open-file' opens non-existing files.
  1208. When nil, an error is thrown.
  1209. This variable applies only to external applications because they
  1210. might choke on non-existing files. If the link is to a file that
  1211. will be opened in Emacs, the variable is ignored."
  1212. :group 'org
  1213. :type 'boolean
  1214. :safe #'booleanp)
  1215. (defcustom org-open-directory-means-index-dot-org nil
  1216. "When non-nil a link to a directory really means to \"index.org\".
  1217. When nil, following a directory link runs Dired or opens
  1218. a finder/explorer window on that directory."
  1219. :group 'org
  1220. :type 'boolean
  1221. :safe #'booleanp)
  1222. (defcustom org-bookmark-names-plist
  1223. '(:last-capture "org-capture-last-stored"
  1224. :last-refile "org-refile-last-stored"
  1225. :last-capture-marker "org-capture-last-stored-marker")
  1226. "Names for bookmarks automatically set by some Org commands.
  1227. This can provide strings as names for a number of bookmarks Org sets
  1228. automatically. The following keys are currently implemented:
  1229. :last-capture
  1230. :last-capture-marker
  1231. :last-refile
  1232. When a key does not show up in the property list, the corresponding bookmark
  1233. is not set."
  1234. :group 'org-structure
  1235. :type 'plist)
  1236. (defgroup org-cycle nil
  1237. "Options concerning visibility cycling in Org mode."
  1238. :tag "Org Cycle"
  1239. :group 'org-structure)
  1240. (defcustom org-cycle-skip-children-state-if-no-children t
  1241. "Non-nil means skip CHILDREN state in entries that don't have any."
  1242. :group 'org-cycle
  1243. :type 'boolean)
  1244. (defcustom org-cycle-max-level nil
  1245. "Maximum level which should still be subject to visibility cycling.
  1246. Levels higher than this will, for cycling, be treated as text, not a headline.
  1247. When `org-odd-levels-only' is set, a value of N in this variable actually
  1248. means 2N-1 stars as the limiting headline.
  1249. When nil, cycle all levels.
  1250. Note that the limiting level of cycling is also influenced by
  1251. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1252. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1253. than its value."
  1254. :group 'org-cycle
  1255. :type '(choice
  1256. (const :tag "No limit" nil)
  1257. (integer :tag "Maximum level")))
  1258. (defcustom org-hide-block-startup nil
  1259. "Non-nil means entering Org mode will fold all blocks.
  1260. This can also be set in on a per-file basis with
  1261. #+STARTUP: hideblocks
  1262. #+STARTUP: showblocks"
  1263. :group 'org-startup
  1264. :group 'org-cycle
  1265. :type 'boolean)
  1266. (defcustom org-cycle-global-at-bob nil
  1267. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1268. This makes it possible to do global cycling without having to use `S-TAB'
  1269. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1270. line of the buffer
  1271. must not be a headline -- it may be empty or some other text.
  1272. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1273. sure the cursor stays at the beginning of the buffer.
  1274. When this option is nil, don't do anything special at the beginning of
  1275. the buffer."
  1276. :group 'org-cycle
  1277. :type 'boolean)
  1278. (defcustom org-cycle-level-after-item/entry-creation t
  1279. "Non-nil means cycle entry level or item indentation in new empty entries.
  1280. When the cursor is at the end of an empty headline, i.e., with only stars
  1281. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1282. and then all possible ancestor states, before returning to the original state.
  1283. This makes data entry extremely fast: M-RET to create a new headline,
  1284. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1285. When the cursor is at the end of an empty plain list item, one TAB will
  1286. make it a subitem, two or more tabs will back up to make this an item
  1287. higher up in the item hierarchy."
  1288. :group 'org-cycle
  1289. :type 'boolean)
  1290. (defcustom org-cycle-emulate-tab t
  1291. "Where should `org-cycle' emulate TAB.
  1292. nil Never
  1293. white Only in completely white lines
  1294. whitestart Only at the beginning of lines, before the first non-white char
  1295. t Everywhere except in headlines
  1296. exc-hl-bol Everywhere except at the start of a headline
  1297. If TAB is used in a place where it does not emulate TAB, the current subtree
  1298. visibility is cycled."
  1299. :group 'org-cycle
  1300. :type '(choice (const :tag "Never" nil)
  1301. (const :tag "Only in completely white lines" white)
  1302. (const :tag "Before first char in a line" whitestart)
  1303. (const :tag "Everywhere except in headlines" t)
  1304. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1305. (defcustom org-cycle-separator-lines 2
  1306. "Number of empty lines needed to keep an empty line between collapsed trees.
  1307. If you leave an empty line between the end of a subtree and the following
  1308. headline, this empty line is hidden when the subtree is folded.
  1309. Org mode will leave (exactly) one empty line visible if the number of
  1310. empty lines is equal or larger to the number given in this variable.
  1311. So the default 2 means at least 2 empty lines after the end of a subtree
  1312. are needed to produce free space between a collapsed subtree and the
  1313. following headline.
  1314. If the number is negative, and the number of empty lines is at least -N,
  1315. all empty lines are shown.
  1316. Special case: when 0, never leave empty lines in collapsed view."
  1317. :group 'org-cycle
  1318. :type 'integer)
  1319. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1320. (defcustom org-pre-cycle-hook nil
  1321. "Hook that is run before visibility cycling is happening.
  1322. The function(s) in this hook must accept a single argument which indicates
  1323. the new state that will be set right after running this hook. The
  1324. argument is a symbol. Before a global state change, it can have the values
  1325. `overview', `content', or `all'. Before a local state change, it can have
  1326. the values `folded', `children', or `subtree'."
  1327. :group 'org-cycle
  1328. :type 'hook)
  1329. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1330. org-cycle-hide-drawers
  1331. org-cycle-show-empty-lines
  1332. org-optimize-window-after-visibility-change)
  1333. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1334. The function(s) in this hook must accept a single argument which indicates
  1335. the new state that was set by the most recent `org-cycle' command. The
  1336. argument is a symbol. After a global state change, it can have the values
  1337. `overview', `contents', or `all'. After a local state change, it can have
  1338. the values `folded', `children', or `subtree'."
  1339. :group 'org-cycle
  1340. :package-version '(Org . "9.4")
  1341. :type 'hook)
  1342. (defgroup org-edit-structure nil
  1343. "Options concerning structure editing in Org mode."
  1344. :tag "Org Edit Structure"
  1345. :group 'org-structure)
  1346. (defcustom org-odd-levels-only nil
  1347. "Non-nil means skip even levels and only use odd levels for the outline.
  1348. This has the effect that two stars are being added/taken away in
  1349. promotion/demotion commands. It also influences how levels are
  1350. handled by the exporters.
  1351. Changing it requires restart of `font-lock-mode' to become effective
  1352. for fontification also in regions already fontified.
  1353. You may also set this on a per-file basis by adding one of the following
  1354. lines to the buffer:
  1355. #+STARTUP: odd
  1356. #+STARTUP: oddeven"
  1357. :group 'org-edit-structure
  1358. :group 'org-appearance
  1359. :type 'boolean)
  1360. (defcustom org-adapt-indentation t
  1361. "Non-nil means adapt indentation to outline node level.
  1362. When this variable is set to t, Org assumes that you write
  1363. outlines by indenting text in each node to align with the
  1364. headline (after the stars).
  1365. When this variable is set to 'headline-data, only adapt the
  1366. indentation of the data lines right below the headline, such as
  1367. planning/clock lines and property/logbook drawers.
  1368. The following issues are influenced by this variable:
  1369. - The indentation is increased by one space in a demotion
  1370. command, and decreased by one in a promotion command. However,
  1371. in the latter case, if shifting some line in the entry body
  1372. would alter document structure (e.g., insert a new headline),
  1373. indentation is not changed at all.
  1374. - Property drawers and planning information is inserted indented
  1375. when this variable is set. When nil, they will not be indented.
  1376. - TAB indents a line relative to current level. The lines below
  1377. a headline will be indented when this variable is set to t.
  1378. Note that this is all about true indentation, by adding and
  1379. removing space characters. See also \"org-indent.el\" which does
  1380. level-dependent indentation in a virtual way, i.e. at display
  1381. time in Emacs."
  1382. :group 'org-edit-structure
  1383. :type '(choice
  1384. (const :tag "Adapt indentation for all lines" t)
  1385. (const :tag "Adapt indentation for headline data lines"
  1386. 'headline-data)
  1387. (const :tag "Do not adapt indentation at all" nil))
  1388. :safe #'booleanp)
  1389. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1390. (defcustom org-special-ctrl-a/e nil
  1391. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1392. When t, `C-a' will bring back the cursor to the beginning of the
  1393. headline text, i.e. after the stars and after a possible TODO
  1394. keyword. In an item, this will be the position after bullet and
  1395. check-box, if any. When the cursor is already at that position,
  1396. another `C-a' will bring it to the beginning of the line.
  1397. `C-e' will jump to the end of the headline, ignoring the presence
  1398. of tags in the headline. A second `C-e' will then jump to the
  1399. true end of the line, after any tags. This also means that, when
  1400. this variable is non-nil, `C-e' also will never jump beyond the
  1401. end of the heading of a folded section, i.e. not after the
  1402. ellipses.
  1403. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1404. normally, going to the true line boundary first. Only a directly
  1405. following, identical keypress will bring the cursor to the
  1406. special positions.
  1407. This may also be a cons cell where the behavior for `C-a' and
  1408. `C-e' is set separately."
  1409. :group 'org-edit-structure
  1410. :type '(choice
  1411. (const :tag "off" nil)
  1412. (const :tag "on: after stars/bullet and before tags first" t)
  1413. (const :tag "reversed: true line boundary first" reversed)
  1414. (cons :tag "Set C-a and C-e separately"
  1415. (choice :tag "Special C-a"
  1416. (const :tag "off" nil)
  1417. (const :tag "on: after stars/bullet first" t)
  1418. (const :tag "reversed: before stars/bullet first" reversed))
  1419. (choice :tag "Special C-e"
  1420. (const :tag "off" nil)
  1421. (const :tag "on: before tags first" t)
  1422. (const :tag "reversed: after tags first" reversed)))))
  1423. (defcustom org-special-ctrl-k nil
  1424. "Non-nil means `C-k' will behave specially in headlines.
  1425. When nil, `C-k' will call the default `kill-line' command.
  1426. When t, the following will happen while the cursor is in the headline:
  1427. - When at the beginning of a headline, kill the entire subtree.
  1428. - When in the middle of the headline text, kill the text up to the tags.
  1429. - When after the headline text and before the tags, kill all the tags."
  1430. :group 'org-edit-structure
  1431. :type 'boolean)
  1432. (defcustom org-ctrl-k-protect-subtree nil
  1433. "Non-nil means, do not delete a hidden subtree with `C-k'.
  1434. When set to the symbol `error', simply throw an error when `C-k' is
  1435. used to kill (part-of) a headline that has hidden text behind it.
  1436. Any other non-nil value will result in a query to the user, if it is
  1437. OK to kill that hidden subtree. When nil, kill without remorse."
  1438. :group 'org-edit-structure
  1439. :version "24.1"
  1440. :type '(choice
  1441. (const :tag "Do not protect hidden subtrees" nil)
  1442. (const :tag "Protect hidden subtrees with a security query" t)
  1443. (const :tag "Never kill a hidden subtree with C-k" error)))
  1444. (defcustom org-special-ctrl-o t
  1445. "Non-nil means, make `C-o' insert a row in tables."
  1446. :group 'org-edit-structure
  1447. :type 'boolean)
  1448. (defcustom org-catch-invisible-edits nil
  1449. "Check if in invisible region before inserting or deleting a character.
  1450. Valid values are:
  1451. nil Do not check, so just do invisible edits.
  1452. error Throw an error and do nothing.
  1453. show Make point visible, and do the requested edit.
  1454. show-and-error Make point visible, then throw an error and abort the edit.
  1455. smart Make point visible, and do insertion/deletion if it is
  1456. adjacent to visible text and the change feels predictable.
  1457. Never delete a previously invisible character or add in the
  1458. middle or right after an invisible region. Basically, this
  1459. allows insertion and backward-delete right before ellipses.
  1460. FIXME: maybe in this case we should not even show?"
  1461. :group 'org-edit-structure
  1462. :version "24.1"
  1463. :type '(choice
  1464. (const :tag "Do not check" nil)
  1465. (const :tag "Throw error when trying to edit" error)
  1466. (const :tag "Unhide, but do not do the edit" show-and-error)
  1467. (const :tag "Show invisible part and do the edit" show)
  1468. (const :tag "Be smart and do the right thing" smart)))
  1469. (defcustom org-yank-folded-subtrees t
  1470. "Non-nil means when yanking subtrees, fold them.
  1471. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1472. it starts with a heading and all other headings in it are either children
  1473. or siblings, then fold all the subtrees. However, do this only if no
  1474. text after the yank would be swallowed into a folded tree by this action."
  1475. :group 'org-edit-structure
  1476. :type 'boolean)
  1477. (defcustom org-yank-adjusted-subtrees nil
  1478. "Non-nil means when yanking subtrees, adjust the level.
  1479. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1480. this function for details."
  1481. :group 'org-edit-structure
  1482. :type 'boolean)
  1483. (defcustom org-M-RET-may-split-line '((default . t))
  1484. "Non-nil means M-RET will split the line at the cursor position.
  1485. When nil, it will go to the end of the line before making a
  1486. new line.
  1487. You may also set this option in a different way for different
  1488. contexts. Valid contexts are:
  1489. headline when creating a new headline
  1490. item when creating a new item
  1491. table in a table field
  1492. default the value to be used for all contexts not explicitly
  1493. customized"
  1494. :group 'org-structure
  1495. :group 'org-table
  1496. :type '(choice
  1497. (const :tag "Always" t)
  1498. (const :tag "Never" nil)
  1499. (repeat :greedy t :tag "Individual contexts"
  1500. (cons
  1501. (choice :tag "Context"
  1502. (const headline)
  1503. (const item)
  1504. (const table)
  1505. (const default))
  1506. (boolean)))))
  1507. (defcustom org-insert-heading-respect-content nil
  1508. "Non-nil means insert new headings after the current subtree.
  1509. \\<org-mode-map>
  1510. When nil, the new heading is created directly after the current line.
  1511. The commands `\\[org-insert-heading-respect-content]' and \
  1512. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1513. for the duration of the command."
  1514. :group 'org-structure
  1515. :type 'boolean)
  1516. (defcustom org-blank-before-new-entry '((heading . auto)
  1517. (plain-list-item . auto))
  1518. "Should `org-insert-heading' leave a blank line before new heading/item?
  1519. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1520. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1521. which case Org will look at the surrounding headings/items and try to
  1522. make an intelligent decision whether to insert a blank line or not."
  1523. :group 'org-edit-structure
  1524. :type '(list
  1525. (cons (const heading)
  1526. (choice (const :tag "Never" nil)
  1527. (const :tag "Always" t)
  1528. (const :tag "Auto" auto)))
  1529. (cons (const plain-list-item)
  1530. (choice (const :tag "Never" nil)
  1531. (const :tag "Always" t)
  1532. (const :tag "Auto" auto)))))
  1533. (defcustom org-insert-heading-hook nil
  1534. "Hook being run after inserting a new heading."
  1535. :group 'org-edit-structure
  1536. :type 'hook)
  1537. (defgroup org-sparse-trees nil
  1538. "Options concerning sparse trees in Org mode."
  1539. :tag "Org Sparse Trees"
  1540. :group 'org-structure)
  1541. (defcustom org-highlight-sparse-tree-matches t
  1542. "Non-nil means highlight all matches that define a sparse tree.
  1543. The highlights will automatically disappear the next time the buffer is
  1544. changed by an edit command."
  1545. :group 'org-sparse-trees
  1546. :type 'boolean)
  1547. (defcustom org-remove-highlights-with-change t
  1548. "Non-nil means any change to the buffer will remove temporary highlights.
  1549. \\<org-mode-map>\
  1550. Such highlights are created by `org-occur' and `org-clock-display'.
  1551. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1552. to get rid of the highlights.
  1553. The highlights created by `org-latex-preview' always need
  1554. `\\[org-latex-preview]' to be removed."
  1555. :group 'org-sparse-trees
  1556. :group 'org-time
  1557. :type 'boolean)
  1558. (defcustom org-occur-case-fold-search t
  1559. "Non-nil means `org-occur' should be case-insensitive.
  1560. If set to `smart' the search will be case-insensitive only if it
  1561. doesn't specify any upper case character."
  1562. :group 'org-sparse-trees
  1563. :version "26.1"
  1564. :type '(choice
  1565. (const :tag "Case-sensitive" nil)
  1566. (const :tag "Case-insensitive" t)
  1567. (const :tag "Case-insensitive for lower case searches only" smart)))
  1568. (defcustom org-occur-hook '(org-first-headline-recenter)
  1569. "Hook that is run after `org-occur' has constructed a sparse tree.
  1570. This can be used to recenter the window to show as much of the structure
  1571. as possible."
  1572. :group 'org-sparse-trees
  1573. :type 'hook)
  1574. (defcustom org-self-insert-cluster-for-undo nil
  1575. "Non-nil means cluster self-insert commands for undo when possible.
  1576. If this is set, then, like in the Emacs command loop, 20 consecutive
  1577. characters will be undone together.
  1578. This is configurable, because there is some impact on typing performance."
  1579. :group 'org-table
  1580. :type 'boolean)
  1581. (defvaralias 'org-activate-links 'org-highlight-links)
  1582. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1583. "Types of links that should be highlighted in Org files.
  1584. This is a list of symbols, each one of them leading to the
  1585. highlighting of a certain link type.
  1586. You can still open links that are not highlighted.
  1587. In principle, it does not hurt to turn on highlighting for all
  1588. link types. There may be a small gain when turning off unused
  1589. link types. The types are:
  1590. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1591. angle Links in angular brackets that may contain whitespace like
  1592. <bbdb:Carsten Dominik>.
  1593. plain Plain links in normal text, no whitespace, like http://google.com.
  1594. radio Text that is matched by a radio target, see manual for details.
  1595. tag Tag settings in a headline (link to tag search).
  1596. date Time stamps (link to calendar).
  1597. footnote Footnote labels.
  1598. If you set this variable during an Emacs session, use `org-mode-restart'
  1599. in the Org buffer so that the change takes effect."
  1600. :group 'org-appearance
  1601. :type '(set :greedy t
  1602. (const :tag "Double bracket links" bracket)
  1603. (const :tag "Angular bracket links" angle)
  1604. (const :tag "Plain text links" plain)
  1605. (const :tag "Radio target matches" radio)
  1606. (const :tag "Tags" tag)
  1607. (const :tag "Timestamps" date)
  1608. (const :tag "Footnotes" footnote)))
  1609. (defcustom org-mark-ring-length 4
  1610. "Number of different positions to be recorded in the ring.
  1611. Changing this requires a restart of Emacs to work correctly."
  1612. :group 'org-link-follow
  1613. :type 'integer)
  1614. (defgroup org-todo nil
  1615. "Options concerning TODO items in Org mode."
  1616. :tag "Org TODO"
  1617. :group 'org)
  1618. (defgroup org-progress nil
  1619. "Options concerning Progress logging in Org mode."
  1620. :tag "Org Progress"
  1621. :group 'org-time)
  1622. (defvar org-todo-interpretation-widgets
  1623. '((:tag "Sequence (cycling hits every state)" sequence)
  1624. (:tag "Type (cycling directly to DONE)" type))
  1625. "The available interpretation symbols for customizing `org-todo-keywords'.
  1626. Interested libraries should add to this list.")
  1627. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1628. "List of TODO entry keyword sequences and their interpretation.
  1629. \\<org-mode-map>This is a list of sequences.
  1630. Each sequence starts with a symbol, either `sequence' or `type',
  1631. indicating if the keywords should be interpreted as a sequence of
  1632. action steps, or as different types of TODO items. The first
  1633. keywords are states requiring action - these states will select a headline
  1634. for inclusion into the global TODO list Org produces. If one of the
  1635. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1636. signify that no further action is necessary. If \"|\" is not found,
  1637. the last keyword is treated as the only DONE state of the sequence.
  1638. The command `\\[org-todo]' cycles an entry through these states, and one
  1639. additional state where no keyword is present. For details about this
  1640. cycling, see the manual.
  1641. TODO keywords and interpretation can also be set on a per-file basis with
  1642. the special #+SEQ_TODO and #+TYP_TODO lines.
  1643. Each keyword can optionally specify a character for fast state selection
  1644. \(in combination with the variable `org-use-fast-todo-selection')
  1645. and specifiers for state change logging, using the same syntax that
  1646. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1647. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1648. indicates to record a time stamp each time this state is selected.
  1649. Each keyword may also specify if a timestamp or a note should be
  1650. recorded when entering or leaving the state, by adding additional
  1651. characters in the parenthesis after the keyword. This looks like this:
  1652. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1653. record only the time of the state change. With X and Y being either
  1654. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1655. Y when leaving the state if and only if the *target* state does not
  1656. define X. You may omit any of the fast-selection key or X or /Y,
  1657. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1658. For backward compatibility, this variable may also be just a list
  1659. of keywords. In this case the interpretation (sequence or type) will be
  1660. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1661. :group 'org-todo
  1662. :group 'org-keywords
  1663. :type '(choice
  1664. (repeat :tag "Old syntax, just keywords"
  1665. (string :tag "Keyword"))
  1666. (repeat :tag "New syntax"
  1667. (cons
  1668. (choice
  1669. :tag "Interpretation"
  1670. ;;Quick and dirty way to see
  1671. ;;`org-todo-interpretation'. This takes the
  1672. ;;place of item arguments
  1673. :convert-widget
  1674. (lambda (widget)
  1675. (widget-put widget
  1676. :args (mapcar
  1677. (lambda (x)
  1678. (widget-convert
  1679. (cons 'const x)))
  1680. org-todo-interpretation-widgets))
  1681. widget))
  1682. (repeat
  1683. (string :tag "Keyword"))))))
  1684. (defvar-local org-todo-keywords-1 nil
  1685. "All TODO and DONE keywords active in a buffer.")
  1686. (defvar org-todo-keywords-for-agenda nil)
  1687. (defvar org-done-keywords-for-agenda nil)
  1688. (defvar org-todo-keyword-alist-for-agenda nil)
  1689. (defvar org-tag-alist-for-agenda nil
  1690. "Alist of all tags from all agenda files.")
  1691. (defvar org-tag-groups-alist-for-agenda nil
  1692. "Alist of all groups tags from all current agenda files.")
  1693. (defvar-local org-tag-groups-alist nil)
  1694. (defvar org-agenda-contributing-files nil)
  1695. (defvar-local org-current-tag-alist nil
  1696. "Alist of all tag groups in current buffer.
  1697. This variable takes into consideration `org-tag-alist',
  1698. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1699. (defvar-local org-not-done-keywords nil)
  1700. (defvar-local org-done-keywords nil)
  1701. (defvar-local org-todo-heads nil)
  1702. (defvar-local org-todo-sets nil)
  1703. (defvar-local org-todo-log-states nil)
  1704. (defvar-local org-todo-kwd-alist nil)
  1705. (defvar-local org-todo-key-alist nil)
  1706. (defvar-local org-todo-key-trigger nil)
  1707. (defcustom org-todo-interpretation 'sequence
  1708. "Controls how TODO keywords are interpreted.
  1709. This variable is in principle obsolete and is only used for
  1710. backward compatibility, if the interpretation of todo keywords is
  1711. not given already in `org-todo-keywords'. See that variable for
  1712. more information."
  1713. :group 'org-todo
  1714. :group 'org-keywords
  1715. :type '(choice (const sequence)
  1716. (const type)))
  1717. (defcustom org-use-fast-todo-selection 'auto
  1718. "\\<org-mode-map>\
  1719. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1720. This variable describes if and under what circumstances the cycling
  1721. mechanism for TODO keywords will be replaced by a single-key, direct
  1722. selection scheme, where the choices are displayed in a little window.
  1723. When nil, fast selection is never used. This means that the command
  1724. will always switch to the next state.
  1725. When it is the symbol `auto', fast selection is whenever selection
  1726. keys have been defined.
  1727. `expert' is like `auto', but no special window with the keyword
  1728. will be shown, choices will only be listed in the prompt.
  1729. In all cases, the special interface is only used if access keys have
  1730. actually been assigned by the user, i.e. if keywords in the configuration
  1731. are followed by a letter in parenthesis, like TODO(t)."
  1732. :group 'org-todo
  1733. :set (lambda (var val)
  1734. (cond
  1735. ((eq var t) (set var 'auto))
  1736. ((eq var 'prefix) (set var nil))
  1737. (t (set var val))))
  1738. :type '(choice
  1739. (const :tag "Never" nil)
  1740. (const :tag "Automatically, when key letter have been defined" auto)
  1741. (const :tag "Automatically, but don't show the selection window" expert)))
  1742. (defcustom org-provide-todo-statistics t
  1743. "Non-nil means update todo statistics after insert and toggle.
  1744. ALL-HEADLINES means update todo statistics by including headlines
  1745. with no TODO keyword as well, counting them as not done.
  1746. A list of TODO keywords means the same, but skip keywords that are
  1747. not in this list.
  1748. When set to a list of two lists, the first list contains keywords
  1749. to consider as TODO keywords, the second list contains keywords
  1750. to consider as DONE keywords.
  1751. When this is set, todo statistics is updated in the parent of the
  1752. current entry each time a todo state is changed."
  1753. :group 'org-todo
  1754. :type '(choice
  1755. (const :tag "Yes, only for TODO entries" t)
  1756. (const :tag "Yes, including all entries" all-headlines)
  1757. (repeat :tag "Yes, for TODOs in this list"
  1758. (string :tag "TODO keyword"))
  1759. (list :tag "Yes, for TODOs and DONEs in these lists"
  1760. (repeat (string :tag "TODO keyword"))
  1761. (repeat (string :tag "DONE keyword")))
  1762. (other :tag "No TODO statistics" nil)))
  1763. (defcustom org-hierarchical-todo-statistics t
  1764. "Non-nil means TODO statistics covers just direct children.
  1765. When nil, all entries in the subtree are considered.
  1766. This has only an effect if `org-provide-todo-statistics' is set.
  1767. To set this to nil for only a single subtree, use a COOKIE_DATA
  1768. property and include the word \"recursive\" into the value."
  1769. :group 'org-todo
  1770. :type 'boolean)
  1771. (defcustom org-after-todo-state-change-hook nil
  1772. "Hook which is run after the state of a TODO item was changed.
  1773. The new state (a string with a TODO keyword, or nil) is available in the
  1774. Lisp variable `org-state'."
  1775. :group 'org-todo
  1776. :type 'hook)
  1777. (defvar org-blocker-hook nil
  1778. "Hook for functions that are allowed to block a state change.
  1779. Functions in this hook should not modify the buffer.
  1780. Each function gets as its single argument a property list,
  1781. see `org-trigger-hook' for more information about this list.
  1782. If any of the functions in this hook returns nil, the state change
  1783. is blocked.")
  1784. (defvar org-trigger-hook nil
  1785. "Hook for functions that are triggered by a state change.
  1786. Each function gets as its single argument a property list with at
  1787. least the following elements:
  1788. (:type type-of-change :position pos-at-entry-start
  1789. :from old-state :to new-state)
  1790. Depending on the type, more properties may be present.
  1791. This mechanism is currently implemented for:
  1792. TODO state changes
  1793. ------------------
  1794. :type todo-state-change
  1795. :from previous state (keyword as a string), or nil, or a symbol
  1796. `todo' or `done', to indicate the general type of state.
  1797. :to new state, like in :from")
  1798. (defcustom org-enforce-todo-dependencies nil
  1799. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1800. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1801. be blocked if any prior sibling is not yet done.
  1802. Finally, if the parent is blocked because of ordered siblings of its own,
  1803. the child will also be blocked."
  1804. :set (lambda (var val)
  1805. (set var val)
  1806. (if val
  1807. (add-hook 'org-blocker-hook
  1808. 'org-block-todo-from-children-or-siblings-or-parent)
  1809. (remove-hook 'org-blocker-hook
  1810. 'org-block-todo-from-children-or-siblings-or-parent)))
  1811. :group 'org-todo
  1812. :type 'boolean)
  1813. (defcustom org-enforce-todo-checkbox-dependencies nil
  1814. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1815. When this is nil, checkboxes have no influence on switching TODO states.
  1816. When non-nil, you first need to check off all check boxes before the TODO
  1817. entry can be switched to DONE.
  1818. This variable needs to be set before org.el is loaded, and you need to
  1819. restart Emacs after a change to make the change effective. The only way
  1820. to change it while Emacs is running is through the customize interface."
  1821. :set (lambda (var val)
  1822. (set var val)
  1823. (if val
  1824. (add-hook 'org-blocker-hook
  1825. 'org-block-todo-from-checkboxes)
  1826. (remove-hook 'org-blocker-hook
  1827. 'org-block-todo-from-checkboxes)))
  1828. :group 'org-todo
  1829. :type 'boolean)
  1830. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1831. "Non-nil means inserting a TODO heading is treated as state change.
  1832. So when the command `\\[org-insert-todo-heading]' is used, state change
  1833. logging will apply if appropriate. When nil, the new TODO item will
  1834. be inserted directly, and no logging will take place."
  1835. :group 'org-todo
  1836. :type 'boolean)
  1837. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1838. "Non-nil means switching TODO states with S-cursor counts as state change.
  1839. This is the default behavior. However, setting this to nil allows a
  1840. convenient way to select a TODO state and bypass any logging associated
  1841. with that."
  1842. :group 'org-todo
  1843. :type 'boolean)
  1844. (defcustom org-todo-state-tags-triggers nil
  1845. "Tag changes that should be triggered by TODO state changes.
  1846. This is a list. Each entry is
  1847. (state-change (tag . flag) .......)
  1848. State-change can be a string with a state, and empty string to indicate the
  1849. state that has no TODO keyword, or it can be one of the symbols `todo'
  1850. or `done', meaning any not-done or done state, respectively."
  1851. :group 'org-todo
  1852. :group 'org-tags
  1853. :type '(repeat
  1854. (cons (choice :tag "When changing to"
  1855. (const :tag "Not-done state" todo)
  1856. (const :tag "Done state" done)
  1857. (string :tag "State"))
  1858. (repeat
  1859. (cons :tag "Tag action"
  1860. (string :tag "Tag")
  1861. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1862. (defcustom org-log-done nil
  1863. "Information to record when a task moves to the DONE state.
  1864. Possible values are:
  1865. nil Don't add anything, just change the keyword
  1866. time Add a time stamp to the task
  1867. note Prompt for a note and add it with template `org-log-note-headings'
  1868. This option can also be set with on a per-file-basis with
  1869. #+STARTUP: nologdone
  1870. #+STARTUP: logdone
  1871. #+STARTUP: lognotedone
  1872. You can have local logging settings for a subtree by setting the LOGGING
  1873. property to one or more of these keywords."
  1874. :group 'org-todo
  1875. :group 'org-progress
  1876. :type '(choice
  1877. (const :tag "No logging" nil)
  1878. (const :tag "Record CLOSED timestamp" time)
  1879. (const :tag "Record CLOSED timestamp with note." note)))
  1880. ;; Normalize old uses of org-log-done.
  1881. (cond
  1882. ((eq org-log-done t) (setq org-log-done 'time))
  1883. ((and (listp org-log-done) (memq 'done org-log-done))
  1884. (setq org-log-done 'note)))
  1885. (defcustom org-log-reschedule nil
  1886. "Information to record when the scheduling date of a task is modified.
  1887. Possible values are:
  1888. nil Don't add anything, just change the date
  1889. time Add a time stamp to the task
  1890. note Prompt for a note and add it with template `org-log-note-headings'
  1891. This option can also be set with on a per-file-basis with
  1892. #+STARTUP: nologreschedule
  1893. #+STARTUP: logreschedule
  1894. #+STARTUP: lognotereschedule
  1895. You can have local logging settings for a subtree by setting the LOGGING
  1896. property to one or more of these keywords.
  1897. This variable has an effect when calling `org-schedule' or
  1898. `org-agenda-schedule' only."
  1899. :group 'org-todo
  1900. :group 'org-progress
  1901. :type '(choice
  1902. (const :tag "No logging" nil)
  1903. (const :tag "Record timestamp" time)
  1904. (const :tag "Record timestamp with note" note)))
  1905. (defcustom org-log-redeadline nil
  1906. "Information to record when the deadline date of a task is modified.
  1907. Possible values are:
  1908. nil Don't add anything, just change the date
  1909. time Add a time stamp to the task
  1910. note Prompt for a note and add it with template `org-log-note-headings'
  1911. This option can also be set with on a per-file-basis with
  1912. #+STARTUP: nologredeadline
  1913. #+STARTUP: logredeadline
  1914. #+STARTUP: lognoteredeadline
  1915. You can have local logging settings for a subtree by setting the LOGGING
  1916. property to one or more of these keywords.
  1917. This variable has an effect when calling `org-deadline' or
  1918. `org-agenda-deadline' only."
  1919. :group 'org-todo
  1920. :group 'org-progress
  1921. :type '(choice
  1922. (const :tag "No logging" nil)
  1923. (const :tag "Record timestamp" time)
  1924. (const :tag "Record timestamp with note." note)))
  1925. (defcustom org-log-note-clock-out nil
  1926. "Non-nil means record a note when clocking out of an item.
  1927. This can also be configured on a per-file basis by adding one of
  1928. the following lines anywhere in the buffer:
  1929. #+STARTUP: lognoteclock-out
  1930. #+STARTUP: nolognoteclock-out"
  1931. :group 'org-todo
  1932. :group 'org-progress
  1933. :type 'boolean)
  1934. (defcustom org-log-done-with-time t
  1935. "Non-nil means the CLOSED time stamp will contain date and time.
  1936. When nil, only the date will be recorded."
  1937. :group 'org-progress
  1938. :type 'boolean)
  1939. (defcustom org-log-note-headings
  1940. '((done . "CLOSING NOTE %t")
  1941. (state . "State %-12s from %-12S %t")
  1942. (note . "Note taken on %t")
  1943. (reschedule . "Rescheduled from %S on %t")
  1944. (delschedule . "Not scheduled, was %S on %t")
  1945. (redeadline . "New deadline from %S on %t")
  1946. (deldeadline . "Removed deadline, was %S on %t")
  1947. (refile . "Refiled on %t")
  1948. (clock-out . ""))
  1949. "Headings for notes added to entries.
  1950. The value is an alist, with the car being a symbol indicating the
  1951. note context, and the cdr is the heading to be used. The heading
  1952. may also be the empty string. The following placeholders can be
  1953. used:
  1954. %t a time stamp.
  1955. %T an active time stamp instead the default inactive one
  1956. %d a short-format time stamp.
  1957. %D an active short-format time stamp.
  1958. %s the new TODO state or time stamp (inactive), in double quotes.
  1959. %S the old TODO state or time stamp (inactive), in double quotes.
  1960. %u the user name.
  1961. %U full user name.
  1962. In fact, it is not a good idea to change the `state' entry,
  1963. because Agenda Log mode depends on the format of these entries."
  1964. :group 'org-todo
  1965. :group 'org-progress
  1966. :type '(list :greedy t
  1967. (cons (const :tag "Heading when closing an item" done) string)
  1968. (cons (const :tag
  1969. "Heading when changing todo state (todo sequence only)"
  1970. state) string)
  1971. (cons (const :tag "Heading when just taking a note" note) string)
  1972. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1973. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1974. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1975. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1976. (cons (const :tag "Heading when refiling" refile) string)
  1977. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1978. (unless (assq 'note org-log-note-headings)
  1979. (push '(note . "%t") org-log-note-headings))
  1980. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1981. (defcustom org-log-into-drawer nil
  1982. "Non-nil means insert state change notes and time stamps into a drawer.
  1983. When nil, state changes notes will be inserted after the headline and
  1984. any scheduling and clock lines, but not inside a drawer.
  1985. The value of this variable should be the name of the drawer to use.
  1986. LOGBOOK is proposed as the default drawer for this purpose, you can
  1987. also set this to a string to define the drawer of your choice.
  1988. A value of t is also allowed, representing \"LOGBOOK\".
  1989. A value of t or nil can also be set with on a per-file-basis with
  1990. #+STARTUP: logdrawer
  1991. #+STARTUP: nologdrawer
  1992. If this variable is set, `org-log-state-notes-insert-after-drawers'
  1993. will be ignored.
  1994. You can set the property LOG_INTO_DRAWER to overrule this setting for
  1995. a subtree.
  1996. Do not check directly this variable in a Lisp program. Call
  1997. function `org-log-into-drawer' instead."
  1998. :group 'org-todo
  1999. :group 'org-progress
  2000. :type '(choice
  2001. (const :tag "Not into a drawer" nil)
  2002. (const :tag "LOGBOOK" t)
  2003. (string :tag "Other")))
  2004. (defun org-log-into-drawer ()
  2005. "Name of the log drawer, as a string, or nil.
  2006. This is the value of `org-log-into-drawer'. However, if the
  2007. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2008. be used instead of the default value."
  2009. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2010. (cond ((equal p "nil") nil)
  2011. ((equal p "t") "LOGBOOK")
  2012. ((stringp p) p)
  2013. (p "LOGBOOK")
  2014. ((stringp org-log-into-drawer) org-log-into-drawer)
  2015. (org-log-into-drawer "LOGBOOK"))))
  2016. (defcustom org-log-state-notes-insert-after-drawers nil
  2017. "Non-nil means insert state change notes after any drawers in entry.
  2018. Only the drawers that *immediately* follow the headline and the
  2019. deadline/scheduled line are skipped.
  2020. When nil, insert notes right after the heading and perhaps the line
  2021. with deadline/scheduling if present.
  2022. This variable will have no effect if `org-log-into-drawer' is
  2023. set."
  2024. :group 'org-todo
  2025. :group 'org-progress
  2026. :type 'boolean)
  2027. (defcustom org-log-states-order-reversed t
  2028. "Non-nil means the latest state note will be directly after heading.
  2029. When nil, the state change notes will be ordered according to time.
  2030. This option can also be set with on a per-file-basis with
  2031. #+STARTUP: logstatesreversed
  2032. #+STARTUP: nologstatesreversed"
  2033. :group 'org-todo
  2034. :group 'org-progress
  2035. :type 'boolean)
  2036. (defcustom org-todo-repeat-to-state nil
  2037. "The TODO state to which a repeater should return the repeating task.
  2038. By default this is the first task of a TODO sequence or the
  2039. previous state of a TYPE_TODO set. But you can specify to use
  2040. the previous state in a TODO sequence or a string.
  2041. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2042. entry, which has precedence over this option."
  2043. :group 'org-todo
  2044. :version "24.1"
  2045. :type '(choice (const :tag "Use the previous TODO state" t)
  2046. (const :tag "Use the head of the TODO sequence" nil)
  2047. (string :tag "Use a specific TODO state")))
  2048. (defcustom org-log-repeat 'time
  2049. "Non-nil means record moving through the DONE state when triggering repeat.
  2050. An auto-repeating task is immediately switched back to TODO when
  2051. marked DONE. If you are not logging state changes (by adding \"@\"
  2052. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2053. record a closing note, there will be no record of the task moving
  2054. through DONE. This variable forces taking a note anyway.
  2055. nil Don't force a record
  2056. time Record a time stamp
  2057. note Prompt for a note and add it with template `org-log-note-headings'
  2058. This option can also be set with on a per-file-basis with
  2059. #+STARTUP: nologrepeat
  2060. #+STARTUP: logrepeat
  2061. #+STARTUP: lognoterepeat
  2062. You can have local logging settings for a subtree by setting the LOGGING
  2063. property to one or more of these keywords."
  2064. :group 'org-todo
  2065. :group 'org-progress
  2066. :type '(choice
  2067. (const :tag "Don't force a record" nil)
  2068. (const :tag "Force recording the DONE state" time)
  2069. (const :tag "Force recording a note with the DONE state" note)))
  2070. (defcustom org-todo-repeat-hook nil
  2071. "Hook that is run after a task has been repeated."
  2072. :package-version '(Org . "9.2")
  2073. :group 'org-todo
  2074. :type 'hook)
  2075. (defgroup org-priorities nil
  2076. "Priorities in Org mode."
  2077. :tag "Org Priorities"
  2078. :group 'org-todo)
  2079. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  2080. (defcustom org-priority-enable-commands t
  2081. "Non-nil means priority commands are active.
  2082. When nil, these commands will be disabled, so that you never accidentally
  2083. set a priority."
  2084. :group 'org-priorities
  2085. :type 'boolean)
  2086. (defvaralias 'org-highest-priority 'org-priority-highest)
  2087. (defcustom org-priority-highest ?A
  2088. "The highest priority of TODO items.
  2089. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2090. Must be smaller than `org-priority-lowest'."
  2091. :group 'org-priorities
  2092. :type '(choice
  2093. (character :tag "Character")
  2094. (integer :tag "Integer (< 65)")))
  2095. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  2096. (defcustom org-priority-lowest ?C
  2097. "The lowest priority of TODO items.
  2098. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2099. Must be higher than `org-priority-highest'."
  2100. :group 'org-priorities
  2101. :type '(choice
  2102. (character :tag "Character")
  2103. (integer :tag "Integer (< 65)")))
  2104. (defvaralias 'org-default-priority 'org-priority-default)
  2105. (defcustom org-priority-default ?B
  2106. "The default priority of TODO items.
  2107. This is the priority an item gets if no explicit priority is given.
  2108. When starting to cycle on an empty priority the first step in the cycle
  2109. depends on `org-priority-start-cycle-with-default'. The resulting first
  2110. step priority must not exceed the range from `org-priority-highest' to
  2111. `org-priority-lowest' which means that `org-priority-default' has to be
  2112. in this range exclusive or inclusive to the range boundaries. Else the
  2113. first step refuses to set the default and the second will fall back on
  2114. \(depending on the command used) the highest or lowest priority."
  2115. :group 'org-priorities
  2116. :type '(choice
  2117. (character :tag "Character")
  2118. (integer :tag "Integer (< 65)")))
  2119. (defcustom org-priority-start-cycle-with-default t
  2120. "Non-nil means start with default priority when starting to cycle.
  2121. When this is nil, the first step in the cycle will be (depending on the
  2122. command used) one higher or lower than the default priority.
  2123. See also `org-priority-default'."
  2124. :group 'org-priorities
  2125. :type 'boolean)
  2126. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2127. (defcustom org-priority-get-priority-function nil
  2128. "Function to extract the priority from a string.
  2129. The string is normally the headline. If this is nil, Org
  2130. computes the priority from the priority cookie like [#A] in the
  2131. headline. It returns an integer, increasing by 1000 for each
  2132. priority level.
  2133. The user can set a different function here, which should take a
  2134. string as an argument and return the numeric priority."
  2135. :group 'org-priorities
  2136. :version "24.1"
  2137. :type '(choice
  2138. (const nil)
  2139. (function)))
  2140. (defgroup org-time nil
  2141. "Options concerning time stamps and deadlines in Org mode."
  2142. :tag "Org Time"
  2143. :group 'org)
  2144. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2145. "Number of minutes to round time stamps to.
  2146. \\<org-mode-map>\
  2147. These are two values, the first applies when first creating a time stamp.
  2148. The second applies when changing it with the commands `S-up' and `S-down'.
  2149. When changing the time stamp, this means that it will change in steps
  2150. of N minutes, as given by the second value.
  2151. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2152. numbers should be factors of 60, so for example 5, 10, 15.
  2153. When this is larger than 1, you can still force an exact time stamp by using
  2154. a double prefix argument to a time stamp command like \
  2155. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2156. and by using a prefix arg to `S-up/down' to specify the exact number
  2157. of minutes to shift."
  2158. :group 'org-time
  2159. :get (lambda (var) ; Make sure both elements are there
  2160. (if (integerp (default-value var))
  2161. (list (default-value var) 5)
  2162. (default-value var)))
  2163. :type '(list
  2164. (integer :tag "when inserting times")
  2165. (integer :tag "when modifying times")))
  2166. ;; Normalize old customizations of this variable.
  2167. (when (integerp org-time-stamp-rounding-minutes)
  2168. (setq org-time-stamp-rounding-minutes
  2169. (list org-time-stamp-rounding-minutes
  2170. org-time-stamp-rounding-minutes)))
  2171. (defcustom org-display-custom-times nil
  2172. "Non-nil means overlay custom formats over all time stamps.
  2173. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2174. To turn this on on a per-file basis, insert anywhere in the file:
  2175. #+STARTUP: customtime"
  2176. :group 'org-time
  2177. :set 'set-default
  2178. :type 'sexp)
  2179. (make-variable-buffer-local 'org-display-custom-times)
  2180. (defcustom org-time-stamp-custom-formats
  2181. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2182. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2183. These are overlaid over the default ISO format if the variable
  2184. `org-display-custom-times' is set. Time like %H:%M should be at the
  2185. end of the second format. The custom formats are also honored by export
  2186. commands, if custom time display is turned on at the time of export."
  2187. :group 'org-time
  2188. :type 'sexp)
  2189. (defun org-time-stamp-format (&optional long inactive)
  2190. "Get the right format for a time string."
  2191. (let ((f (if long (cdr org-time-stamp-formats)
  2192. (car org-time-stamp-formats))))
  2193. (if inactive
  2194. (concat "[" (substring f 1 -1) "]")
  2195. f)))
  2196. (defcustom org-deadline-warning-days 14
  2197. "Number of days before expiration during which a deadline becomes active.
  2198. This variable governs the display in sparse trees and in the agenda.
  2199. When 0 or negative, it means use this number (the absolute value of it)
  2200. even if a deadline has a different individual lead time specified.
  2201. Custom commands can set this variable in the options section."
  2202. :group 'org-time
  2203. :group 'org-agenda-daily/weekly
  2204. :type 'integer)
  2205. (defcustom org-scheduled-delay-days 0
  2206. "Number of days before a scheduled item becomes active.
  2207. This variable governs the display in sparse trees and in the agenda.
  2208. The default value (i.e. 0) means: don't delay scheduled item.
  2209. When negative, it means use this number (the absolute value of it)
  2210. even if a scheduled item has a different individual delay time
  2211. specified.
  2212. Custom commands can set this variable in the options section."
  2213. :group 'org-time
  2214. :group 'org-agenda-daily/weekly
  2215. :version "24.4"
  2216. :package-version '(Org . "8.0")
  2217. :type 'integer)
  2218. (defcustom org-read-date-prefer-future t
  2219. "Non-nil means assume future for incomplete date input from user.
  2220. This affects the following situations:
  2221. 1. The user gives a month but not a year.
  2222. For example, if it is April and you enter \"feb 2\", this will be read
  2223. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2224. 2. The user gives a day, but no month.
  2225. For example, if today is the 15th, and you enter \"3\", Org will read
  2226. this as the third of *next* month. However, if you enter \"17\",
  2227. it will be considered as *this* month.
  2228. If you set this variable to the symbol `time', then also the following
  2229. will work:
  2230. 3. If the user gives a time.
  2231. If the time is before now, it will be interpreted as tomorrow.
  2232. Currently none of this works for ISO week specifications.
  2233. When this option is nil, the current day, month and year will always be
  2234. used as defaults.
  2235. See also `org-agenda-jump-prefer-future'."
  2236. :group 'org-time
  2237. :type '(choice
  2238. (const :tag "Never" nil)
  2239. (const :tag "Check month and day" t)
  2240. (const :tag "Check month, day, and time" time)))
  2241. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2242. "Should the agenda jump command prefer the future for incomplete dates?
  2243. The default is to do the same as configured in `org-read-date-prefer-future'.
  2244. But you can also set a deviating value here.
  2245. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2246. :group 'org-agenda
  2247. :group 'org-time
  2248. :version "24.1"
  2249. :type '(choice
  2250. (const :tag "Use org-read-date-prefer-future"
  2251. org-read-date-prefer-future)
  2252. (const :tag "Never" nil)
  2253. (const :tag "Always" t)))
  2254. (defcustom org-read-date-force-compatible-dates t
  2255. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2256. Depending on the system Emacs is running on, certain dates cannot
  2257. be represented with the type used internally to represent time.
  2258. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2259. correctly. Some systems allow for earlier dates, some for later,
  2260. some for both. One way to find out is to insert any date into an
  2261. Org buffer, putting the cursor on the year and hitting S-up and
  2262. S-down to test the range.
  2263. When this variable is set to t, the date/time prompt will not let
  2264. you specify dates outside the 1970-2037 range, so it is certain that
  2265. these dates will work in whatever version of Emacs you are
  2266. running, and also that you can move a file from one Emacs implementation
  2267. to another. Whenever Org is forcing the year for you, it will display
  2268. a message and beep.
  2269. When this variable is nil, Org will check if the date is
  2270. representable in the specific Emacs implementation you are using.
  2271. If not, it will force a year, usually the current year, and beep
  2272. to remind you. Currently this setting is not recommended because
  2273. the likelihood that you will open your Org files in an Emacs that
  2274. has limited date range is not negligible.
  2275. A workaround for this problem is to use diary sexp dates for time
  2276. stamps outside of this range."
  2277. :group 'org-time
  2278. :version "24.1"
  2279. :type 'boolean)
  2280. (defcustom org-read-date-display-live t
  2281. "Non-nil means display current interpretation of date prompt live.
  2282. This display will be in an overlay, in the minibuffer. Note that
  2283. live display is only active when `org-read-date-popup-calendar'
  2284. is non-nil."
  2285. :group 'org-time
  2286. :type 'boolean)
  2287. (defvaralias 'org-popup-calendar-for-date-prompt
  2288. 'org-read-date-popup-calendar)
  2289. (defcustom org-read-date-popup-calendar t
  2290. "Non-nil means pop up a calendar when prompting for a date.
  2291. In the calendar, the date can be selected with mouse-1. However, the
  2292. minibuffer will also be active, and you can simply enter the date as well.
  2293. When nil, only the minibuffer will be available."
  2294. :group 'org-time
  2295. :type 'boolean)
  2296. (defcustom org-extend-today-until 0
  2297. "The hour when your day really ends. Must be an integer.
  2298. This has influence for the following applications:
  2299. - When switching the agenda to \"today\". If it is still earlier than
  2300. the time given here, the day recognized as TODAY is actually yesterday.
  2301. - When a date is read from the user and it is still before the time given
  2302. here, the current date and time will be assumed to be yesterday, 23:59.
  2303. Also, timestamps inserted in capture templates follow this rule.
  2304. IMPORTANT: This is a feature whose implementation is and likely will
  2305. remain incomplete. Really, it is only here because past midnight seems to
  2306. be the favorite working time of John Wiegley :-)"
  2307. :group 'org-time
  2308. :type 'integer)
  2309. (defcustom org-use-effective-time nil
  2310. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2311. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2312. \"effective time\" of any timestamps between midnight and 8am will be
  2313. 23:59 of the previous day."
  2314. :group 'org-time
  2315. :version "24.1"
  2316. :type 'boolean)
  2317. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2318. "When non-nil, use the last clock out time for `org-todo'.
  2319. Note that this option has precedence over the combined use of
  2320. `org-use-effective-time' and `org-extend-today-until'."
  2321. :group 'org-time
  2322. :version "24.4"
  2323. :package-version '(Org . "8.0")
  2324. :type 'boolean)
  2325. (defcustom org-edit-timestamp-down-means-later nil
  2326. "Non-nil means S-down will increase the time in a time stamp.
  2327. When nil, S-up will increase."
  2328. :group 'org-time
  2329. :type 'boolean)
  2330. (defcustom org-calendar-follow-timestamp-change t
  2331. "Non-nil means make the calendar window follow timestamp changes.
  2332. When a timestamp is modified and the calendar window is visible, it will be
  2333. moved to the new date."
  2334. :group 'org-time
  2335. :type 'boolean)
  2336. (defgroup org-tags nil
  2337. "Options concerning tags in Org mode."
  2338. :tag "Org Tags"
  2339. :group 'org)
  2340. (defcustom org-tag-alist nil
  2341. "Default tags available in Org files.
  2342. The value of this variable is an alist. Associations either:
  2343. (TAG)
  2344. (TAG . SELECT)
  2345. (SPECIAL)
  2346. where TAG is a tag as a string, SELECT is character, used to
  2347. select that tag through the fast tag selection interface, and
  2348. SPECIAL is one of the following keywords: `:startgroup',
  2349. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2350. `:newline'. These keywords are used to define a hierarchy of
  2351. tags. See manual for details.
  2352. When this variable is nil, Org mode bases tag input on what is
  2353. already in the buffer. The value can be overridden locally by
  2354. using a TAGS keyword, e.g.,
  2355. #+TAGS: tag1 tag2
  2356. See also `org-tag-persistent-alist' to sidestep this behavior."
  2357. :group 'org-tags
  2358. :type '(repeat
  2359. (choice
  2360. (cons :tag "Tag with key"
  2361. (string :tag "Tag name")
  2362. (character :tag "Access char"))
  2363. (list :tag "Tag" (string :tag "Tag name"))
  2364. (const :tag "Start radio group" (:startgroup))
  2365. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2366. (const :tag "Group tags delimiter" (:grouptags))
  2367. (const :tag "End radio group" (:endgroup))
  2368. (const :tag "End tag group, non distinct" (:endgrouptag))
  2369. (const :tag "New line" (:newline)))))
  2370. (defcustom org-tag-persistent-alist nil
  2371. "Tags always available in Org files.
  2372. The value of this variable is an alist. Associations either:
  2373. (TAG)
  2374. (TAG . SELECT)
  2375. (SPECIAL)
  2376. where TAG is a tag as a string, SELECT is a character, used to
  2377. select that tag through the fast tag selection interface, and
  2378. SPECIAL is one of the following keywords: `:startgroup',
  2379. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2380. `:newline'. These keywords are used to define a hierarchy of
  2381. tags. See manual for details.
  2382. Unlike to `org-tag-alist', tags defined in this variable do not
  2383. depend on a local TAGS keyword. Instead, to disable these tags
  2384. on a per-file basis, insert anywhere in the file:
  2385. #+STARTUP: noptag"
  2386. :group 'org-tags
  2387. :type '(repeat
  2388. (choice
  2389. (cons :tag "Tag with key"
  2390. (string :tag "Tag name")
  2391. (character :tag "Access char"))
  2392. (list :tag "Tag" (string :tag "Tag name"))
  2393. (const :tag "Start radio group" (:startgroup))
  2394. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2395. (const :tag "Group tags delimiter" (:grouptags))
  2396. (const :tag "End radio group" (:endgroup))
  2397. (const :tag "End tag group, non distinct" (:endgrouptag))
  2398. (const :tag "New line" (:newline)))))
  2399. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2400. "If non-nil, always offer completion for all tags of all agenda files.
  2401. Setting this variable locally allows for dynamic generation of tag
  2402. completions in capture buffers.
  2403. (add-hook \\='org-capture-mode-hook
  2404. (lambda ()
  2405. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2406. :group 'org-tags
  2407. :version "24.1"
  2408. :type 'boolean)
  2409. (defvar org-file-tags nil
  2410. "List of tags that can be inherited by all entries in the file.
  2411. The tags will be inherited if the variable `org-use-tag-inheritance'
  2412. says they should be.
  2413. This variable is populated from #+FILETAGS lines.")
  2414. (defcustom org-use-fast-tag-selection 'auto
  2415. "Non-nil means use fast tag selection scheme.
  2416. This is a special interface to select and deselect tags with single keys.
  2417. When nil, fast selection is never used.
  2418. When the symbol `auto', fast selection is used if and only if selection
  2419. characters for tags have been configured, either through the variable
  2420. `org-tag-alist' or through a #+TAGS line in the buffer.
  2421. When t, fast selection is always used and selection keys are assigned
  2422. automatically if necessary."
  2423. :group 'org-tags
  2424. :type '(choice
  2425. (const :tag "Always" t)
  2426. (const :tag "Never" nil)
  2427. (const :tag "When selection characters are configured" auto)))
  2428. (defcustom org-fast-tag-selection-single-key nil
  2429. "Non-nil means fast tag selection exits after first change.
  2430. When nil, you have to press RET to exit it.
  2431. During fast tag selection, you can toggle this flag with `C-c'.
  2432. This variable can also have the value `expert'. In this case, the window
  2433. displaying the tags menu is not even shown, until you press `C-c' again."
  2434. :group 'org-tags
  2435. :type '(choice
  2436. (const :tag "No" nil)
  2437. (const :tag "Yes" t)
  2438. (const :tag "Expert" expert)))
  2439. (defvar org-fast-tag-selection-include-todo nil
  2440. "Non-nil means fast tags selection interface will also offer TODO states.
  2441. This is an undocumented feature, you should not rely on it.")
  2442. (defcustom org-tags-column -77
  2443. "The column to which tags should be indented in a headline.
  2444. If this number is positive, it specifies the column. If it is negative,
  2445. it means that the tags should be flushright to that column. For example,
  2446. -80 works well for a normal 80 character screen.
  2447. When 0, place tags directly after headline text, with only one space in
  2448. between."
  2449. :group 'org-tags
  2450. :type 'integer)
  2451. (defcustom org-auto-align-tags t
  2452. "Non-nil keeps tags aligned when modifying headlines.
  2453. Some operations (i.e. demoting) change the length of a headline and
  2454. therefore shift the tags around. With this option turned on, after
  2455. each such operation the tags are again aligned to `org-tags-column'."
  2456. :group 'org-tags
  2457. :type 'boolean)
  2458. (defcustom org-use-tag-inheritance t
  2459. "Non-nil means tags in levels apply also for sublevels.
  2460. When nil, only the tags directly given in a specific line apply there.
  2461. This may also be a list of tags that should be inherited, or a regexp that
  2462. matches tags that should be inherited. Additional control is possible
  2463. with the variable `org-tags-exclude-from-inheritance' which gives an
  2464. explicit list of tags to be excluded from inheritance, even if the value of
  2465. `org-use-tag-inheritance' would select it for inheritance.
  2466. If this option is t, a match early-on in a tree can lead to a large
  2467. number of matches in the subtree when constructing the agenda or creating
  2468. a sparse tree. If you only want to see the first match in a tree during
  2469. a search, check out the variable `org-tags-match-list-sublevels'."
  2470. :group 'org-tags
  2471. :type '(choice
  2472. (const :tag "Not" nil)
  2473. (const :tag "Always" t)
  2474. (repeat :tag "Specific tags" (string :tag "Tag"))
  2475. (regexp :tag "Tags matched by regexp")))
  2476. (defcustom org-tags-exclude-from-inheritance nil
  2477. "List of tags that should never be inherited.
  2478. This is a way to exclude a few tags from inheritance. For way to do
  2479. the opposite, to actively allow inheritance for selected tags,
  2480. see the variable `org-use-tag-inheritance'."
  2481. :group 'org-tags
  2482. :type '(repeat (string :tag "Tag")))
  2483. (defun org-tag-inherit-p (tag)
  2484. "Check if TAG is one that should be inherited."
  2485. (cond
  2486. ((member tag org-tags-exclude-from-inheritance) nil)
  2487. ((eq org-use-tag-inheritance t) t)
  2488. ((not org-use-tag-inheritance) nil)
  2489. ((stringp org-use-tag-inheritance)
  2490. (string-match org-use-tag-inheritance tag))
  2491. ((listp org-use-tag-inheritance)
  2492. (member tag org-use-tag-inheritance))
  2493. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2494. (defcustom org-tags-match-list-sublevels t
  2495. "Non-nil means list also sublevels of headlines matching a search.
  2496. This variable applies to tags/property searches, and also to stuck
  2497. projects because this search is based on a tags match as well.
  2498. When set to the symbol `indented', sublevels are indented with
  2499. leading dots.
  2500. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2501. the sublevels of a headline matching a tag search often also match
  2502. the same search. Listing all of them can create very long lists.
  2503. Setting this variable to nil causes subtrees of a match to be skipped.
  2504. This variable is semi-obsolete and probably should always be true. It
  2505. is better to limit inheritance to certain tags using the variables
  2506. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2507. :group 'org-tags
  2508. :type '(choice
  2509. (const :tag "No, don't list them" nil)
  2510. (const :tag "Yes, do list them" t)
  2511. (const :tag "List them, indented with leading dots" indented)))
  2512. (defcustom org-tags-sort-function nil
  2513. "When set, tags are sorted using this function as a comparator."
  2514. :group 'org-tags
  2515. :type '(choice
  2516. (const :tag "No sorting" nil)
  2517. (const :tag "Alphabetical" org-string-collate-lessp)
  2518. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2519. (function :tag "Custom function" nil)))
  2520. (defvar org-tags-history nil
  2521. "History of minibuffer reads for tags.")
  2522. (defvar org-last-tags-completion-table nil
  2523. "The last used completion table for tags.")
  2524. (defvar org-after-tags-change-hook nil
  2525. "Hook that is run after the tags in a line have changed.")
  2526. (defgroup org-properties nil
  2527. "Options concerning properties in Org mode."
  2528. :tag "Org Properties"
  2529. :group 'org)
  2530. (defcustom org-property-format "%-10s %s"
  2531. "How property key/value pairs should be formatted by `indent-line'.
  2532. When `indent-line' hits a property definition, it will format the line
  2533. according to this format, mainly to make sure that the values are
  2534. lined-up with respect to each other."
  2535. :group 'org-properties
  2536. :type 'string)
  2537. (defcustom org-properties-postprocess-alist nil
  2538. "Alist of properties and functions to adjust inserted values.
  2539. Elements of this alist must be of the form
  2540. ([string] [function])
  2541. where [string] must be a property name and [function] must be a
  2542. lambda expression: this lambda expression must take one argument,
  2543. the value to adjust, and return the new value as a string.
  2544. For example, this element will allow the property \"Remaining\"
  2545. to be updated wrt the relation between the \"Effort\" property
  2546. and the clock summary:
  2547. ((\"Remaining\" (lambda(value)
  2548. (let ((clocksum (org-clock-sum-current-item))
  2549. (effort (org-duration-to-minutes
  2550. (org-entry-get (point) \"Effort\"))))
  2551. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2552. :group 'org-properties
  2553. :version "24.1"
  2554. :type '(alist :key-type (string :tag "Property")
  2555. :value-type (function :tag "Function")))
  2556. (defcustom org-use-property-inheritance nil
  2557. "Non-nil means properties apply also for sublevels.
  2558. This setting is chiefly used during property searches. Turning it on can
  2559. cause significant overhead when doing a search, which is why it is not
  2560. on by default.
  2561. When nil, only the properties directly given in the current entry count.
  2562. When t, every property is inherited. The value may also be a list of
  2563. properties that should have inheritance, or a regular expression matching
  2564. properties that should be inherited.
  2565. However, note that some special properties use inheritance under special
  2566. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2567. and the properties ending in \"_ALL\" when they are used as descriptor
  2568. for valid values of a property.
  2569. Note for programmers:
  2570. When querying an entry with `org-entry-get', you can control if inheritance
  2571. should be used. By default, `org-entry-get' looks only at the local
  2572. properties. You can request inheritance by setting the inherit argument
  2573. to t (to force inheritance) or to `selective' (to respect the setting
  2574. in this variable)."
  2575. :group 'org-properties
  2576. :type '(choice
  2577. (const :tag "Not" nil)
  2578. (const :tag "Always" t)
  2579. (repeat :tag "Specific properties" (string :tag "Property"))
  2580. (regexp :tag "Properties matched by regexp")))
  2581. (defun org-property-inherit-p (property)
  2582. "Return a non-nil value if PROPERTY should be inherited."
  2583. (cond
  2584. ((eq org-use-property-inheritance t) t)
  2585. ((not org-use-property-inheritance) nil)
  2586. ((stringp org-use-property-inheritance)
  2587. (string-match org-use-property-inheritance property))
  2588. ((listp org-use-property-inheritance)
  2589. (member-ignore-case property org-use-property-inheritance))
  2590. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2591. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2592. "The default column format, if no other format has been defined.
  2593. This variable can be set on the per-file basis by inserting a line
  2594. #+COLUMNS: %25ITEM ....."
  2595. :group 'org-properties
  2596. :type 'string)
  2597. (defcustom org-columns-default-format-for-agenda nil
  2598. "The default column format in an agenda buffer.
  2599. This will be used for column view in the agenda unless a format has
  2600. been set by adding `org-overriding-columns-format' to the local
  2601. settings list of a custom agenda view. When nil, the columns format
  2602. for the first item in the agenda list will be used, or as a fall-back,
  2603. `org-columns-default-format'."
  2604. :group 'org-properties
  2605. :type '(choice
  2606. (const :tag "No default" nil)
  2607. (string :tag "Format string")))
  2608. (defcustom org-columns-ellipses ".."
  2609. "The ellipses to be used when a field in column view is truncated.
  2610. When this is the empty string, as many characters as possible are shown,
  2611. but then there will be no visual indication that the field has been truncated.
  2612. When this is a string of length N, the last N characters of a truncated
  2613. field are replaced by this string. If the column is narrower than the
  2614. ellipses string, only part of the ellipses string will be shown."
  2615. :group 'org-properties
  2616. :type 'string)
  2617. (defconst org-global-properties-fixed
  2618. '(("VISIBILITY_ALL" . "folded children content all")
  2619. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2620. "List of property/value pairs that can be inherited by any entry.
  2621. These are fixed values, for the preset properties. The user variable
  2622. that can be used to add to this list is `org-global-properties'.
  2623. The entries in this list are cons cells where the car is a property
  2624. name and cdr is a string with the value. If the value represents
  2625. multiple items like an \"_ALL\" property, separate the items by
  2626. spaces.")
  2627. (defcustom org-global-properties nil
  2628. "List of property/value pairs that can be inherited by any entry.
  2629. This list will be combined with the constant `org-global-properties-fixed'.
  2630. The entries in this list are cons cells where the car is a property
  2631. name and cdr is a string with the value.
  2632. Buffer local properties are added either by a document property drawer
  2633. :PROPERTIES:
  2634. :NAME: VALUE
  2635. :END:
  2636. or by adding lines like
  2637. #+PROPERTY: NAME VALUE"
  2638. :group 'org-properties
  2639. :type '(repeat
  2640. (cons (string :tag "Property")
  2641. (string :tag "Value"))))
  2642. (defvar-local org-keyword-properties nil
  2643. "List of property/value pairs inherited by any entry.
  2644. Valid for the current buffer. This variable is populated from
  2645. PROPERTY keywords.
  2646. Note that properties are defined also in property drawers.
  2647. Properties defined there take precedence over properties defined
  2648. as keywords.")
  2649. (defgroup org-agenda nil
  2650. "Options concerning agenda views in Org mode."
  2651. :tag "Org Agenda"
  2652. :group 'org)
  2653. (defvar-local org-category nil
  2654. "Variable used by Org files to set a category for agenda display.
  2655. There are multiple ways to set the category. One way is to set
  2656. it in the document property drawer. For example:
  2657. :PROPERTIES:
  2658. :CATEGORY: ELisp
  2659. :END:
  2660. Other ways to define it is as an emacs file variable, for example
  2661. # -*- mode: org; org-category: \"ELisp\"
  2662. or for the file to contain a special line:
  2663. #+CATEGORY: ELisp
  2664. If the file does not specify a category, then file's base name
  2665. is used instead.")
  2666. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2667. (defcustom org-agenda-files nil
  2668. "The files to be used for agenda display.
  2669. If an entry is a directory, all files in that directory that are matched
  2670. by `org-agenda-file-regexp' will be part of the file list.
  2671. If the value of the variable is not a list but a single file name, then
  2672. the list of agenda files is actually stored and maintained in that file,
  2673. one agenda file per line. In this file paths can be given relative to
  2674. `org-directory'. Tilde expansion and environment variable substitution
  2675. are also made.
  2676. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2677. and removed with `\\[org-remove-file]'."
  2678. :group 'org-agenda
  2679. :type '(choice
  2680. (repeat :tag "List of files and directories" file)
  2681. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2682. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2683. "Regular expression to match files for `org-agenda-files'.
  2684. If any element in the list in that variable contains a directory instead
  2685. of a normal file, all files in that directory that are matched by this
  2686. regular expression will be included."
  2687. :group 'org-agenda
  2688. :type 'regexp)
  2689. (defvaralias 'org-agenda-multi-occur-extra-files
  2690. 'org-agenda-text-search-extra-files)
  2691. (defcustom org-agenda-text-search-extra-files nil
  2692. "List of extra files to be searched by text search commands.
  2693. These files will be searched in addition to the agenda files by the
  2694. commands `org-search-view' (`\\[org-agenda] s') \
  2695. and `org-occur-in-agenda-files'.
  2696. Note that these files will only be searched for text search commands,
  2697. not for the other agenda views like todo lists, tag searches or the weekly
  2698. agenda. This variable is intended to list notes and possibly archive files
  2699. that should also be searched by these two commands.
  2700. In fact, if the first element in the list is the symbol `agenda-archives',
  2701. then all archive files of all agenda files will be added to the search
  2702. scope."
  2703. :group 'org-agenda
  2704. :type '(set :greedy t
  2705. (const :tag "Agenda Archives" agenda-archives)
  2706. (repeat :inline t (file))))
  2707. (defcustom org-agenda-skip-unavailable-files nil
  2708. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2709. A nil value means to remove them, after a query, from the list."
  2710. :group 'org-agenda
  2711. :type 'boolean)
  2712. (defgroup org-latex nil
  2713. "Options for embedding LaTeX code into Org mode."
  2714. :tag "Org LaTeX"
  2715. :group 'org)
  2716. (defcustom org-format-latex-options
  2717. '(:foreground default :background default :scale 1.0
  2718. :html-foreground "Black" :html-background "Transparent"
  2719. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2720. "Options for creating images from LaTeX fragments.
  2721. This is a property list with the following properties:
  2722. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2723. `default' means use the foreground of the default face.
  2724. `auto' means use the foreground from the text face.
  2725. :background the background color, or \"Transparent\".
  2726. `default' means use the background of the default face.
  2727. `auto' means use the background from the text face.
  2728. :scale a scaling factor for the size of the images, to get more pixels
  2729. :html-foreground, :html-background, :html-scale
  2730. the same numbers for HTML export.
  2731. :matchers a list indicating which matchers should be used to
  2732. find LaTeX fragments. Valid members of this list are:
  2733. \"begin\" find environments
  2734. \"$1\" find single characters surrounded by $.$
  2735. \"$\" find math expressions surrounded by $...$
  2736. \"$$\" find math expressions surrounded by $$....$$
  2737. \"\\(\" find math expressions surrounded by \\(...\\)
  2738. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2739. :group 'org-latex
  2740. :type 'plist)
  2741. (defcustom org-format-latex-signal-error t
  2742. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2743. When nil, just push out a message."
  2744. :group 'org-latex
  2745. :version "24.1"
  2746. :type 'boolean)
  2747. (defcustom org-latex-to-mathml-jar-file nil
  2748. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2749. Use this to specify additional executable file say a jar file.
  2750. When using MathToWeb as the converter, specify the full-path to
  2751. your mathtoweb.jar file."
  2752. :group 'org-latex
  2753. :version "24.1"
  2754. :type '(choice
  2755. (const :tag "None" nil)
  2756. (file :tag "JAR file" :must-match t)))
  2757. (defcustom org-latex-to-mathml-convert-command nil
  2758. "Command to convert LaTeX fragments to MathML.
  2759. Replace format-specifiers in the command as noted below and use
  2760. `shell-command' to convert LaTeX to MathML.
  2761. %j: Executable file in fully expanded form as specified by
  2762. `org-latex-to-mathml-jar-file'.
  2763. %I: Input LaTeX file in fully expanded form.
  2764. %i: The latex fragment to be converted.
  2765. %o: Output MathML file.
  2766. This command is used by `org-create-math-formula'.
  2767. When using MathToWeb as the converter, set this option to
  2768. \"java -jar %j -unicode -force -df %o %I\".
  2769. When using LaTeXML set this option to
  2770. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2771. :group 'org-latex
  2772. :version "24.1"
  2773. :type '(choice
  2774. (const :tag "None" nil)
  2775. (string :tag "\nShell command")))
  2776. (defcustom org-latex-to-html-convert-command nil
  2777. "Command to convert LaTeX fragments to HTML.
  2778. This command is very open-ended: the output of the command will
  2779. directly replace the LaTeX fragment in the resulting HTML.
  2780. Replace format-specifiers in the command as noted below and use
  2781. `shell-command' to convert LaTeX to HTML.
  2782. %i: The LaTeX fragment to be converted.
  2783. For example, this could be used with LaTeXML as
  2784. \"latexmlc 'literal:%i' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2785. :group 'org-latex
  2786. :package-version '(Org . "9.4")
  2787. :type '(choice
  2788. (const :tag "None" nil)
  2789. (string :tag "Shell command")))
  2790. (defcustom org-preview-latex-default-process 'dvipng
  2791. "The default process to convert LaTeX fragments to image files.
  2792. All available processes and theirs documents can be found in
  2793. `org-preview-latex-process-alist', which see."
  2794. :group 'org-latex
  2795. :version "26.1"
  2796. :package-version '(Org . "9.0")
  2797. :type 'symbol)
  2798. (defcustom org-preview-latex-process-alist
  2799. '((dvipng
  2800. :programs ("latex" "dvipng")
  2801. :description "dvi > png"
  2802. :message "you need to install the programs: latex and dvipng."
  2803. :image-input-type "dvi"
  2804. :image-output-type "png"
  2805. :image-size-adjust (1.0 . 1.0)
  2806. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2807. :image-converter ("dvipng -D %D -T tight -o %O %f"))
  2808. (dvisvgm
  2809. :programs ("latex" "dvisvgm")
  2810. :description "dvi > svg"
  2811. :message "you need to install the programs: latex and dvisvgm."
  2812. :image-input-type "dvi"
  2813. :image-output-type "svg"
  2814. :image-size-adjust (1.7 . 1.5)
  2815. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2816. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2817. (imagemagick
  2818. :programs ("latex" "convert")
  2819. :description "pdf > png"
  2820. :message "you need to install the programs: latex and imagemagick."
  2821. :image-input-type "pdf"
  2822. :image-output-type "png"
  2823. :image-size-adjust (1.0 . 1.0)
  2824. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2825. :image-converter
  2826. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2827. "Definitions of external processes for LaTeX previewing.
  2828. Org mode can use some external commands to generate TeX snippet's images for
  2829. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2830. `org-create-formula-image' how to call them.
  2831. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2832. PROPERTIES accepts the following attributes:
  2833. :programs list of strings, required programs.
  2834. :description string, describe the process.
  2835. :message string, message it when required programs cannot be found.
  2836. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2837. :image-output-type string, output file type of image converter (e.g., \"png\").
  2838. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2839. image size showed in buffer and the cdr element is for
  2840. HTML file. This option is only useful for process
  2841. developers, users should use variable
  2842. `org-format-latex-options' instead.
  2843. :post-clean list of strings, files matched are to be cleaned up once
  2844. the image is generated. When nil, the files with \".dvi\",
  2845. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2846. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2847. be cleaned up.
  2848. :latex-header list of strings, the LaTeX header of the snippet file.
  2849. When nil, the fallback value is used instead, which is
  2850. controlled by `org-format-latex-header',
  2851. `org-latex-default-packages-alist' and
  2852. `org-latex-packages-alist', which see.
  2853. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2854. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2855. replaced with values defined below.
  2856. :image-converter list of image converter commands strings. Each of them is
  2857. given to the shell and supports any of the following
  2858. place-holders defined below.
  2859. Place-holders used by `:image-converter' and `:latex-compiler':
  2860. %f input file name
  2861. %b base name of input file
  2862. %o base directory of input file
  2863. %O absolute output file name
  2864. Place-holders only used by `:image-converter':
  2865. %D dpi, which is used to adjust image size by some processing commands.
  2866. %S the image size scale ratio, which is used to adjust image size by some
  2867. processing commands."
  2868. :group 'org-latex
  2869. :version "26.1"
  2870. :package-version '(Org . "9.0")
  2871. :type '(alist :tag "LaTeX to image backends"
  2872. :value-type (plist)))
  2873. (defcustom org-preview-latex-image-directory "ltximg/"
  2874. "Path to store latex preview images.
  2875. A relative path here creates many directories relative to the
  2876. processed Org files paths. An absolute path puts all preview
  2877. images at the same place."
  2878. :group 'org-latex
  2879. :version "26.1"
  2880. :package-version '(Org . "9.0")
  2881. :type 'string)
  2882. (defun org-format-latex-mathml-available-p ()
  2883. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2884. (save-match-data
  2885. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2886. org-latex-to-mathml-convert-command)
  2887. (let ((executable (car (split-string
  2888. org-latex-to-mathml-convert-command))))
  2889. (when (executable-find executable)
  2890. (if (string-match
  2891. "%j" org-latex-to-mathml-convert-command)
  2892. (file-readable-p org-latex-to-mathml-jar-file)
  2893. t))))))
  2894. (defcustom org-format-latex-header "\\documentclass{article}
  2895. \\usepackage[usenames]{color}
  2896. \[PACKAGES]
  2897. \[DEFAULT-PACKAGES]
  2898. \\pagestyle{empty} % do not remove
  2899. % The settings below are copied from fullpage.sty
  2900. \\setlength{\\textwidth}{\\paperwidth}
  2901. \\addtolength{\\textwidth}{-3cm}
  2902. \\setlength{\\oddsidemargin}{1.5cm}
  2903. \\addtolength{\\oddsidemargin}{-2.54cm}
  2904. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2905. \\setlength{\\textheight}{\\paperheight}
  2906. \\addtolength{\\textheight}{-\\headheight}
  2907. \\addtolength{\\textheight}{-\\headsep}
  2908. \\addtolength{\\textheight}{-\\footskip}
  2909. \\addtolength{\\textheight}{-3cm}
  2910. \\setlength{\\topmargin}{1.5cm}
  2911. \\addtolength{\\topmargin}{-2.54cm}"
  2912. "The document header used for processing LaTeX fragments.
  2913. It is imperative that this header make sure that no page number
  2914. appears on the page. The package defined in the variables
  2915. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2916. will either replace the placeholder \"[PACKAGES]\" in this
  2917. header, or they will be appended."
  2918. :group 'org-latex
  2919. :type 'string)
  2920. (defun org-set-packages-alist (var val)
  2921. "Set the packages alist and make sure it has 3 elements per entry."
  2922. (set var (mapcar (lambda (x)
  2923. (if (and (consp x) (= (length x) 2))
  2924. (list (car x) (nth 1 x) t)
  2925. x))
  2926. val)))
  2927. (defun org-get-packages-alist (var)
  2928. "Get the packages alist and make sure it has 3 elements per entry."
  2929. (mapcar (lambda (x)
  2930. (if (and (consp x) (= (length x) 2))
  2931. (list (car x) (nth 1 x) t)
  2932. x))
  2933. (default-value var)))
  2934. (defcustom org-latex-default-packages-alist
  2935. '(("AUTO" "inputenc" t ("pdflatex"))
  2936. ("T1" "fontenc" t ("pdflatex"))
  2937. ("" "graphicx" t)
  2938. ("" "grffile" t)
  2939. ("" "longtable" nil)
  2940. ("" "wrapfig" nil)
  2941. ("" "rotating" nil)
  2942. ("normalem" "ulem" t)
  2943. ("" "amsmath" t)
  2944. ("" "textcomp" t)
  2945. ("" "amssymb" t)
  2946. ("" "capt-of" nil)
  2947. ("" "hyperref" nil))
  2948. "Alist of default packages to be inserted in the header.
  2949. Change this only if one of the packages here causes an
  2950. incompatibility with another package you are using.
  2951. The packages in this list are needed by one part or another of
  2952. Org mode to function properly:
  2953. - inputenc, fontenc: for basic font and character selection
  2954. - graphicx: for including images
  2955. - grffile: allow periods and spaces in graphics file names
  2956. - longtable: For multipage tables
  2957. - wrapfig: for figure placement
  2958. - rotating: for sideways figures and tables
  2959. - ulem: for underline and strike-through
  2960. - amsmath: for subscript and superscript and math environments
  2961. - textcomp, amssymb: for various symbols used
  2962. for interpreting the entities in `org-entities'. You can skip
  2963. some of these packages if you don't use any of their symbols.
  2964. - capt-of: for captions outside of floats
  2965. - hyperref: for cross references
  2966. Therefore you should not modify this variable unless you know
  2967. what you are doing. The one reason to change it anyway is that
  2968. you might be loading some other package that conflicts with one
  2969. of the default packages. Each element is either a cell or
  2970. a string.
  2971. A cell is of the format
  2972. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2973. If SNIPPET-FLAG is non-nil, the package also needs to be included
  2974. when compiling LaTeX snippets into images for inclusion into
  2975. non-LaTeX output.
  2976. COMPILERS is a list of compilers that should include the package,
  2977. see `org-latex-compiler'. If the document compiler is not in the
  2978. list, and the list is non-nil, the package will not be inserted
  2979. in the final document.
  2980. A string will be inserted as-is in the header of the document."
  2981. :group 'org-latex
  2982. :group 'org-export-latex
  2983. :set 'org-set-packages-alist
  2984. :get 'org-get-packages-alist
  2985. :version "26.1"
  2986. :package-version '(Org . "8.3")
  2987. :type '(repeat
  2988. (choice
  2989. (list :tag "options/package pair"
  2990. (string :tag "options")
  2991. (string :tag "package")
  2992. (boolean :tag "Snippet")
  2993. (choice
  2994. (const :tag "For all compilers" nil)
  2995. (repeat :tag "Allowed compiler" string)))
  2996. (string :tag "A line of LaTeX"))))
  2997. (defcustom org-latex-packages-alist nil
  2998. "Alist of packages to be inserted in every LaTeX header.
  2999. These will be inserted after `org-latex-default-packages-alist'.
  3000. Each element is either a cell or a string.
  3001. A cell is of the format:
  3002. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3003. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3004. needed when turning LaTeX snippets into images for inclusion into
  3005. non-LaTeX output.
  3006. COMPILERS is a list of compilers that should include the package,
  3007. see `org-latex-compiler'. If the document compiler is not in the
  3008. list, and the list is non-nil, the package will not be inserted
  3009. in the final document.
  3010. A string will be inserted as-is in the header of the document.
  3011. Make sure that you only list packages here which:
  3012. - you want in every file;
  3013. - do not conflict with the setup in `org-format-latex-header';
  3014. - do not conflict with the default packages in
  3015. `org-latex-default-packages-alist'."
  3016. :group 'org-latex
  3017. :group 'org-export-latex
  3018. :set 'org-set-packages-alist
  3019. :get 'org-get-packages-alist
  3020. :type '(repeat
  3021. (choice
  3022. (list :tag "options/package pair"
  3023. (string :tag "options")
  3024. (string :tag "package")
  3025. (boolean :tag "Snippet"))
  3026. (string :tag "A line of LaTeX"))))
  3027. (defgroup org-appearance nil
  3028. "Settings for Org mode appearance."
  3029. :tag "Org Appearance"
  3030. :group 'org)
  3031. (defcustom org-level-color-stars-only nil
  3032. "Non-nil means fontify only the stars in each headline.
  3033. When nil, the entire headline is fontified.
  3034. Changing it requires restart of `font-lock-mode' to become effective
  3035. also in regions already fontified."
  3036. :group 'org-appearance
  3037. :type 'boolean)
  3038. (defcustom org-hide-leading-stars nil
  3039. "Non-nil means hide the first N-1 stars in a headline.
  3040. This works by using the face `org-hide' for these stars. This
  3041. face is white for a light background, and black for a dark
  3042. background. You may have to customize the face `org-hide' to
  3043. make this work.
  3044. Changing it requires restart of `font-lock-mode' to become effective
  3045. also in regions already fontified.
  3046. You may also set this on a per-file basis by adding one of the following
  3047. lines to the buffer:
  3048. #+STARTUP: hidestars
  3049. #+STARTUP: showstars"
  3050. :group 'org-appearance
  3051. :type 'boolean)
  3052. (defcustom org-hidden-keywords nil
  3053. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3054. For example, a value \\='(title) for this list makes the document's title
  3055. appear in the buffer without the initial \"#+TITLE:\" part."
  3056. :group 'org-appearance
  3057. :version "24.1"
  3058. :type '(set (const :tag "#+AUTHOR" author)
  3059. (const :tag "#+DATE" date)
  3060. (const :tag "#+EMAIL" email)
  3061. (const :tag "#+TITLE" title)))
  3062. (defcustom org-custom-properties nil
  3063. "List of properties (as strings) with a special meaning.
  3064. The default use of these custom properties is to let the user
  3065. hide them with `org-toggle-custom-properties-visibility'."
  3066. :group 'org-properties
  3067. :group 'org-appearance
  3068. :version "24.3"
  3069. :type '(repeat (string :tag "Property Name")))
  3070. (defcustom org-fontify-todo-headline nil
  3071. "Non-nil means change the face of a headline if it is marked as TODO.
  3072. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3073. When this is non-nil, the headline after the keyword is set to the
  3074. `org-headline-todo' as an additional indication."
  3075. :group 'org-appearance
  3076. :package-version '(Org . "9.4")
  3077. :type 'boolean
  3078. :safe t)
  3079. (defcustom org-fontify-done-headline t
  3080. "Non-nil means change the face of a headline if it is marked DONE.
  3081. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3082. When this is non-nil, the headline after the keyword is set to the
  3083. `org-headline-done' as an additional indication."
  3084. :group 'org-appearance
  3085. :package-version '(Org . "9.4")
  3086. :type 'boolean)
  3087. (defcustom org-fontify-emphasized-text t
  3088. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3089. Changing this variable requires a restart of Emacs to take effect."
  3090. :group 'org-appearance
  3091. :type 'boolean)
  3092. (defcustom org-fontify-whole-heading-line nil
  3093. "Non-nil means fontify the whole line for headings.
  3094. This is useful when setting a background color for the
  3095. org-level-* faces."
  3096. :group 'org-appearance
  3097. :type 'boolean)
  3098. (defcustom org-fontify-whole-block-delimiter-line t
  3099. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3100. This is useful when setting a background color for the
  3101. org-block-begin-line and org-block-end-line faces."
  3102. :group 'org-appearance
  3103. :type 'boolean)
  3104. (defcustom org-highlight-latex-and-related nil
  3105. "Non-nil means highlight LaTeX related syntax in the buffer.
  3106. When non-nil, the value should be a list containing any of the
  3107. following symbols:
  3108. `native' Highlight LaTeX snippets and environments natively.
  3109. `latex' Highlight LaTeX snippets and environments.
  3110. `script' Highlight subscript and superscript.
  3111. `entities' Highlight entities."
  3112. :group 'org-appearance
  3113. :version "24.4"
  3114. :package-version '(Org . "8.0")
  3115. :type '(choice
  3116. (const :tag "No highlighting" nil)
  3117. (set :greedy t :tag "Highlight"
  3118. (const :tag "LaTeX snippets and environments (native)" native)
  3119. (const :tag "LaTeX snippets and environments" latex)
  3120. (const :tag "Subscript and superscript" script)
  3121. (const :tag "Entities" entities))))
  3122. (defcustom org-hide-emphasis-markers nil
  3123. "Non-nil mean font-lock should hide the emphasis marker characters."
  3124. :group 'org-appearance
  3125. :type 'boolean
  3126. :safe #'booleanp)
  3127. (defcustom org-hide-macro-markers nil
  3128. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3129. :group 'org-appearance
  3130. :type 'boolean)
  3131. (defcustom org-pretty-entities nil
  3132. "Non-nil means show entities as UTF8 characters.
  3133. When nil, the \\name form remains in the buffer."
  3134. :group 'org-appearance
  3135. :version "24.1"
  3136. :type 'boolean)
  3137. (defcustom org-pretty-entities-include-sub-superscripts t
  3138. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3139. :group 'org-appearance
  3140. :version "24.1"
  3141. :type 'boolean)
  3142. (defvar org-emph-re nil
  3143. "Regular expression for matching emphasis.
  3144. After a match, the match groups contain these elements:
  3145. 0 The match of the full regular expression, including the characters
  3146. before and after the proper match
  3147. 1 The character before the proper match, or empty at beginning of line
  3148. 2 The proper match, including the leading and trailing markers
  3149. 3 The leading marker like * or /, indicating the type of highlighting
  3150. 4 The text between the emphasis markers, not including the markers
  3151. 5 The character after the match, empty at the end of a line")
  3152. (defvar org-verbatim-re nil
  3153. "Regular expression for matching verbatim text.")
  3154. (defvar org-emphasis-regexp-components) ; defined just below
  3155. (defvar org-emphasis-alist) ; defined just below
  3156. (defun org-set-emph-re (var val)
  3157. "Set variable and compute the emphasis regular expression."
  3158. (set var val)
  3159. (when (and (boundp 'org-emphasis-alist)
  3160. (boundp 'org-emphasis-regexp-components)
  3161. org-emphasis-alist org-emphasis-regexp-components)
  3162. (pcase-let*
  3163. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3164. (body (if (<= nl 0) body
  3165. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3166. (template
  3167. (format (concat "\\([%s]\\|^\\)" ;before markers
  3168. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3169. "\\([%s]\\|$\\)") ;after markers
  3170. pre border border body border post)))
  3171. (setq org-emph-re (format template "*/_+"))
  3172. (setq org-verbatim-re (format template "=~")))))
  3173. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3174. ;; set this option proved cumbersome. See this message/thread:
  3175. ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
  3176. (defvar org-emphasis-regexp-components
  3177. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3178. "Components used to build the regular expression for emphasis.
  3179. This is a list with five entries. Terminology: In an emphasis string
  3180. like \" *strong word* \", we call the initial space PREMATCH, the final
  3181. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3182. and \"trong wor\" is the body. The different components in this variable
  3183. specify what is allowed/forbidden in each part:
  3184. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3185. post Chars allowed as postmatch. End of line will be allowed too.
  3186. border The chars *forbidden* as border characters.
  3187. body-regexp A regexp like \".\" to match a body character. Don't use
  3188. non-shy groups here, and don't allow newline here.
  3189. newline The maximum number of newlines allowed in an emphasis exp.
  3190. You need to reload Org or to restart Emacs after setting this.")
  3191. (defcustom org-emphasis-alist
  3192. '(("*" bold)
  3193. ("/" italic)
  3194. ("_" underline)
  3195. ("=" org-verbatim verbatim)
  3196. ("~" org-code verbatim)
  3197. ("+" (:strike-through t)))
  3198. "Alist of characters and faces to emphasize text.
  3199. Text starting and ending with a special character will be emphasized,
  3200. for example *bold*, _underlined_ and /italic/. This variable sets the
  3201. marker characters and the face to be used by font-lock for highlighting
  3202. in Org buffers.
  3203. You need to reload Org or to restart Emacs after customizing this."
  3204. :group 'org-appearance
  3205. :set 'org-set-emph-re
  3206. :version "24.4"
  3207. :package-version '(Org . "8.0")
  3208. :type '(repeat
  3209. (list
  3210. (string :tag "Marker character")
  3211. (choice
  3212. (face :tag "Font-lock-face")
  3213. (plist :tag "Face property list"))
  3214. (option (const verbatim)))))
  3215. (defvar org-protecting-blocks '("src" "example" "export")
  3216. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3217. This is needed for font-lock setup.")
  3218. ;;; Functions and variables from their packages
  3219. ;; Declared here to avoid compiler warnings
  3220. (defvar mark-active)
  3221. ;; Various packages
  3222. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3223. (declare-function calendar-forward-day "cal-move" (arg))
  3224. (declare-function calendar-goto-date "cal-move" (date))
  3225. (declare-function calendar-goto-today "cal-move" ())
  3226. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3227. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3228. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3229. (declare-function cdlatex-tab "ext:cdlatex" ())
  3230. (declare-function dired-get-filename
  3231. "dired"
  3232. (&optional localp no-error-if-not-filep))
  3233. (declare-function iswitchb-read-buffer
  3234. "iswitchb"
  3235. (prompt &optional
  3236. default require-match _predicate start matches-set))
  3237. (declare-function org-agenda-change-all-lines
  3238. "org-agenda"
  3239. (newhead hdmarker &optional fixface just-this))
  3240. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3241. "org-agenda"
  3242. (&optional end))
  3243. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3244. (declare-function org-agenda-format-item
  3245. "org-agenda"
  3246. (extra txt &optional level category tags dotime
  3247. remove-re habitp))
  3248. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3249. (declare-function org-agenda-save-markers-for-cut-and-paste
  3250. "org-agenda"
  3251. (beg end))
  3252. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3253. (declare-function org-agenda-skip "org-agenda" ())
  3254. (declare-function org-attach-expand "org-attach" (file))
  3255. (declare-function org-attach-reveal "org-attach" ())
  3256. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3257. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3258. (declare-function org-indent-mode "org-indent" (&optional arg))
  3259. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3260. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3261. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3262. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3263. (declare-function parse-time-string "parse-time" (string))
  3264. (defvar align-mode-rules-list)
  3265. (defvar calc-embedded-close-formula)
  3266. (defvar calc-embedded-open-formula)
  3267. (defvar calc-embedded-open-mode)
  3268. (defvar font-lock-unfontify-region-function)
  3269. (defvar iswitchb-temp-buflist)
  3270. (defvar org-agenda-tags-todo-honor-ignore-options)
  3271. (defvar remember-data-file)
  3272. (defvar texmathp-why)
  3273. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3274. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3275. (declare-function org-resolve-clocks "org-clock"
  3276. (&optional also-non-dangling-p prompt last-valid))
  3277. (defvar org-clock-start-time)
  3278. (defvar org-clock-marker (make-marker)
  3279. "Marker recording the last clock-in.")
  3280. (defvar org-clock-hd-marker (make-marker)
  3281. "Marker recording the last clock-in, but the headline position.")
  3282. (defvar org-clock-heading ""
  3283. "The heading of the current clock entry.")
  3284. (defun org-clock-is-active ()
  3285. "Return the buffer where the clock is currently running.
  3286. Return nil if no clock is running."
  3287. (marker-buffer org-clock-marker))
  3288. (defun org-check-running-clock ()
  3289. "Check if the current buffer contains the running clock.
  3290. If yes, offer to stop it and to save the buffer with the changes."
  3291. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3292. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3293. (buffer-name))))
  3294. (org-clock-out)
  3295. (when (y-or-n-p "Save changed buffer?")
  3296. (save-buffer))))
  3297. (defun org-clocktable-try-shift (dir n)
  3298. "Check if this line starts a clock table, if yes, shift the time block."
  3299. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3300. (org-clocktable-shift dir n)))
  3301. ;;;###autoload
  3302. (defun org-clock-persistence-insinuate ()
  3303. "Set up hooks for clock persistence."
  3304. (require 'org-clock)
  3305. (add-hook 'org-mode-hook 'org-clock-load)
  3306. (add-hook 'kill-emacs-hook 'org-clock-save))
  3307. (defun org-clock-auto-clockout-insinuate ()
  3308. "Set up hook for auto clocking out when Emacs is idle.
  3309. See `org-clock-auto-clockout-timer'.
  3310. This function is meant to be added to the user configuration."
  3311. (require 'org-clock)
  3312. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3313. (defgroup org-archive nil
  3314. "Options concerning archiving in Org mode."
  3315. :tag "Org Archive"
  3316. :group 'org-structure)
  3317. (defcustom org-archive-location "%s_archive::"
  3318. "The location where subtrees should be archived.
  3319. The value of this variable is a string, consisting of two parts,
  3320. separated by a double-colon. The first part is a filename and
  3321. the second part is a headline.
  3322. When the filename is omitted, archiving happens in the same file.
  3323. %s in the filename will be replaced by the current file
  3324. name (without the directory part). Archiving to a different file
  3325. is useful to keep archived entries from contributing to the
  3326. Org Agenda.
  3327. The archived entries will be filed as subtrees of the specified
  3328. headline. When the headline is omitted, the subtrees are simply
  3329. filed away at the end of the file, as top-level entries. Also in
  3330. the heading you can use %s to represent the file name, this can be
  3331. useful when using the same archive for a number of different files.
  3332. Here are a few examples:
  3333. \"%s_archive::\"
  3334. If the current file is Projects.org, archive in file
  3335. Projects.org_archive, as top-level trees. This is the default.
  3336. \"::* Archived Tasks\"
  3337. Archive in the current file, under the top-level headline
  3338. \"* Archived Tasks\".
  3339. \"~/org/archive.org::\"
  3340. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3341. \"~/org/archive.org::* From %s\"
  3342. Archive in file ~/org/archive.org (absolute path), under headlines
  3343. \"From FILENAME\" where file name is the current file name.
  3344. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3345. The \"datetree/\" string is special, signifying to archive
  3346. items to the datetree. Items are placed in either the CLOSED
  3347. date of the item, or the current date if there is no CLOSED date.
  3348. The heading will be a subentry to the current date. There doesn't
  3349. need to be a heading, but there always needs to be a slash after
  3350. datetree. For example, to store archived items directly in the
  3351. datetree, use \"~/org/datetree.org::datetree/\".
  3352. \"basement::** Finished Tasks\"
  3353. Archive in file ./basement (relative path), as level 3 trees
  3354. below the level 2 heading \"** Finished Tasks\".
  3355. You may define it locally by setting an ARCHIVE property. If
  3356. such a property is found in the file or in an entry, and anywhere
  3357. up the hierarchy, it will be used.
  3358. You can also set it for the whole file using the keyword-syntax:
  3359. #+ARCHIVE: basement::** Finished Tasks"
  3360. :group 'org-archive
  3361. :type 'string)
  3362. (defcustom org-agenda-skip-archived-trees t
  3363. "Non-nil means the agenda will skip any items located in archived trees.
  3364. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3365. variable is no longer recommended, you should leave it at the value t.
  3366. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3367. :group 'org-archive
  3368. :group 'org-agenda-skip
  3369. :type 'boolean)
  3370. (defcustom org-columns-skip-archived-trees t
  3371. "Non-nil means ignore archived trees when creating column view."
  3372. :group 'org-archive
  3373. :group 'org-properties
  3374. :type 'boolean)
  3375. (defcustom org-cycle-open-archived-trees nil
  3376. "Non-nil means `org-cycle' will open archived trees.
  3377. An archived tree is a tree marked with the tag ARCHIVE.
  3378. When nil, archived trees will stay folded. You can still open them with
  3379. normal outline commands like `show-all', but not with the cycling commands."
  3380. :group 'org-archive
  3381. :group 'org-cycle
  3382. :type 'boolean)
  3383. (defcustom org-sparse-tree-open-archived-trees nil
  3384. "Non-nil means sparse tree construction shows matches in archived trees.
  3385. When nil, matches in these trees are highlighted, but the trees are kept in
  3386. collapsed state."
  3387. :group 'org-archive
  3388. :group 'org-sparse-trees
  3389. :type 'boolean)
  3390. (defcustom org-sparse-tree-default-date-type nil
  3391. "The default date type when building a sparse tree.
  3392. When this is nil, a date is a scheduled or a deadline timestamp.
  3393. Otherwise, these types are allowed:
  3394. all: all timestamps
  3395. active: only active timestamps (<...>)
  3396. inactive: only inactive timestamps ([...])
  3397. scheduled: only scheduled timestamps
  3398. deadline: only deadline timestamps"
  3399. :type '(choice (const :tag "Scheduled or deadline" nil)
  3400. (const :tag "All timestamps" all)
  3401. (const :tag "Only active timestamps" active)
  3402. (const :tag "Only inactive timestamps" inactive)
  3403. (const :tag "Only scheduled timestamps" scheduled)
  3404. (const :tag "Only deadline timestamps" deadline)
  3405. (const :tag "Only closed timestamps" closed))
  3406. :version "26.1"
  3407. :package-version '(Org . "8.3")
  3408. :group 'org-sparse-trees)
  3409. (defun org-cycle-hide-archived-subtrees (state)
  3410. "Re-hide all archived subtrees after a visibility state change.
  3411. STATE should be one of the symbols listed in the docstring of
  3412. `org-cycle-hook'."
  3413. (when (and (not org-cycle-open-archived-trees)
  3414. (not (memq state '(overview folded))))
  3415. (save-excursion
  3416. (let* ((globalp (memq state '(contents all)))
  3417. (beg (if globalp (point-min) (point)))
  3418. (end (if globalp (point-max) (org-end-of-subtree t))))
  3419. (org-hide-archived-subtrees beg end)
  3420. (goto-char beg)
  3421. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3422. (message "%s" (substitute-command-keys
  3423. "Subtree is archived and stays closed. Use \
  3424. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3425. (defun org-force-cycle-archived ()
  3426. "Cycle subtree even if it is archived."
  3427. (interactive)
  3428. (setq this-command 'org-cycle)
  3429. (let ((org-cycle-open-archived-trees t))
  3430. (call-interactively 'org-cycle)))
  3431. (defun org-hide-archived-subtrees (beg end)
  3432. "Re-hide all archived subtrees after a visibility state change."
  3433. (org-with-wide-buffer
  3434. (let ((case-fold-search nil)
  3435. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3436. (goto-char beg)
  3437. ;; Include headline point is currently on.
  3438. (beginning-of-line)
  3439. (while (and (< (point) end) (re-search-forward re end t))
  3440. (when (member org-archive-tag (org-get-tags nil t))
  3441. (org-flag-subtree t)
  3442. (org-end-of-subtree t))))))
  3443. (defun org-flag-subtree (flag)
  3444. (save-excursion
  3445. (org-back-to-heading t)
  3446. (org-flag-region (line-end-position)
  3447. (progn (org-end-of-subtree t) (point))
  3448. flag
  3449. 'outline)))
  3450. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3451. ;; Declare Column View Code
  3452. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3453. (declare-function org-columns-compute "org-colview" (property))
  3454. ;; Declare ID code
  3455. (declare-function org-id-store-link "org-id")
  3456. (declare-function org-id-locations-load "org-id")
  3457. (declare-function org-id-locations-save "org-id")
  3458. (defvar org-id-track-globally)
  3459. ;;; Variables for pre-computed regular expressions, all buffer local
  3460. (defvar-local org-todo-regexp nil
  3461. "Matches any of the TODO state keywords.
  3462. Since TODO keywords are case-sensitive, `case-fold-search' is
  3463. expected to be bound to nil when matching against this regexp.")
  3464. (defvar-local org-not-done-regexp nil
  3465. "Matches any of the TODO state keywords except the last one.
  3466. Since TODO keywords are case-sensitive, `case-fold-search' is
  3467. expected to be bound to nil when matching against this regexp.")
  3468. (defvar-local org-not-done-heading-regexp nil
  3469. "Matches a TODO headline that is not done.
  3470. Since TODO keywords are case-sensitive, `case-fold-search' is
  3471. expected to be bound to nil when matching against this regexp.")
  3472. (defvar-local org-todo-line-regexp nil
  3473. "Matches a headline and puts TODO state into group 2 if present.
  3474. Since TODO keywords are case-sensitive, `case-fold-search' is
  3475. expected to be bound to nil when matching against this regexp.")
  3476. (defvar-local org-complex-heading-regexp nil
  3477. "Matches a headline and puts everything into groups:
  3478. group 1: Stars
  3479. group 2: The TODO keyword, maybe
  3480. group 3: Priority cookie
  3481. group 4: True headline
  3482. group 5: Tags
  3483. Since TODO keywords are case-sensitive, `case-fold-search' is
  3484. expected to be bound to nil when matching against this regexp.")
  3485. (defvar-local org-complex-heading-regexp-format nil
  3486. "Printf format to make regexp to match an exact headline.
  3487. This regexp will match the headline of any node which has the
  3488. exact headline text that is put into the format, but may have any
  3489. TODO state, priority and tags.")
  3490. (defvar-local org-todo-line-tags-regexp nil
  3491. "Matches a headline and puts TODO state into group 2 if present.
  3492. Also put tags into group 4 if tags are present.")
  3493. (defconst org-plain-time-of-day-regexp
  3494. (concat
  3495. "\\(\\<[012]?[0-9]"
  3496. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3497. "\\(--?"
  3498. "\\(\\<[012]?[0-9]"
  3499. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3500. "\\)?")
  3501. "Regular expression to match a plain time or time range.
  3502. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3503. groups carry important information:
  3504. 0 the full match
  3505. 1 the first time, range or not
  3506. 8 the second time, if it is a range.")
  3507. (defconst org-plain-time-extension-regexp
  3508. (concat
  3509. "\\(\\<[012]?[0-9]"
  3510. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3511. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3512. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3513. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3514. groups carry important information:
  3515. 0 the full match
  3516. 7 hours of duration
  3517. 9 minutes of duration")
  3518. (defconst org-stamp-time-of-day-regexp
  3519. (concat
  3520. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3521. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  3522. "\\(--?"
  3523. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3524. "Regular expression to match a timestamp time or time range.
  3525. After a match, the following groups carry important information:
  3526. 0 the full match
  3527. 1 date plus weekday, for back referencing to make sure both times are on the same day
  3528. 2 the first time, range or not
  3529. 4 the second time, if it is a range.")
  3530. (defconst org-startup-options
  3531. '(("fold" org-startup-folded t)
  3532. ("overview" org-startup-folded t)
  3533. ("nofold" org-startup-folded nil)
  3534. ("showall" org-startup-folded nil)
  3535. ("showeverything" org-startup-folded showeverything)
  3536. ("content" org-startup-folded content)
  3537. ("indent" org-startup-indented t)
  3538. ("noindent" org-startup-indented nil)
  3539. ("num" org-startup-numerated t)
  3540. ("nonum" org-startup-numerated nil)
  3541. ("hidestars" org-hide-leading-stars t)
  3542. ("showstars" org-hide-leading-stars nil)
  3543. ("odd" org-odd-levels-only t)
  3544. ("oddeven" org-odd-levels-only nil)
  3545. ("align" org-startup-align-all-tables t)
  3546. ("noalign" org-startup-align-all-tables nil)
  3547. ("shrink" org-startup-shrink-all-tables t)
  3548. ("inlineimages" org-startup-with-inline-images t)
  3549. ("noinlineimages" org-startup-with-inline-images nil)
  3550. ("latexpreview" org-startup-with-latex-preview t)
  3551. ("nolatexpreview" org-startup-with-latex-preview nil)
  3552. ("customtime" org-display-custom-times t)
  3553. ("logdone" org-log-done time)
  3554. ("lognotedone" org-log-done note)
  3555. ("nologdone" org-log-done nil)
  3556. ("lognoteclock-out" org-log-note-clock-out t)
  3557. ("nolognoteclock-out" org-log-note-clock-out nil)
  3558. ("logrepeat" org-log-repeat state)
  3559. ("lognoterepeat" org-log-repeat note)
  3560. ("logdrawer" org-log-into-drawer t)
  3561. ("nologdrawer" org-log-into-drawer nil)
  3562. ("logstatesreversed" org-log-states-order-reversed t)
  3563. ("nologstatesreversed" org-log-states-order-reversed nil)
  3564. ("nologrepeat" org-log-repeat nil)
  3565. ("logreschedule" org-log-reschedule time)
  3566. ("lognotereschedule" org-log-reschedule note)
  3567. ("nologreschedule" org-log-reschedule nil)
  3568. ("logredeadline" org-log-redeadline time)
  3569. ("lognoteredeadline" org-log-redeadline note)
  3570. ("nologredeadline" org-log-redeadline nil)
  3571. ("logrefile" org-log-refile time)
  3572. ("lognoterefile" org-log-refile note)
  3573. ("nologrefile" org-log-refile nil)
  3574. ("fninline" org-footnote-define-inline t)
  3575. ("nofninline" org-footnote-define-inline nil)
  3576. ("fnlocal" org-footnote-section nil)
  3577. ("fnauto" org-footnote-auto-label t)
  3578. ("fnprompt" org-footnote-auto-label nil)
  3579. ("fnconfirm" org-footnote-auto-label confirm)
  3580. ("fnplain" org-footnote-auto-label plain)
  3581. ("fnadjust" org-footnote-auto-adjust t)
  3582. ("nofnadjust" org-footnote-auto-adjust nil)
  3583. ("constcgs" constants-unit-system cgs)
  3584. ("constSI" constants-unit-system SI)
  3585. ("noptag" org-tag-persistent-alist nil)
  3586. ("hideblocks" org-hide-block-startup t)
  3587. ("nohideblocks" org-hide-block-startup nil)
  3588. ("beamer" org-startup-with-beamer-mode t)
  3589. ("entitiespretty" org-pretty-entities t)
  3590. ("entitiesplain" org-pretty-entities nil))
  3591. "Variable associated with STARTUP options for Org.
  3592. Each element is a list of three items: the startup options (as written
  3593. in the #+STARTUP line), the corresponding variable, and the value to set
  3594. this variable to if the option is found. An optional fourth element PUSH
  3595. means to push this value onto the list in the variable.")
  3596. (defcustom org-group-tags t
  3597. "When non-nil (the default), use group tags.
  3598. This can be turned on/off through `org-toggle-tags-groups'."
  3599. :group 'org-tags
  3600. :group 'org-startup
  3601. :type 'boolean)
  3602. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3603. (defun org-toggle-tags-groups ()
  3604. "Toggle support for group tags.
  3605. Support for group tags is controlled by the option
  3606. `org-group-tags', which is non-nil by default."
  3607. (interactive)
  3608. (setq org-group-tags (not org-group-tags))
  3609. (cond ((and (derived-mode-p 'org-agenda-mode)
  3610. org-group-tags)
  3611. (org-agenda-redo))
  3612. ((derived-mode-p 'org-mode)
  3613. (let ((org-inhibit-startup t)) (org-mode))))
  3614. (message "Groups tags support has been turned %s"
  3615. (if org-group-tags "on" "off")))
  3616. (defun org--tag-add-to-alist (alist1 alist2)
  3617. "Merge tags from ALIST1 into ALIST2.
  3618. Duplicates tags outside a group are removed. Keywords and order
  3619. are preserved.
  3620. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3621. See `org-tag-alist' for their structure."
  3622. (cond
  3623. ((null alist2) alist1)
  3624. ((null alist1) alist2)
  3625. (t
  3626. (let ((to-add nil)
  3627. (group-flag nil))
  3628. (dolist (tag-pair alist1)
  3629. (pcase tag-pair
  3630. (`(,(or :startgrouptag :startgroup))
  3631. (setq group-flag t)
  3632. (push tag-pair to-add))
  3633. (`(,(or :endgrouptag :endgroup))
  3634. (setq group-flag nil)
  3635. (push tag-pair to-add))
  3636. (`(,(or :grouptags :newline))
  3637. (push tag-pair to-add))
  3638. (`(,tag . ,_)
  3639. ;; Remove duplicates from ALIST1, unless they are in
  3640. ;; a group. Indeed, it makes sense to have a tag appear in
  3641. ;; multiple groups.
  3642. (when (or group-flag (not (assoc tag alist2)))
  3643. (push tag-pair to-add)))
  3644. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3645. ;; Preserve order of ALIST1.
  3646. (append (nreverse to-add) alist2)))))
  3647. (defun org-priority-to-value (s)
  3648. "Convert priority string S to its numeric value."
  3649. (or (save-match-data
  3650. (and (string-match "\\([0-9]+\\)" s)
  3651. (string-to-number (match-string 1 s))))
  3652. (string-to-char s)))
  3653. (defun org-set-regexps-and-options (&optional tags-only)
  3654. "Precompute regular expressions used in the current buffer.
  3655. When optional argument TAGS-ONLY is non-nil, only compute tags
  3656. related expressions."
  3657. (when (derived-mode-p 'org-mode)
  3658. (let ((alist (org-collect-keywords
  3659. (append '("FILETAGS" "TAGS")
  3660. (and (not tags-only)
  3661. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3662. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3663. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3664. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3665. ;; Startup options. Get this early since it does change
  3666. ;; behavior for other options (e.g., tags).
  3667. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3668. (cdr (assoc "STARTUP" alist)))))
  3669. (dolist (option startup)
  3670. (pcase (assoc-string option org-startup-options t)
  3671. (`(,_ ,variable ,value t)
  3672. (unless (listp (symbol-value variable))
  3673. (set (make-local-variable variable) nil))
  3674. (add-to-list variable value))
  3675. (`(,_ ,variable ,value . ,_)
  3676. (set (make-local-variable variable) value))
  3677. (_ nil))))
  3678. (setq-local org-file-tags
  3679. (mapcar #'org-add-prop-inherited
  3680. (cl-mapcan (lambda (value)
  3681. (cl-mapcan
  3682. (lambda (k) (org-split-string k ":"))
  3683. (split-string value)))
  3684. (cdr (assoc "FILETAGS" alist)))))
  3685. (setq org-current-tag-alist
  3686. (org--tag-add-to-alist
  3687. org-tag-persistent-alist
  3688. (let ((tags (cdr (assoc "TAGS" alist))))
  3689. (if tags
  3690. (org-tag-string-to-alist
  3691. (mapconcat #'identity tags "\n"))
  3692. org-tag-alist))))
  3693. (setq org-tag-groups-alist
  3694. (org-tag-alist-to-groups org-current-tag-alist))
  3695. (unless tags-only
  3696. ;; Properties.
  3697. (let ((properties nil))
  3698. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3699. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3700. (setq properties (org--update-property-plist
  3701. (match-string-no-properties 1 value)
  3702. (match-string-no-properties 2 value)
  3703. properties))))
  3704. (setq-local org-keyword-properties properties))
  3705. ;; Archive location.
  3706. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3707. (when archive (setq-local org-archive-location archive)))
  3708. ;; Category.
  3709. (let ((category (cdr (assoc "CATEGORY" alist))))
  3710. (when category
  3711. (setq-local org-category (intern category))
  3712. (setq-local org-keyword-properties
  3713. (org--update-property-plist
  3714. "CATEGORY" category org-keyword-properties))))
  3715. ;; Columns.
  3716. (let ((column (cdr (assoc "COLUMNS" alist))))
  3717. (when column (setq-local org-columns-default-format column)))
  3718. ;; Constants.
  3719. (let ((store nil))
  3720. (dolist (pair (cl-mapcan #'split-string
  3721. (cdr (assoc "CONSTANTS" alist))))
  3722. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3723. (let* ((name (match-string 1 pair))
  3724. (value (match-string 2 pair))
  3725. (old (assoc name store)))
  3726. (if old (setcdr old value)
  3727. (push (cons name value) store)))))
  3728. (setq org-table-formula-constants-local store))
  3729. ;; Link abbreviations.
  3730. (let ((links
  3731. (delq nil
  3732. (mapcar
  3733. (lambda (value)
  3734. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3735. (cons (match-string-no-properties 1 value)
  3736. (match-string-no-properties 2 value))))
  3737. (cdr (assoc "LINK" alist))))))
  3738. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3739. ;; Priorities.
  3740. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3741. (pcase (and value (split-string value))
  3742. (`(,high ,low ,default . ,_)
  3743. (setq-local org-priority-highest (org-priority-to-value high))
  3744. (setq-local org-priority-lowest (org-priority-to-value low))
  3745. (setq-local org-priority-default (org-priority-to-value default)))))
  3746. ;; Scripts.
  3747. (let ((value (cdr (assoc "OPTIONS" alist))))
  3748. (dolist (option value)
  3749. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3750. (setq-local org-use-sub-superscripts
  3751. (read (match-string 1 option))))))
  3752. ;; TODO keywords.
  3753. (setq-local org-todo-kwd-alist nil)
  3754. (setq-local org-todo-key-alist nil)
  3755. (setq-local org-todo-key-trigger nil)
  3756. (setq-local org-todo-keywords-1 nil)
  3757. (setq-local org-done-keywords nil)
  3758. (setq-local org-todo-heads nil)
  3759. (setq-local org-todo-sets nil)
  3760. (setq-local org-todo-log-states nil)
  3761. (let ((todo-sequences
  3762. (or (append (mapcar (lambda (value)
  3763. (cons 'type (split-string value)))
  3764. (cdr (assoc "TYP_TODO" alist)))
  3765. (mapcar (lambda (value)
  3766. (cons 'sequence (split-string value)))
  3767. (append (cdr (assoc "TODO" alist))
  3768. (cdr (assoc "SEQ_TODO" alist)))))
  3769. (let ((d (default-value 'org-todo-keywords)))
  3770. (if (not (stringp (car d))) d
  3771. ;; XXX: Backward compatibility code.
  3772. (list (cons org-todo-interpretation d)))))))
  3773. (dolist (sequence todo-sequences)
  3774. (let* ((sequence (or (run-hook-with-args-until-success
  3775. 'org-todo-setup-filter-hook sequence)
  3776. sequence))
  3777. (sequence-type (car sequence))
  3778. (keywords (cdr sequence))
  3779. (sep (member "|" keywords))
  3780. names alist)
  3781. (dolist (k (remove "|" keywords))
  3782. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3783. k)
  3784. (error "Invalid TODO keyword %s" k))
  3785. (let ((name (match-string 1 k))
  3786. (key (match-string 2 k))
  3787. (log (org-extract-log-state-settings k)))
  3788. (push name names)
  3789. (push (cons name (and key (string-to-char key))) alist)
  3790. (when log (push log org-todo-log-states))))
  3791. (let* ((names (nreverse names))
  3792. (done (if sep (org-remove-keyword-keys (cdr sep))
  3793. (last names)))
  3794. (head (car names))
  3795. (tail (list sequence-type head (car done) (org-last done))))
  3796. (add-to-list 'org-todo-heads head 'append)
  3797. (push names org-todo-sets)
  3798. (setq org-done-keywords (append org-done-keywords done nil))
  3799. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3800. (setq org-todo-key-alist
  3801. (append org-todo-key-alist
  3802. (and alist
  3803. (append '((:startgroup))
  3804. (nreverse alist)
  3805. '((:endgroup))))))
  3806. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3807. (setq org-todo-sets (nreverse org-todo-sets)
  3808. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3809. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3810. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3811. ;; Compute the regular expressions and other local variables.
  3812. ;; Using `org-outline-regexp-bol' would complicate them much,
  3813. ;; because of the fixed white space at the end of that string.
  3814. (unless org-done-keywords
  3815. (setq org-done-keywords
  3816. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3817. (setq org-not-done-keywords
  3818. (org-delete-all org-done-keywords
  3819. (copy-sequence org-todo-keywords-1))
  3820. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3821. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3822. org-not-done-heading-regexp
  3823. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3824. org-todo-line-regexp
  3825. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3826. org-complex-heading-regexp
  3827. (concat "^\\(\\*+\\)"
  3828. "\\(?: +" org-todo-regexp "\\)?"
  3829. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3830. "\\(?: +\\(.*?\\)\\)??"
  3831. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3832. "[ \t]*$")
  3833. org-complex-heading-regexp-format
  3834. (concat "^\\(\\*+\\)"
  3835. "\\(?: +" org-todo-regexp "\\)?"
  3836. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3837. "\\(?: +"
  3838. ;; Stats cookies can be stuck to body.
  3839. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3840. "\\(%s\\)"
  3841. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3842. "\\)"
  3843. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3844. "[ \t]*$")
  3845. org-todo-line-tags-regexp
  3846. (concat "^\\(\\*+\\)"
  3847. "\\(?: +" org-todo-regexp "\\)?"
  3848. "\\(?: +\\(.*?\\)\\)??"
  3849. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3850. "[ \t]*$"))
  3851. (org-compute-latex-and-related-regexp)))))
  3852. (defun org-collect-keywords (keywords &optional unique directory)
  3853. "Return values for KEYWORDS in current buffer, as an alist.
  3854. KEYWORDS is a list of strings. Return value is a list of
  3855. elements with the pattern:
  3856. (NAME . LIST-OF-VALUES)
  3857. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3858. is a list of non-empty values, as strings, in order of appearance
  3859. in the buffer.
  3860. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3861. value, empty or not, appearing in the buffer, as a string.
  3862. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3863. (VALUE . DIRECTORY)
  3864. where VALUE is the regular value, and DIRECTORY is the variable
  3865. `default-directory' for the buffer containing the keyword. This
  3866. is important for values containing relative file names, since the
  3867. function follows SETUPFILE keywords, and may change its working
  3868. directory."
  3869. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3870. (unique (mapcar #'upcase unique))
  3871. (alist (org--collect-keywords-1
  3872. keywords unique directory
  3873. (and buffer-file-name (list buffer-file-name))
  3874. nil)))
  3875. ;; Re-order results.
  3876. (dolist (entry alist)
  3877. (pcase entry
  3878. (`(,_ . ,(and value (pred consp)))
  3879. (setcdr entry (nreverse value)))))
  3880. (nreverse alist)))
  3881. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3882. (org-with-point-at 1
  3883. (let ((case-fold-search t)
  3884. (regexp (org-make-options-regexp keywords)))
  3885. (while (and keywords (re-search-forward regexp nil t))
  3886. (let ((element (org-element-at-point)))
  3887. (when (eq 'keyword (org-element-type element))
  3888. (let ((value (org-element-property :value element)))
  3889. (pcase (org-element-property :key element)
  3890. ("SETUPFILE"
  3891. (when (and (org-string-nw-p value)
  3892. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3893. (let* ((uri (org-strip-quotes value))
  3894. (uri-is-url (org-file-url-p uri))
  3895. (uri (if uri-is-url
  3896. uri
  3897. (expand-file-name uri))))
  3898. (unless (member uri files)
  3899. (with-temp-buffer
  3900. (unless uri-is-url
  3901. (setq default-directory (file-name-directory uri)))
  3902. (let ((contents (org-file-contents uri :noerror)))
  3903. (when contents
  3904. (insert contents)
  3905. ;; Fake Org mode: `org-element-at-point'
  3906. ;; doesn't need full set-up.
  3907. (let ((major-mode 'org-mode))
  3908. (setq alist
  3909. (org--collect-keywords-1
  3910. keywords unique directory
  3911. (cons uri files)
  3912. alist))))))))))
  3913. (keyword
  3914. (let ((entry (assoc keyword alist))
  3915. (final
  3916. (cond ((not (member keyword directory)) value)
  3917. (buffer-file-name
  3918. (cons value
  3919. (file-name-directory buffer-file-name)))
  3920. (t (cons value default-directory)))))
  3921. (cond ((member keyword unique)
  3922. (push (cons keyword final) alist)
  3923. (setq keywords (remove keyword keywords))
  3924. (setq regexp (org-make-options-regexp keywords)))
  3925. ((null entry) (push (list keyword final) alist))
  3926. (t (push final (cdr entry)))))))))))
  3927. alist)))
  3928. (defun org-tag-string-to-alist (s)
  3929. "Return tag alist associated to string S.
  3930. S is a value for TAGS keyword or produced with
  3931. `org-tag-alist-to-string'. Return value is an alist suitable for
  3932. `org-tag-alist' or `org-tag-persistent-alist'."
  3933. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3934. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3935. "\\(?:(\\(.\\))\\)?\\'"))
  3936. alist group-flag)
  3937. (dolist (tokens lines (cdr (nreverse alist)))
  3938. (push '(:newline) alist)
  3939. (while tokens
  3940. (let ((token (pop tokens)))
  3941. (pcase token
  3942. ("{"
  3943. (push '(:startgroup) alist)
  3944. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3945. ("}"
  3946. (push '(:endgroup) alist)
  3947. (setq group-flag nil))
  3948. ("["
  3949. (push '(:startgrouptag) alist)
  3950. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3951. ("]"
  3952. (push '(:endgrouptag) alist)
  3953. (setq group-flag nil))
  3954. (":"
  3955. (push '(:grouptags) alist))
  3956. ((guard (string-match tag-re token))
  3957. (let ((tag (match-string 1 token))
  3958. (key (and (match-beginning 2)
  3959. (string-to-char (match-string 2 token)))))
  3960. ;; Push all tags in groups, no matter if they already
  3961. ;; appear somewhere else in the list.
  3962. (when (or group-flag (not (assoc tag alist)))
  3963. (push (cons tag key) alist))))))))))
  3964. (defun org-tag-alist-to-string (alist &optional skip-key)
  3965. "Return tag string associated to ALIST.
  3966. ALIST is an alist, as defined in `org-tag-alist' or
  3967. `org-tag-persistent-alist', or produced with
  3968. `org-tag-string-to-alist'.
  3969. Return value is a string suitable as a value for \"TAGS\"
  3970. keyword.
  3971. When optional argument SKIP-KEY is non-nil, skip selection keys
  3972. next to tags."
  3973. (mapconcat (lambda (token)
  3974. (pcase token
  3975. (`(:startgroup) "{")
  3976. (`(:endgroup) "}")
  3977. (`(:startgrouptag) "[")
  3978. (`(:endgrouptag) "]")
  3979. (`(:grouptags) ":")
  3980. (`(:newline) "\\n")
  3981. ((and
  3982. (guard (not skip-key))
  3983. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  3984. (format "%s(%c)" tag key))
  3985. (`(,(and tag (pred stringp)) . ,_) tag)
  3986. (_ (user-error "Invalid tag token: %S" token))))
  3987. alist
  3988. " "))
  3989. (defun org-tag-alist-to-groups (alist)
  3990. "Return group alist from tag ALIST.
  3991. ALIST is an alist, as defined in `org-tag-alist' or
  3992. `org-tag-persistent-alist', or produced with
  3993. `org-tag-string-to-alist'. Return value is an alist following
  3994. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  3995. a string, summarizing TAGS, as a list of strings."
  3996. (let (groups group-status current-group)
  3997. (dolist (token alist (nreverse groups))
  3998. (pcase token
  3999. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4000. (`(,(or :endgroup :endgrouptag))
  4001. (when (eq group-status 'append)
  4002. (push (nreverse current-group) groups))
  4003. (setq group-status nil current-group nil))
  4004. (`(:grouptags) (setq group-status 'append))
  4005. ((and `(,tag . ,_) (guard group-status))
  4006. (if (eq group-status 'append) (push tag current-group)
  4007. (setq current-group (list tag))))
  4008. (_ nil)))))
  4009. (defvar org--file-cache (make-hash-table :test #'equal)
  4010. "Hash table to store contents of files referenced via a URL.
  4011. This is the cache of file URLs read using `org-file-contents'.")
  4012. (defun org-reset-file-cache ()
  4013. "Reset the cache of files downloaded by `org-file-contents'."
  4014. (clrhash org--file-cache))
  4015. (defun org-file-url-p (file)
  4016. "Non-nil if FILE is a URL."
  4017. (require 'ffap)
  4018. (string-match-p ffap-url-regexp file))
  4019. (defun org-file-contents (file &optional noerror nocache)
  4020. "Return the contents of FILE, as a string.
  4021. FILE can be a file name or URL.
  4022. If FILE is a URL, download the contents. If the URL contents are
  4023. already cached in the `org--file-cache' hash table, the download step
  4024. is skipped.
  4025. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4026. from file or URL, and return nil.
  4027. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4028. is available. This option applies only if FILE is a URL."
  4029. (let* ((is-url (org-file-url-p file))
  4030. (cache (and is-url
  4031. (not nocache)
  4032. (gethash file org--file-cache))))
  4033. (cond
  4034. (cache)
  4035. (is-url
  4036. (with-current-buffer (url-retrieve-synchronously file)
  4037. (goto-char (point-min))
  4038. ;; Move point to after the url-retrieve header.
  4039. (search-forward "\n\n" nil :move)
  4040. ;; Search for the success code only in the url-retrieve header.
  4041. (if (save-excursion
  4042. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4043. ;; Update the cache `org--file-cache' and return contents.
  4044. (puthash file
  4045. (buffer-substring-no-properties (point) (point-max))
  4046. org--file-cache)
  4047. (funcall (if noerror #'message #'user-error)
  4048. "Unable to fetch file from %S"
  4049. file)
  4050. nil)))
  4051. (t
  4052. (with-temp-buffer
  4053. (condition-case nil
  4054. (progn
  4055. (insert-file-contents file)
  4056. (buffer-string))
  4057. (file-error
  4058. (funcall (if noerror #'message #'user-error)
  4059. "Unable to read file %S"
  4060. file)
  4061. nil)))))))
  4062. (defun org-extract-log-state-settings (x)
  4063. "Extract the log state setting from a TODO keyword string.
  4064. This will extract info from a string like \"WAIT(w@/!)\"."
  4065. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4066. (let ((kw (match-string 1 x))
  4067. (log1 (and (match-end 3) (match-string 3 x)))
  4068. (log2 (and (match-end 4) (match-string 4 x))))
  4069. (and (or log1 log2)
  4070. (list kw
  4071. (and log1 (if (equal log1 "!") 'time 'note))
  4072. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4073. (defun org-remove-keyword-keys (list)
  4074. "Remove a pair of parenthesis at the end of each string in LIST."
  4075. (mapcar (lambda (x)
  4076. (if (string-match "(.*)$" x)
  4077. (substring x 0 (match-beginning 0))
  4078. x))
  4079. list))
  4080. (defun org-assign-fast-keys (alist)
  4081. "Assign fast keys to a keyword-key alist.
  4082. Respect keys that are already there."
  4083. (let (new e (alt ?0))
  4084. (while (setq e (pop alist))
  4085. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4086. (cdr e)) ;; Key already assigned.
  4087. (push e new)
  4088. (let ((clist (string-to-list (downcase (car e))))
  4089. (used (append new alist)))
  4090. (when (= (car clist) ?@)
  4091. (pop clist))
  4092. (while (and clist (rassoc (car clist) used))
  4093. (pop clist))
  4094. (unless clist
  4095. (while (rassoc alt used)
  4096. (cl-incf alt)))
  4097. (push (cons (car e) (or (car clist) alt)) new))))
  4098. (nreverse new)))
  4099. ;;; Some variables used in various places
  4100. (defvar org-window-configuration nil
  4101. "Used in various places to store a window configuration.")
  4102. (defvar org-selected-window nil
  4103. "Used in various places to store a window configuration.")
  4104. (defvar org-finish-function nil
  4105. "Function to be called when `C-c C-c' is used.
  4106. This is for getting out of special buffers like capture.")
  4107. (defvar org-last-state)
  4108. ;; Defined somewhere in this file, but used before definition.
  4109. (defvar org-entities) ;; defined in org-entities.el
  4110. (defvar org-struct-menu)
  4111. (defvar org-org-menu)
  4112. (defvar org-tbl-menu)
  4113. ;;;; Define the Org mode
  4114. (defun org-before-change-function (_beg _end)
  4115. "Every change indicates that a table might need an update."
  4116. (setq org-table-may-need-update t))
  4117. (defvar org-mode-map)
  4118. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4119. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4120. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4121. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4122. (defvar bidi-paragraph-direction)
  4123. (defvar buffer-face-mode-face)
  4124. (require 'outline)
  4125. ;; Other stuff we need.
  4126. (require 'time-date)
  4127. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4128. (require 'easymenu)
  4129. (require 'overlay)
  4130. (require 'org-entities)
  4131. (require 'org-faces)
  4132. (require 'org-list)
  4133. (require 'org-pcomplete)
  4134. (require 'org-src)
  4135. (require 'org-footnote)
  4136. (require 'org-macro)
  4137. ;; babel
  4138. (require 'ob)
  4139. ;;;###autoload
  4140. (define-derived-mode org-mode outline-mode "Org"
  4141. "Outline-based notes management and organizer, alias
  4142. \"Carsten's outline-mode for keeping track of everything.\"
  4143. Org mode develops organizational tasks around a NOTES file which
  4144. contains information about projects as plain text. Org mode is
  4145. implemented on top of Outline mode, which is ideal to keep the content
  4146. of large files well structured. It supports ToDo items, deadlines and
  4147. time stamps, which magically appear in the diary listing of the Emacs
  4148. calendar. Tables are easily created with a built-in table editor.
  4149. Plain text URL-like links connect to websites, emails (VM), Usenet
  4150. messages (Gnus), BBDB entries, and any files related to the project.
  4151. For printing and sharing of notes, an Org file (or a part of it)
  4152. can be exported as a structured ASCII or HTML file.
  4153. The following commands are available:
  4154. \\{org-mode-map}"
  4155. (org-load-modules-maybe)
  4156. (org-install-agenda-files-menu)
  4157. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4158. (add-to-invisibility-spec '(org-hide-block . t))
  4159. (setq-local outline-regexp org-outline-regexp)
  4160. (setq-local outline-level 'org-outline-level)
  4161. (setq bidi-paragraph-direction 'left-to-right)
  4162. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4163. (unless org-display-table
  4164. (setq org-display-table (make-display-table)))
  4165. (set-display-table-slot
  4166. org-display-table 4
  4167. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4168. org-ellipsis)))
  4169. (setq buffer-display-table org-display-table))
  4170. (org-set-regexps-and-options)
  4171. (org-set-font-lock-defaults)
  4172. (when (and org-tag-faces (not org-tags-special-faces-re))
  4173. ;; tag faces set outside customize.... force initialization.
  4174. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4175. ;; Calc embedded
  4176. (setq-local calc-embedded-open-mode "# ")
  4177. ;; Modify a few syntax entries
  4178. (modify-syntax-entry ?\" "\"")
  4179. (modify-syntax-entry ?\\ "_")
  4180. (modify-syntax-entry ?~ "_")
  4181. (modify-syntax-entry ?< "(>")
  4182. (modify-syntax-entry ?> ")<")
  4183. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4184. ;; Activate before-change-function
  4185. (setq-local org-table-may-need-update t)
  4186. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4187. ;; Check for running clock before killing a buffer
  4188. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4189. ;; Initialize macros templates.
  4190. (org-macro-initialize-templates)
  4191. ;; Initialize radio targets.
  4192. (org-update-radio-target-regexp)
  4193. ;; Indentation.
  4194. (setq-local indent-line-function 'org-indent-line)
  4195. (setq-local indent-region-function 'org-indent-region)
  4196. ;; Filling and auto-filling.
  4197. (org-setup-filling)
  4198. ;; Comments.
  4199. (org-setup-comments-handling)
  4200. ;; Initialize cache.
  4201. (org-element-cache-reset)
  4202. ;; Beginning/end of defun
  4203. (setq-local beginning-of-defun-function 'org-backward-element)
  4204. (setq-local end-of-defun-function
  4205. (lambda ()
  4206. (if (not (org-at-heading-p))
  4207. (org-forward-element)
  4208. (org-forward-element)
  4209. (forward-char -1))))
  4210. ;; Next error for sparse trees
  4211. (setq-local next-error-function 'org-occur-next-match)
  4212. ;; Make commit log messages from Org documents easier.
  4213. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4214. ;; Make sure dependence stuff works reliably, even for users who set it
  4215. ;; too late :-(
  4216. (if org-enforce-todo-dependencies
  4217. (add-hook 'org-blocker-hook
  4218. 'org-block-todo-from-children-or-siblings-or-parent)
  4219. (remove-hook 'org-blocker-hook
  4220. 'org-block-todo-from-children-or-siblings-or-parent))
  4221. (if org-enforce-todo-checkbox-dependencies
  4222. (add-hook 'org-blocker-hook
  4223. 'org-block-todo-from-checkboxes)
  4224. (remove-hook 'org-blocker-hook
  4225. 'org-block-todo-from-checkboxes))
  4226. ;; Align options lines
  4227. (setq-local
  4228. align-mode-rules-list
  4229. '((org-in-buffer-settings
  4230. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4231. (modes . '(org-mode)))))
  4232. ;; Setup the pcomplete hooks
  4233. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4234. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4235. (setq-local pcomplete-default-completion-function #'ignore)
  4236. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4237. (setq-local pcomplete-termination-string "")
  4238. (add-hook 'completion-at-point-functions
  4239. #'pcomplete-completions-at-point nil t)
  4240. (setq-local buffer-face-mode-face 'org-default)
  4241. ;; If empty file that did not turn on Org mode automatically, make
  4242. ;; it to.
  4243. (when (and org-insert-mode-line-in-empty-file
  4244. (called-interactively-p 'any)
  4245. (= (point-min) (point-max)))
  4246. (insert "# -*- mode: org -*-\n\n"))
  4247. (unless org-inhibit-startup
  4248. (org-unmodified
  4249. (when org-startup-with-beamer-mode (org-beamer-mode))
  4250. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4251. (org-table-map-tables
  4252. (cond ((and org-startup-align-all-tables
  4253. org-startup-shrink-all-tables)
  4254. (lambda () (org-table-align) (org-table-shrink)))
  4255. (org-startup-align-all-tables #'org-table-align)
  4256. (t #'org-table-shrink))
  4257. t))
  4258. (when org-startup-with-inline-images (org-display-inline-images))
  4259. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4260. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4261. (when org-startup-truncated (setq truncate-lines t))
  4262. (when org-startup-numerated (require 'org-num) (org-num-mode 1))
  4263. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4264. ;; Activate `org-table-header-line-mode'
  4265. (when org-table-header-line-p
  4266. (org-table-header-line-mode 1))
  4267. ;; Try to set `org-hide' face correctly.
  4268. (let ((foreground (org-find-invisible-foreground)))
  4269. (when foreground
  4270. (set-face-foreground 'org-hide foreground)))
  4271. ;; Set face extension as requested.
  4272. (org--set-faces-extend '(org-block-begin-line org-block-end-line)
  4273. org-fontify-whole-block-delimiter-line)
  4274. (org--set-faces-extend org-level-faces org-fontify-whole-heading-line))
  4275. ;; Update `customize-package-emacs-version-alist'
  4276. (add-to-list 'customize-package-emacs-version-alist
  4277. '(Org ("8.0" . "24.4")
  4278. ("8.1" . "24.4")
  4279. ("8.2" . "24.4")
  4280. ("8.2.7" . "24.4")
  4281. ("8.3" . "26.1")
  4282. ("9.0" . "26.1")
  4283. ("9.1" . "26.1")
  4284. ("9.2" . "27.1")
  4285. ("9.3" . "27.1")
  4286. ("9.4" . "27.2")))
  4287. (defvar org-mode-transpose-word-syntax-table
  4288. (let ((st (make-syntax-table text-mode-syntax-table)))
  4289. (dolist (c org-emphasis-alist st)
  4290. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4291. (when (fboundp 'abbrev-table-put)
  4292. (abbrev-table-put org-mode-abbrev-table
  4293. :parents (list text-mode-abbrev-table)))
  4294. (defun org-find-invisible-foreground ()
  4295. (let ((candidates (remove
  4296. "unspecified-bg"
  4297. (nconc
  4298. (list (face-background 'default)
  4299. (face-background 'org-default))
  4300. (mapcar
  4301. (lambda (alist)
  4302. (when (boundp alist)
  4303. (cdr (assq 'background-color (symbol-value alist)))))
  4304. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4305. (list (face-foreground 'org-hide))))))
  4306. (car (remove nil candidates))))
  4307. (defun org-current-time (&optional rounding-minutes past)
  4308. "Current time, possibly rounded to ROUNDING-MINUTES.
  4309. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4310. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4311. the rounding returns a past time."
  4312. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4313. (car org-time-stamp-rounding-minutes)))
  4314. (now (current-time)))
  4315. (if (< r 1)
  4316. now
  4317. (let* ((time (decode-time now))
  4318. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4319. (nthcdr 2 time))))
  4320. (if (or (not past) (org-time-less-p res now))
  4321. res
  4322. (org-time-subtract res (* r 60)))))))
  4323. (defun org-today ()
  4324. "Return today date, considering `org-extend-today-until'."
  4325. (time-to-days
  4326. (org-time-since (* 3600 org-extend-today-until))))
  4327. ;;;; Font-Lock stuff, including the activators
  4328. (defconst org-match-sexp-depth 3
  4329. "Number of stacked braces for sub/superscript matching.")
  4330. (defun org-create-multibrace-regexp (left right n)
  4331. "Create a regular expression which will match a balanced sexp.
  4332. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4333. as single character strings.
  4334. The regexp returned will match the entire expression including the
  4335. delimiters. It will also define a single group which contains the
  4336. match except for the outermost delimiters. The maximum depth of
  4337. stacked delimiters is N. Escaping delimiters is not possible."
  4338. (let* ((nothing (concat "[^" left right "]*?"))
  4339. (or "\\|")
  4340. (re nothing)
  4341. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4342. (while (> n 1)
  4343. (setq n (1- n)
  4344. re (concat re or next)
  4345. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4346. (concat left "\\(" re "\\)" right)))
  4347. (defconst org-match-substring-regexp
  4348. (concat
  4349. "\\(\\S-\\)\\([_^]\\)\\("
  4350. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4351. "\\|"
  4352. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4353. "\\|"
  4354. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4355. "The regular expression matching a sub- or superscript.")
  4356. (defconst org-match-substring-with-braces-regexp
  4357. (concat
  4358. "\\(\\S-\\)\\([_^]\\)"
  4359. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4360. "The regular expression matching a sub- or superscript, forcing braces.")
  4361. (defvar org-emph-face nil)
  4362. (defun org-do-emphasis-faces (limit)
  4363. "Run through the buffer and emphasize strings."
  4364. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4365. (car org-emphasis-regexp-components))))
  4366. (catch :exit
  4367. (while (re-search-forward quick-re limit t)
  4368. (let* ((marker (match-string 2))
  4369. (verbatim? (member marker '("~" "="))))
  4370. (when (save-excursion
  4371. (goto-char (match-beginning 0))
  4372. (and
  4373. ;; Do not match table hlines.
  4374. (not (and (equal marker "+")
  4375. (org-match-line
  4376. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4377. ;; Do not match headline stars. Do not consider
  4378. ;; stars of a headline as closing marker for bold
  4379. ;; markup either.
  4380. (not (and (equal marker "*")
  4381. (save-excursion
  4382. (forward-char)
  4383. (skip-chars-backward "*")
  4384. (looking-at-p org-outline-regexp-bol))))
  4385. ;; Match full emphasis markup regexp.
  4386. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4387. ;; Do not span over paragraph boundaries.
  4388. (not (string-match-p org-element-paragraph-separate
  4389. (match-string 2)))
  4390. ;; Do not span over cells in table rows.
  4391. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4392. (string-match-p "|" (match-string 4))))))
  4393. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4394. (m (if org-hide-emphasis-markers 4 2)))
  4395. (font-lock-prepend-text-property
  4396. (match-beginning m) (match-end m) 'face face)
  4397. (when verbatim?
  4398. (org-remove-flyspell-overlays-in
  4399. (match-beginning 0) (match-end 0))
  4400. (remove-text-properties (match-beginning 2) (match-end 2)
  4401. '(display t invisible t intangible t)))
  4402. (add-text-properties (match-beginning 2) (match-end 2)
  4403. '(font-lock-multiline t org-emphasis t))
  4404. (when (and org-hide-emphasis-markers
  4405. (not (org-at-comment-p)))
  4406. (add-text-properties (match-end 4) (match-beginning 5)
  4407. '(invisible org-link))
  4408. (add-text-properties (match-beginning 3) (match-end 3)
  4409. '(invisible org-link)))
  4410. (throw :exit t))))))))
  4411. (defun org-emphasize (&optional char)
  4412. "Insert or change an emphasis, i.e. a font like bold or italic.
  4413. If there is an active region, change that region to a new emphasis.
  4414. If there is no region, just insert the marker characters and position
  4415. the cursor between them.
  4416. CHAR should be the marker character. If it is a space, it means to
  4417. remove the emphasis of the selected region.
  4418. If CHAR is not given (for example in an interactive call) it will be
  4419. prompted for."
  4420. (interactive)
  4421. (let ((erc org-emphasis-regexp-components)
  4422. (string "") beg end move s)
  4423. (if (org-region-active-p)
  4424. (setq beg (region-beginning)
  4425. end (region-end)
  4426. string (buffer-substring beg end))
  4427. (setq move t))
  4428. (unless char
  4429. (message "Emphasis marker or tag: [%s]"
  4430. (mapconcat #'car org-emphasis-alist ""))
  4431. (setq char (read-char-exclusive)))
  4432. (if (equal char ?\s)
  4433. (setq s ""
  4434. move nil)
  4435. (unless (assoc (char-to-string char) org-emphasis-alist)
  4436. (user-error "No such emphasis marker: \"%c\"" char))
  4437. (setq s (char-to-string char)))
  4438. (while (and (> (length string) 1)
  4439. (equal (substring string 0 1) (substring string -1))
  4440. (assoc (substring string 0 1) org-emphasis-alist))
  4441. (setq string (substring string 1 -1)))
  4442. (setq string (concat s string s))
  4443. (when beg (delete-region beg end))
  4444. (unless (or (bolp)
  4445. (string-match (concat "[" (nth 0 erc) "\n]")
  4446. (char-to-string (char-before (point)))))
  4447. (insert " "))
  4448. (unless (or (eobp)
  4449. (string-match (concat "[" (nth 1 erc) "\n]")
  4450. (char-to-string (char-after (point)))))
  4451. (insert " ") (backward-char 1))
  4452. (insert string)
  4453. (and move (backward-char 1))))
  4454. (defconst org-nonsticky-props
  4455. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4456. (defsubst org-rear-nonsticky-at (pos)
  4457. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4458. (defun org-activate-links (limit)
  4459. "Add link properties to links.
  4460. This includes angle, plain, and bracket links."
  4461. (catch :exit
  4462. (while (re-search-forward org-link-any-re limit t)
  4463. (let* ((start (match-beginning 0))
  4464. (end (match-end 0))
  4465. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4466. (visible-end (or (match-end 3) (match-end 2)))
  4467. (style (cond ((eq ?< (char-after start)) 'angle)
  4468. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4469. (t 'plain))))
  4470. (when (and (memq style org-highlight-links)
  4471. ;; Do not span over paragraph boundaries.
  4472. (not (string-match-p org-element-paragraph-separate
  4473. (match-string 0)))
  4474. ;; Do not confuse plain links with tags.
  4475. (not (and (eq style 'plain)
  4476. (let ((face (get-text-property
  4477. (max (1- start) (point-min)) 'face)))
  4478. (if (consp face) (memq 'org-tag face)
  4479. (eq 'org-tag face))))))
  4480. (let* ((link-object (save-excursion
  4481. (goto-char start)
  4482. (save-match-data (org-element-link-parser))))
  4483. (link (org-element-property :raw-link link-object))
  4484. (type (org-element-property :type link-object))
  4485. (path (org-element-property :path link-object))
  4486. (properties ;for link's visible part
  4487. (list
  4488. 'face (pcase (org-link-get-parameter type :face)
  4489. ((and (pred functionp) face) (funcall face path))
  4490. ((and (pred facep) face) face)
  4491. ((and (pred consp) face) face) ;anonymous
  4492. (_ 'org-link))
  4493. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4494. 'highlight)
  4495. 'keymap (or (org-link-get-parameter type :keymap)
  4496. org-mouse-map)
  4497. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4498. ((and (pred stringp) echo) echo)
  4499. ((and (pred functionp) echo) echo)
  4500. (_ (concat "LINK: " link)))
  4501. 'htmlize-link (pcase (org-link-get-parameter type
  4502. :htmlize-link)
  4503. ((and (pred functionp) f) (funcall f))
  4504. (_ `(:uri ,link)))
  4505. 'font-lock-multiline t)))
  4506. (org-remove-flyspell-overlays-in start end)
  4507. (org-rear-nonsticky-at end)
  4508. (if (not (eq 'bracket style))
  4509. (add-text-properties start end properties)
  4510. ;; Handle invisible parts in bracket links.
  4511. (remove-text-properties start end '(invisible nil))
  4512. (let ((hidden
  4513. (append `(invisible
  4514. ,(or (org-link-get-parameter type :display)
  4515. 'org-link))
  4516. properties)))
  4517. (add-text-properties start visible-start hidden)
  4518. (add-text-properties visible-start visible-end properties)
  4519. (add-text-properties visible-end end hidden)
  4520. (org-rear-nonsticky-at visible-start)
  4521. (org-rear-nonsticky-at visible-end)))
  4522. (let ((f (org-link-get-parameter type :activate-func)))
  4523. (when (functionp f)
  4524. (funcall f start end path (eq style 'bracket))))
  4525. (throw :exit t))))) ;signal success
  4526. nil))
  4527. (defun org-activate-code (limit)
  4528. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4529. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4530. (remove-text-properties (match-beginning 0) (match-end 0)
  4531. '(display t invisible t intangible t))
  4532. t))
  4533. (defcustom org-src-fontify-natively t
  4534. "When non-nil, fontify code in code blocks.
  4535. See also the `org-block' face."
  4536. :type 'boolean
  4537. :version "26.1"
  4538. :package-version '(Org . "8.3")
  4539. :group 'org-appearance
  4540. :group 'org-babel)
  4541. (defcustom org-allow-promoting-top-level-subtree nil
  4542. "When non-nil, allow promoting a top level subtree.
  4543. The leading star of the top level headline will be replaced
  4544. by a #."
  4545. :type 'boolean
  4546. :version "24.1"
  4547. :group 'org-appearance)
  4548. (defun org-fontify-meta-lines-and-blocks (limit)
  4549. (condition-case nil
  4550. (org-fontify-meta-lines-and-blocks-1 limit)
  4551. (error (message "Org mode fontification error in %S at %d"
  4552. (current-buffer)
  4553. (line-number-at-pos)))))
  4554. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4555. "Fontify #+ lines and blocks."
  4556. (let ((case-fold-search t))
  4557. (when (re-search-forward
  4558. (rx bol (group (zero-or-more (any " \t")) "#"
  4559. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4560. (any " \t")
  4561. eol))
  4562. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4563. (zero-or-more (any " \t"))
  4564. (group (group (zero-or-more (not (any " \t\n"))))
  4565. (zero-or-more (any " \t"))
  4566. (group (zero-or-more any)))))
  4567. limit t)
  4568. (let ((beg (match-beginning 0))
  4569. (end-of-beginline (match-end 0))
  4570. ;; Including \n at end of #+begin line will include \n
  4571. ;; after the end of block content.
  4572. (block-start (match-end 0))
  4573. (block-end nil)
  4574. (lang (match-string 7)) ; The language, if it is a source block.
  4575. (bol-after-beginline (line-beginning-position 2))
  4576. (dc1 (downcase (match-string 2)))
  4577. (dc3 (downcase (match-string 3)))
  4578. (whole-blockline org-fontify-whole-block-delimiter-line)
  4579. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4580. (cond
  4581. ((and (match-end 4) (equal dc3 "+begin"))
  4582. ;; Truly a block
  4583. (setq block-type (downcase (match-string 5))
  4584. ;; Src, example, export, maybe more.
  4585. quoting (member block-type org-protecting-blocks))
  4586. (when (re-search-forward
  4587. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4588. (seq (zero-or-more (any " \t"))
  4589. "#+end"
  4590. ,(match-string 4)
  4591. word-end
  4592. (zero-or-more any)))))
  4593. ;; We look further than LIMIT on purpose.
  4594. nil t)
  4595. ;; We do have a matching #+end line.
  4596. (setq beg-of-endline (match-beginning 0)
  4597. end-of-endline (match-end 0)
  4598. nl-before-endline (1- (match-beginning 0)))
  4599. (setq block-end (match-beginning 0)) ; Include the final newline.
  4600. (when quoting
  4601. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4602. (remove-text-properties beg end-of-endline
  4603. '(display t invisible t intangible t)))
  4604. (add-text-properties
  4605. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4606. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4607. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4608. (cond
  4609. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4610. (org-src-font-lock-fontify-block lang block-start block-end)
  4611. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4612. (quoting
  4613. (add-text-properties
  4614. bol-after-beginline beg-of-endline
  4615. (list 'face
  4616. (list :inherit
  4617. (let ((face-name
  4618. (intern (format "org-block-%s" lang))))
  4619. (append (and (facep face-name) (list face-name))
  4620. '(org-block)))))))
  4621. ((not org-fontify-quote-and-verse-blocks))
  4622. ((string= block-type "quote")
  4623. (add-face-text-property
  4624. bol-after-beginline beg-of-endline 'org-quote t))
  4625. ((string= block-type "verse")
  4626. (add-face-text-property
  4627. bol-after-beginline beg-of-endline 'org-verse t)))
  4628. ;; Fontify the #+begin and #+end lines of the blocks
  4629. (add-text-properties
  4630. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4631. '(face org-block-begin-line))
  4632. (unless (eq (char-after beg-of-endline) ?*)
  4633. (add-text-properties
  4634. beg-of-endline
  4635. (if whole-blockline
  4636. (let ((beg-of-next-line (1+ end-of-endline)))
  4637. (min (point-max) beg-of-next-line))
  4638. (min (point-max) end-of-endline))
  4639. '(face org-block-end-line)))
  4640. t))
  4641. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  4642. (org-remove-flyspell-overlays-in
  4643. (match-beginning 0)
  4644. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4645. (add-text-properties
  4646. beg (match-end 3)
  4647. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4648. '(font-lock-fontified t invisible t)
  4649. '(font-lock-fontified t face org-document-info-keyword)))
  4650. (add-text-properties
  4651. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4652. (if (string-equal dc1 "+title:")
  4653. '(font-lock-fontified t face org-document-title)
  4654. '(font-lock-fontified t face org-document-info))))
  4655. ((string-prefix-p "+caption" dc1)
  4656. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4657. (remove-text-properties (match-beginning 0) (match-end 0)
  4658. '(display t invisible t intangible t))
  4659. ;; Handle short captions
  4660. (save-excursion
  4661. (beginning-of-line)
  4662. (looking-at (rx (group (zero-or-more (any " \t"))
  4663. "#+caption"
  4664. (optional "[" (zero-or-more any) "]")
  4665. ":")
  4666. (zero-or-more (any " \t")))))
  4667. (add-text-properties (line-beginning-position) (match-end 1)
  4668. '(font-lock-fontified t face org-meta-line))
  4669. (add-text-properties (match-end 0) (line-end-position)
  4670. '(font-lock-fontified t face org-block))
  4671. t)
  4672. ((member dc3 '(" " ""))
  4673. ;; Just a comment, the plus was not there
  4674. (org-remove-flyspell-overlays-in beg (match-end 0))
  4675. (add-text-properties
  4676. beg (match-end 0)
  4677. '(font-lock-fontified t face font-lock-comment-face)))
  4678. (t ;; Just any other in-buffer setting, but not indented
  4679. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4680. (remove-text-properties (match-beginning 0) (match-end 0)
  4681. '(display t invisible t intangible t))
  4682. (add-text-properties beg (match-end 0)
  4683. '(font-lock-fontified t face org-meta-line))
  4684. t))))))
  4685. (defun org-fontify-drawers (limit)
  4686. "Fontify drawers."
  4687. (when (re-search-forward org-drawer-regexp limit t)
  4688. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4689. '(font-lock-fontified t face org-drawer))
  4690. (org-remove-flyspell-overlays-in
  4691. (line-beginning-position) (line-beginning-position 2))
  4692. t))
  4693. (defun org-fontify-macros (limit)
  4694. "Fontify macros."
  4695. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4696. (let ((begin (match-beginning 0))
  4697. (opening-end (match-beginning 1)))
  4698. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4699. (match-string 1))
  4700. (let ((end (match-end 1))
  4701. (closing-start (match-beginning 1)))
  4702. (add-text-properties
  4703. begin end
  4704. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4705. (org-remove-flyspell-overlays-in begin end)
  4706. (when org-hide-macro-markers
  4707. (add-text-properties begin opening-end '(invisible t))
  4708. (add-text-properties closing-start end '(invisible t)))
  4709. t)))))
  4710. (defun org-fontify-extend-region (beg end _old-len)
  4711. (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4712. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4713. (extend (lambda (r1 r2 dir)
  4714. (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
  4715. (replace-regexp-in-string "[][]" r2
  4716. (match-string-no-properties 0)))))
  4717. (re-search-forward (regexp-quote re) nil t dir)))))
  4718. (save-match-data
  4719. (save-excursion
  4720. (goto-char beg)
  4721. (back-to-indentation)
  4722. (cond ((looking-at end-re)
  4723. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4724. ((looking-at begin-re)
  4725. (cons beg (or (funcall extend "end" "]" 1) end)))
  4726. (t (cons beg end)))))))
  4727. (defun org-activate-footnote-links (limit)
  4728. "Add text properties for footnotes."
  4729. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4730. (when fn
  4731. (let* ((beg (nth 1 fn))
  4732. (end (nth 2 fn))
  4733. (label (car fn))
  4734. (referencep (/= (line-beginning-position) beg)))
  4735. (when (and referencep (nth 3 fn))
  4736. (save-excursion
  4737. (goto-char beg)
  4738. (search-forward (or label "fn:"))
  4739. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4740. (add-text-properties beg end
  4741. (list 'mouse-face 'highlight
  4742. 'keymap org-mouse-map
  4743. 'help-echo
  4744. (if referencep "Footnote reference"
  4745. "Footnote definition")
  4746. 'font-lock-fontified t
  4747. 'font-lock-multiline t
  4748. 'face 'org-footnote))))))
  4749. (defun org-activate-dates (limit)
  4750. "Add text properties for dates."
  4751. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4752. (not (equal (char-before (match-beginning 0)) 91)))
  4753. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4754. (add-text-properties (match-beginning 0) (match-end 0)
  4755. (list 'mouse-face 'highlight
  4756. 'keymap org-mouse-map))
  4757. (org-rear-nonsticky-at (match-end 0))
  4758. (when org-display-custom-times
  4759. ;; If it's a date range, activate custom time for second date.
  4760. (when (match-end 3)
  4761. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4762. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4763. t))
  4764. (defun org-activate-target-links (limit)
  4765. "Add text properties for target matches."
  4766. (when org-target-link-regexp
  4767. (let ((case-fold-search t))
  4768. ;; `org-target-link-regexp' matches one character before the
  4769. ;; actual target.
  4770. (unless (bolp) (forward-char -1))
  4771. (when (re-search-forward org-target-link-regexp limit t)
  4772. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4773. (add-text-properties (match-beginning 1) (match-end 1)
  4774. (list 'mouse-face 'highlight
  4775. 'keymap org-mouse-map
  4776. 'help-echo "Radio target link"
  4777. 'org-linked-text t))
  4778. (org-rear-nonsticky-at (match-end 1))
  4779. t))))
  4780. (defvar org-latex-and-related-regexp nil
  4781. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4782. (defun org-compute-latex-and-related-regexp ()
  4783. "Compute regular expression for LaTeX, entities and sub/superscript.
  4784. Result depends on variable `org-highlight-latex-and-related'."
  4785. (let ((re-sub
  4786. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4787. ((eq org-use-sub-superscripts '{})
  4788. (list org-match-substring-with-braces-regexp))
  4789. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4790. (re-latex
  4791. (when (or (memq 'latex org-highlight-latex-and-related)
  4792. (memq 'native org-highlight-latex-and-related))
  4793. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4794. (delq nil
  4795. (mapcar (lambda (x)
  4796. (and (member (car x) matchers) (nth 1 x)))
  4797. org-latex-regexps)))))
  4798. (re-entities
  4799. (when (memq 'entities org-highlight-latex-and-related)
  4800. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4801. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4802. (setq-local org-latex-and-related-regexp
  4803. (mapconcat #'identity
  4804. (append re-latex re-entities re-sub)
  4805. "\\|"))))
  4806. (defun org-do-latex-and-related (limit)
  4807. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4808. Stop at first highlighted object, if any. Return t if some
  4809. highlighting was done, nil otherwise."
  4810. (when (org-string-nw-p org-latex-and-related-regexp)
  4811. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4812. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4813. (catch 'found
  4814. (while (and (< (point) limit)
  4815. (re-search-forward org-latex-and-related-regexp nil t))
  4816. (cond
  4817. ((cl-some (lambda (f)
  4818. (memq f '(org-code org-verbatim underline
  4819. org-special-keyword)))
  4820. (save-excursion
  4821. (goto-char (1+ (match-beginning 0)))
  4822. (face-at-point nil t))))
  4823. ;; Try to limit false positives. In this case, ignore
  4824. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4825. ;; contain an empty line.
  4826. ((save-excursion
  4827. (goto-char (match-beginning 0))
  4828. (and (looking-at-p latex-prefix-re)
  4829. (save-match-data
  4830. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4831. (t
  4832. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4833. '(?_ ?^))
  4834. 1
  4835. 0))
  4836. (start (+ offset (match-beginning 0)))
  4837. (end (match-end 0)))
  4838. (if (memq 'native org-highlight-latex-and-related)
  4839. (org-src-font-lock-fontify-block "latex" start end)
  4840. (font-lock-prepend-text-property start end
  4841. 'face 'org-latex-and-related))
  4842. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4843. '(font-lock-multiline t))
  4844. (throw 'found t)))))
  4845. nil))))
  4846. (defun org-restart-font-lock ()
  4847. "Restart `font-lock-mode', to force refontification."
  4848. (when (and (boundp 'font-lock-mode) font-lock-mode)
  4849. (font-lock-mode -1)
  4850. (font-lock-mode 1)))
  4851. (defun org-activate-tags (limit)
  4852. (when (re-search-forward org-tag-line-re limit t)
  4853. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4854. (add-text-properties (match-beginning 1) (match-end 1)
  4855. (list 'mouse-face 'highlight
  4856. 'keymap org-mouse-map))
  4857. (org-rear-nonsticky-at (match-end 1))
  4858. t))
  4859. (defun org-outline-level ()
  4860. "Compute the outline level of the heading at point.
  4861. If this is called at a normal headline, the level is the number
  4862. of stars. Use `org-reduced-level' to remove the effect of
  4863. `org-odd-levels'. Unlike to `org-current-level', this function
  4864. takes into consideration inlinetasks."
  4865. (org-with-wide-buffer
  4866. (end-of-line)
  4867. (if (re-search-backward org-outline-regexp-bol nil t)
  4868. (1- (- (match-end 0) (match-beginning 0)))
  4869. 0)))
  4870. (defvar org-font-lock-keywords nil)
  4871. (defsubst org-re-property (property &optional literal allow-null value)
  4872. "Return a regexp matching a PROPERTY line.
  4873. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4874. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4875. non-nil, match properties even without a value.
  4876. Match group 3 is set to the value when it exists. If there is no
  4877. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4878. With optional argument VALUE, match only property lines with
  4879. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4880. unless LITERAL is non-nil."
  4881. (concat
  4882. "^\\(?4:[ \t]*\\)"
  4883. (format "\\(?1::\\(?2:%s\\):\\)"
  4884. (if literal property (regexp-quote property)))
  4885. (cond (value
  4886. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4887. (if literal value (regexp-quote value))))
  4888. (allow-null
  4889. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4890. (t
  4891. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4892. (defconst org-property-re
  4893. (org-re-property "\\S-+" 'literal t)
  4894. "Regular expression matching a property line.
  4895. There are four matching groups:
  4896. 1: :PROPKEY: including the leading and trailing colon,
  4897. 2: PROPKEY without the leading and trailing colon,
  4898. 3: PROPVAL without leading or trailing spaces,
  4899. 4: the indentation of the current line,
  4900. 5: trailing whitespace.")
  4901. (defvar org-font-lock-hook nil
  4902. "Functions to be called for special font lock stuff.")
  4903. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4904. (defvar org-font-lock-set-keywords-hook nil
  4905. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4906. This is called after `org-font-lock-extra-keywords' is defined, but before
  4907. it is installed to be used by font lock. This can be useful if something
  4908. needs to be inserted at a specific position in the font-lock sequence.")
  4909. (defun org-font-lock-hook (limit)
  4910. "Run `org-font-lock-hook' within LIMIT."
  4911. (run-hook-with-args 'org-font-lock-hook limit))
  4912. (defun org-set-font-lock-defaults ()
  4913. "Set font lock defaults for the current buffer."
  4914. (let* ((em org-fontify-emphasized-text)
  4915. (lk org-highlight-links)
  4916. (org-font-lock-extra-keywords
  4917. (list
  4918. ;; Call the hook
  4919. '(org-font-lock-hook)
  4920. ;; Headlines
  4921. `(,(if org-fontify-whole-heading-line
  4922. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4923. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4924. (1 (org-get-level-face 1))
  4925. (2 (org-get-level-face 2))
  4926. (3 (org-get-level-face 3)))
  4927. ;; Table lines
  4928. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4929. (1 'org-table t))
  4930. ;; Table internals
  4931. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4932. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4933. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4934. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4935. ;; Properties
  4936. (list org-property-re
  4937. '(1 'org-special-keyword t)
  4938. '(3 'org-property-value t))
  4939. ;; Drawers
  4940. '(org-fontify-drawers)
  4941. ;; Link related fontification.
  4942. '(org-activate-links)
  4943. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  4944. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  4945. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  4946. (when (memq 'footnote lk) '(org-activate-footnote-links))
  4947. ;; Targets.
  4948. (list org-radio-target-regexp '(0 'org-target t))
  4949. (list org-target-regexp '(0 'org-target t))
  4950. ;; Diary sexps.
  4951. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  4952. ;; Macro
  4953. '(org-fontify-macros)
  4954. ;; TODO keyword
  4955. (list (format org-heading-keyword-regexp-format
  4956. org-todo-regexp)
  4957. '(2 (org-get-todo-face 2) t))
  4958. ;; TODO
  4959. (when org-fontify-todo-headline
  4960. (list (format org-heading-keyword-regexp-format
  4961. (concat
  4962. "\\(?:"
  4963. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  4964. "\\)"))
  4965. '(2 'org-headline-todo t)))
  4966. ;; DONE
  4967. (when org-fontify-done-headline
  4968. (list (format org-heading-keyword-regexp-format
  4969. (concat
  4970. "\\(?:"
  4971. (mapconcat 'regexp-quote org-done-keywords "\\|")
  4972. "\\)"))
  4973. '(2 'org-headline-done t)))
  4974. ;; Priorities
  4975. '(org-font-lock-add-priority-faces)
  4976. ;; Tags
  4977. '(org-font-lock-add-tag-faces)
  4978. ;; Tags groups
  4979. (when (and org-group-tags org-tag-groups-alist)
  4980. (list (concat org-outline-regexp-bol ".+\\(:"
  4981. (regexp-opt (mapcar 'car org-tag-groups-alist))
  4982. ":\\).*$")
  4983. '(1 'org-tag-group prepend)))
  4984. ;; Special keywords
  4985. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  4986. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  4987. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  4988. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  4989. ;; Emphasis
  4990. (when em '(org-do-emphasis-faces))
  4991. ;; Checkboxes
  4992. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  4993. 1 'org-checkbox prepend)
  4994. (when (cdr (assq 'checkbox org-list-automatic-rules))
  4995. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  4996. (0 (org-get-checkbox-statistics-face) t)))
  4997. ;; Description list items
  4998. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  4999. 1 'org-list-dt prepend)
  5000. ;; ARCHIVEd headings
  5001. (list (concat
  5002. org-outline-regexp-bol
  5003. "\\(.*:" org-archive-tag ":.*\\)")
  5004. '(1 'org-archived prepend))
  5005. ;; Specials
  5006. '(org-do-latex-and-related)
  5007. '(org-fontify-entities)
  5008. '(org-raise-scripts)
  5009. ;; Code
  5010. '(org-activate-code (1 'org-code t))
  5011. ;; COMMENT
  5012. (list (format
  5013. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5014. org-todo-regexp
  5015. org-comment-string)
  5016. '(9 'org-special-keyword t))
  5017. ;; Blocks and meta lines
  5018. '(org-fontify-meta-lines-and-blocks))))
  5019. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5020. (run-hooks 'org-font-lock-set-keywords-hook)
  5021. ;; Now set the full font-lock-keywords
  5022. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5023. (setq-local font-lock-defaults
  5024. '(org-font-lock-keywords t nil nil backward-paragraph))
  5025. (setq-local font-lock-extend-after-change-region-function
  5026. #'org-fontify-extend-region)
  5027. (kill-local-variable 'font-lock-keywords)
  5028. nil))
  5029. (defun org-toggle-pretty-entities ()
  5030. "Toggle the composition display of entities as UTF8 characters."
  5031. (interactive)
  5032. (setq-local org-pretty-entities (not org-pretty-entities))
  5033. (org-restart-font-lock)
  5034. (if org-pretty-entities
  5035. (message "Entities are now displayed as UTF8 characters")
  5036. (save-restriction
  5037. (widen)
  5038. (decompose-region (point-min) (point-max))
  5039. (message "Entities are now displayed as plain text"))))
  5040. (defvar-local org-custom-properties-overlays nil
  5041. "List of overlays used for custom properties.")
  5042. (defun org-toggle-custom-properties-visibility ()
  5043. "Display or hide properties in `org-custom-properties'."
  5044. (interactive)
  5045. (if org-custom-properties-overlays
  5046. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5047. (setq org-custom-properties-overlays nil))
  5048. (when org-custom-properties
  5049. (org-with-wide-buffer
  5050. (goto-char (point-min))
  5051. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5052. (while (re-search-forward regexp nil t)
  5053. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5054. (when (and end (< (point) end))
  5055. ;; Hide first custom property in current drawer.
  5056. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5057. (overlay-put o 'invisible t)
  5058. (overlay-put o 'org-custom-property t)
  5059. (push o org-custom-properties-overlays))
  5060. ;; Hide additional custom properties in the same drawer.
  5061. (while (re-search-forward regexp end t)
  5062. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5063. (overlay-put o 'invisible t)
  5064. (overlay-put o 'org-custom-property t)
  5065. (push o org-custom-properties-overlays)))))
  5066. ;; Each entry is limited to a single property drawer.
  5067. (outline-next-heading)))))))
  5068. (defun org-fontify-entities (limit)
  5069. "Find an entity to fontify."
  5070. (let (ee)
  5071. (when org-pretty-entities
  5072. (catch 'match
  5073. ;; "\_ "-family is left out on purpose. Only the first one,
  5074. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5075. ;; confusing when adding a second white space character.
  5076. (while (re-search-forward
  5077. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5078. limit t)
  5079. (when (and (not (org-at-comment-p))
  5080. (setq ee (org-entity-get (match-string 1)))
  5081. (= (length (nth 6 ee)) 1))
  5082. (let* ((end (if (equal (match-string 2) "{}")
  5083. (match-end 2)
  5084. (match-end 1))))
  5085. (add-text-properties
  5086. (match-beginning 0) end
  5087. (list 'font-lock-fontified t))
  5088. (compose-region (match-beginning 0) end
  5089. (nth 6 ee) nil)
  5090. (backward-char 1)
  5091. (throw 'match t))))
  5092. nil))))
  5093. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5094. "Fontify string S like in Org mode."
  5095. (with-temp-buffer
  5096. (insert s)
  5097. (let ((org-odd-levels-only odd-levels))
  5098. (org-mode)
  5099. (org-font-lock-ensure)
  5100. (buffer-string))))
  5101. (defun org-get-level-face (n)
  5102. "Get the right face for match N in font-lock matching of headlines."
  5103. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5104. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5105. (org-f (if org-cycle-level-faces
  5106. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5107. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5108. (cond
  5109. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5110. ((eq n 2) org-f)
  5111. (t (unless org-level-color-stars-only org-f)))))
  5112. (defun org-face-from-face-or-color (context inherit face-or-color)
  5113. "Create a face list that inherits INHERIT, but sets the foreground color.
  5114. When FACE-OR-COLOR is not a string, just return it."
  5115. (if (stringp face-or-color)
  5116. (list :inherit inherit
  5117. (cdr (assoc context org-faces-easy-properties))
  5118. face-or-color)
  5119. face-or-color))
  5120. (defun org-get-todo-face (kwd)
  5121. "Get the right face for a TODO keyword KWD.
  5122. If KWD is a number, get the corresponding match group."
  5123. (when (numberp kwd) (setq kwd (match-string kwd)))
  5124. (or (org-face-from-face-or-color
  5125. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5126. (and (member kwd org-done-keywords) 'org-done)
  5127. 'org-todo))
  5128. (defun org-get-priority-face (priority)
  5129. "Get the right face for PRIORITY.
  5130. PRIORITY is a character."
  5131. (or (org-face-from-face-or-color
  5132. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5133. 'org-priority))
  5134. (defun org-get-tag-face (tag)
  5135. "Get the right face for TAG.
  5136. If TAG is a number, get the corresponding match group."
  5137. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5138. (or (org-face-from-face-or-color
  5139. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5140. 'org-tag)))
  5141. (defvar org-priority-regexp) ; defined later in the file
  5142. (defun org-font-lock-add-priority-faces (limit)
  5143. "Add the special priority faces."
  5144. (while (re-search-forward org-priority-regexp limit t)
  5145. (add-text-properties
  5146. (match-beginning 1) (1+ (match-end 2))
  5147. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5148. 'font-lock-fontified t))))
  5149. (defun org-font-lock-add-tag-faces (limit)
  5150. "Add the special tag faces."
  5151. (when (and org-tag-faces org-tags-special-faces-re)
  5152. (while (re-search-forward org-tags-special-faces-re limit t)
  5153. (add-text-properties (match-beginning 1) (match-end 1)
  5154. (list 'face (org-get-tag-face 1)
  5155. 'font-lock-fontified t))
  5156. (backward-char 1))))
  5157. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5158. "Remove fontification and activation overlays from links."
  5159. (font-lock-default-unfontify-region beg end)
  5160. (let* ((buffer-undo-list t)
  5161. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5162. (inhibit-modification-hooks t)
  5163. deactivate-mark buffer-file-name buffer-file-truename)
  5164. (decompose-region beg end)
  5165. (remove-text-properties beg end
  5166. '(mouse-face t keymap t org-linked-text t
  5167. invisible t intangible t
  5168. org-emphasis t))
  5169. (org-remove-font-lock-display-properties beg end)))
  5170. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5171. ((raise 0.3) (height 0.7))
  5172. ((raise -0.5))
  5173. ((raise 0.5)))
  5174. "Display properties for showing superscripts and subscripts.")
  5175. (defun org-remove-font-lock-display-properties (beg end)
  5176. "Remove specific display properties that have been added by font lock.
  5177. The will remove the raise properties that are used to show superscripts
  5178. and subscripts."
  5179. (let (next prop)
  5180. (while (< beg end)
  5181. (setq next (next-single-property-change beg 'display nil end)
  5182. prop (get-text-property beg 'display))
  5183. (when (member prop org-script-display)
  5184. (put-text-property beg next 'display nil))
  5185. (setq beg next))))
  5186. (defun org-raise-scripts (limit)
  5187. "Add raise properties to sub/superscripts."
  5188. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5189. (re-search-forward
  5190. (if (eq org-use-sub-superscripts t)
  5191. org-match-substring-regexp
  5192. org-match-substring-with-braces-regexp)
  5193. limit t))
  5194. (let* ((pos (point)) table-p comment-p
  5195. (mpos (match-beginning 3))
  5196. (emph-p (get-text-property mpos 'org-emphasis))
  5197. (link-p (get-text-property mpos 'mouse-face))
  5198. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5199. (goto-char (point-at-bol))
  5200. (setq table-p (looking-at-p org-table-dataline-regexp)
  5201. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5202. (goto-char pos)
  5203. ;; Handle a_b^c
  5204. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5205. (unless (or comment-p emph-p link-p keyw-p)
  5206. (put-text-property (match-beginning 3) (match-end 0)
  5207. 'display
  5208. (if (equal (char-after (match-beginning 2)) ?^)
  5209. (nth (if table-p 3 1) org-script-display)
  5210. (nth (if table-p 2 0) org-script-display)))
  5211. (add-text-properties (match-beginning 2) (match-end 2)
  5212. (list 'invisible t))
  5213. (when (and (eq (char-after (match-beginning 3)) ?{)
  5214. (eq (char-before (match-end 3)) ?}))
  5215. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5216. (list 'invisible t))
  5217. (add-text-properties (1- (match-end 3)) (match-end 3)
  5218. (list 'invisible t))))
  5219. t)))
  5220. (defun org-remove-empty-overlays-at (pos)
  5221. "Remove outline overlays that do not contain non-white stuff."
  5222. (dolist (o (overlays-at pos))
  5223. (and (eq 'outline (overlay-get o 'invisible))
  5224. (not (string-match-p "\\S-" (buffer-substring (overlay-start o)
  5225. (overlay-end o))))
  5226. (delete-overlay o))))
  5227. (defun org-show-empty-lines-in-parent ()
  5228. "Move to the parent and re-show empty lines before visible headlines."
  5229. (save-excursion
  5230. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5231. (org-cycle-show-empty-lines context))))
  5232. (defun org-files-list ()
  5233. "Return `org-agenda-files' list, plus all open Org files.
  5234. This is useful for operations that need to scan all of a user's
  5235. open and agenda-wise Org files."
  5236. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5237. (dolist (buf (buffer-list))
  5238. (with-current-buffer buf
  5239. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5240. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5241. :test #'equal))))
  5242. files))
  5243. (defsubst org-entry-beginning-position ()
  5244. "Return the beginning position of the current entry."
  5245. (save-excursion (org-back-to-heading t) (point)))
  5246. (defsubst org-entry-end-position ()
  5247. "Return the end position of the current entry."
  5248. (save-excursion (outline-next-heading) (point)))
  5249. (defun org-subtree-end-visible-p ()
  5250. "Is the end of the current subtree visible?"
  5251. (pos-visible-in-window-p
  5252. (save-excursion (org-end-of-subtree t) (point))))
  5253. (defun org-first-headline-recenter ()
  5254. "Move cursor to the first headline and recenter the headline."
  5255. (let ((window (get-buffer-window)))
  5256. (when window
  5257. (goto-char (point-min))
  5258. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5259. (set-window-start window (line-beginning-position))))))
  5260. ;;; Visibility (headlines, blocks, drawers)
  5261. ;;;; Headlines visibility
  5262. (defun org-show-entry ()
  5263. "Show the body directly following its heading.
  5264. Show the heading too, if it is currently invisible."
  5265. (interactive)
  5266. (save-excursion
  5267. (org-back-to-heading-or-point-min t)
  5268. (org-flag-region
  5269. (line-end-position 0)
  5270. (save-excursion
  5271. (if (re-search-forward
  5272. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5273. (match-beginning 1)
  5274. (point-max)))
  5275. nil
  5276. 'outline)
  5277. (org-cycle-hide-drawers 'children)))
  5278. (defun org-hide-entry ()
  5279. "Hide the body directly following its heading."
  5280. (interactive)
  5281. (save-excursion
  5282. (org-back-to-heading-or-point-min t)
  5283. (when (org-at-heading-p) (forward-line))
  5284. (org-flag-region
  5285. (line-end-position 0)
  5286. (save-excursion
  5287. (if (re-search-forward
  5288. (concat "[\r\n]" org-outline-regexp) nil t)
  5289. (line-end-position 0)
  5290. (point-max)))
  5291. t
  5292. 'outline)))
  5293. (defun org-show-children (&optional level)
  5294. "Show all direct subheadings of this heading.
  5295. Prefix arg LEVEL is how many levels below the current level
  5296. should be shown. Default is enough to cause the following
  5297. heading to appear."
  5298. (interactive "p")
  5299. (unless (org-before-first-heading-p)
  5300. (save-excursion
  5301. (org-with-limited-levels (org-back-to-heading t))
  5302. (let* ((current-level (funcall outline-level))
  5303. (max-level (org-get-valid-level
  5304. current-level
  5305. (if level (prefix-numeric-value level) 1)))
  5306. (end (save-excursion (org-end-of-subtree t t)))
  5307. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5308. (past-first-child nil)
  5309. ;; Make sure to skip inlinetasks.
  5310. (re (format regexp-fmt
  5311. current-level
  5312. (cond
  5313. ((not (featurep 'org-inlinetask)) "")
  5314. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5315. 3))
  5316. (t (1- org-inlinetask-min-level))))))
  5317. ;; Display parent heading.
  5318. (org-flag-heading nil)
  5319. (forward-line)
  5320. ;; Display children. First child may be deeper than expected
  5321. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5322. ;; MAX-LEVEL accordingly.
  5323. (while (re-search-forward re end t)
  5324. (unless past-first-child
  5325. (setq re (format regexp-fmt
  5326. current-level
  5327. (max (funcall outline-level) max-level)))
  5328. (setq past-first-child t))
  5329. (org-flag-heading nil))))))
  5330. (defun org-show-subtree ()
  5331. "Show everything after this heading at deeper levels."
  5332. (interactive)
  5333. (org-flag-region
  5334. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5335. ;;;; Blocks and drawers visibility
  5336. (defun org--hide-wrapper-toggle (element category force no-error)
  5337. "Toggle visibility for ELEMENT.
  5338. ELEMENT is a block or drawer type parsed element. CATEGORY is
  5339. either `block' or `drawer'. When FORCE is `off', show the block
  5340. or drawer. If it is non-nil, hide it unconditionally. Throw an
  5341. error when not at a block or drawer, unless NO-ERROR is non-nil.
  5342. Return a non-nil value when toggling is successful."
  5343. (let ((type (org-element-type element)))
  5344. (cond
  5345. ((memq type
  5346. (pcase category
  5347. (`drawer '(drawer property-drawer))
  5348. (`block '(center-block
  5349. comment-block dynamic-block example-block export-block
  5350. quote-block special-block src-block verse-block))
  5351. (_ (error "Unknown category: %S" category))))
  5352. (let* ((post (org-element-property :post-affiliated element))
  5353. (start (save-excursion
  5354. (goto-char post)
  5355. (line-end-position)))
  5356. (end (save-excursion
  5357. (goto-char (org-element-property :end element))
  5358. (skip-chars-backward " \t\n")
  5359. (line-end-position))))
  5360. ;; Do nothing when not before or at the block opening line or
  5361. ;; at the block closing line.
  5362. (unless (let ((eol (line-end-position)))
  5363. (and (> eol start) (/= eol end)))
  5364. (let* ((spec (if (eq category 'block) 'org-hide-block 'outline))
  5365. (flag
  5366. (cond ((eq force 'off) nil)
  5367. (force t)
  5368. ((eq spec (get-char-property start 'invisible)) nil)
  5369. (t t))))
  5370. (org-flag-region start end flag spec))
  5371. ;; When the block is hidden away, make sure point is left in
  5372. ;; a visible part of the buffer.
  5373. (when (invisible-p (max (1- (point)) (point-min)))
  5374. (goto-char post))
  5375. ;; Signal success.
  5376. t)))
  5377. (no-error nil)
  5378. (t
  5379. (user-error (if (eq category 'drawer)
  5380. "Not at a drawer"
  5381. "Not at a block"))))))
  5382. (defun org-hide-block-toggle (&optional force no-error element)
  5383. "Toggle the visibility of the current block.
  5384. When optional argument FORCE is `off', make block visible. If it
  5385. is non-nil, hide it unconditionally. Throw an error when not at
  5386. a block, unless NO-ERROR is non-nil. When optional argument
  5387. ELEMENT is provided, consider it instead of the current block.
  5388. Return a non-nil value when toggling is successful."
  5389. (interactive)
  5390. (org--hide-wrapper-toggle
  5391. (or element (org-element-at-point)) 'block force no-error))
  5392. (defun org-hide-drawer-toggle (&optional force no-error element)
  5393. "Toggle the visibility of the current drawer.
  5394. When optional argument FORCE is `off', make drawer visible. If
  5395. it is non-nil, hide it unconditionally. Throw an error when not
  5396. at a drawer, unless NO-ERROR is non-nil. When optional argument
  5397. ELEMENT is provided, consider it instead of the current drawer.
  5398. Return a non-nil value when toggling is successful."
  5399. (interactive)
  5400. (org--hide-wrapper-toggle
  5401. (or element (org-element-at-point)) 'drawer force no-error))
  5402. (defun org-hide-block-all ()
  5403. "Fold all blocks in the current buffer."
  5404. (interactive)
  5405. (org-show-all '(blocks))
  5406. (org-block-map 'org-hide-block-toggle))
  5407. (defun org-hide-drawer-all ()
  5408. "Fold all drawers in the current buffer."
  5409. (save-excursion
  5410. (goto-char (point-min))
  5411. (while (re-search-forward org-drawer-regexp nil t)
  5412. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5413. 'invisible))
  5414. (o (cdr-safe pair)))
  5415. (if (overlayp o) (goto-char (overlay-end o)) ;invisible drawer
  5416. (pcase (get-char-property-and-overlay (point) 'invisible)
  5417. (`(outline . ,o) (goto-char (overlay-end o))) ;already folded
  5418. (_
  5419. (let* ((drawer (org-element-at-point))
  5420. (type (org-element-type drawer)))
  5421. (when (memq type '(drawer property-drawer))
  5422. (org-hide-drawer-toggle t nil drawer)
  5423. ;; Make sure to skip drawer entirely or we might flag it
  5424. ;; another time when matching its ending line with
  5425. ;; `org-drawer-regexp'.
  5426. (goto-char (org-element-property :end drawer)))))))))))
  5427. (defun org-cycle-hide-drawers (state)
  5428. "Re-hide all drawers after a visibility state change.
  5429. STATE should be one of the symbols listed in the docstring of
  5430. `org-cycle-hook'."
  5431. (when (and (derived-mode-p 'org-mode)
  5432. (not (memq state '(overview folded contents))))
  5433. (let* ((global? (eq state 'all))
  5434. (beg (if global? (point-min) (line-beginning-position)))
  5435. (end (cond (global? (point-max))
  5436. ((eq state 'children) (org-entry-end-position))
  5437. (t (save-excursion (org-end-of-subtree t t))))))
  5438. (save-excursion
  5439. (goto-char beg)
  5440. (while (re-search-forward org-drawer-regexp end t)
  5441. (pcase (get-char-property-and-overlay (point) 'invisible)
  5442. ;; Do not fold already folded drawers.
  5443. (`(outline . ,o) (goto-char (overlay-end o)))
  5444. (_
  5445. (let ((drawer (org-element-at-point)))
  5446. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5447. (org-hide-drawer-toggle t nil drawer)
  5448. ;; Make sure to skip drawer entirely or we might flag
  5449. ;; it another time when matching its ending line with
  5450. ;; `org-drawer-regexp'.
  5451. (goto-char (org-element-property :end drawer)))))))))))
  5452. ;;;; Visibility cycling
  5453. (defvar-local org-cycle-global-status nil)
  5454. (put 'org-cycle-global-status 'org-state t)
  5455. (defvar-local org-cycle-subtree-status nil)
  5456. (put 'org-cycle-subtree-status 'org-state t)
  5457. (defun org-show-all (&optional types)
  5458. "Show all contents in the visible part of the buffer.
  5459. By default, the function expands headings, blocks and drawers.
  5460. When optional argument TYPE is a list of symbols among `blocks',
  5461. `drawers' and `headings', to only expand one specific type."
  5462. (interactive)
  5463. (let ((types (or types '(blocks drawers headings))))
  5464. (when (memq 'blocks types)
  5465. (org-flag-region (point-min) (point-max) nil 'org-hide-block))
  5466. (cond
  5467. ;; Fast path. Since headings and drawers share the same
  5468. ;; invisible spec, clear everything in one go.
  5469. ((and (memq 'headings types)
  5470. (memq 'drawers types))
  5471. (org-flag-region (point-min) (point-max) nil 'outline))
  5472. ((memq 'headings types)
  5473. (org-flag-region (point-min) (point-max) nil 'outline)
  5474. (org-cycle-hide-drawers 'all))
  5475. ((memq 'drawers types)
  5476. (save-excursion
  5477. (goto-char (point-min))
  5478. (while (re-search-forward org-drawer-regexp nil t)
  5479. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5480. 'invisible))
  5481. (o (cdr-safe pair)))
  5482. (if (overlayp o) (goto-char (overlay-end o))
  5483. (pcase (get-char-property-and-overlay (point) 'invisible)
  5484. (`(outline . ,o)
  5485. (goto-char (overlay-end o))
  5486. (delete-overlay o))
  5487. (_ nil))))))))))
  5488. ;;;###autoload
  5489. (defun org-cycle (&optional arg)
  5490. "TAB-action and visibility cycling for Org mode.
  5491. This is the command invoked in Org mode by the `TAB' key. Its main
  5492. purpose is outline visibility cycling, but it also invokes other actions
  5493. in special contexts.
  5494. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5495. the entire
  5496. buffer through 3 states (global cycling)
  5497. 1. OVERVIEW: Show only top-level headlines.
  5498. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5499. 3. SHOW ALL: Show everything.
  5500. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5501. switch to the startup visibility,
  5502. determined by the variable `org-startup-folded', and by any VISIBILITY
  5503. properties in the buffer.
  5504. With a `\\[universal-argument] \\[universal-argument] \
  5505. \\[universal-argument]' prefix argument, show the entire buffer, including
  5506. any drawers.
  5507. When inside a table, re-align the table and move to the next field.
  5508. When point is at the beginning of a headline, rotate the subtree started
  5509. by this line through 3 different states (local cycling)
  5510. 1. FOLDED: Only the main headline is shown.
  5511. 2. CHILDREN: The main headline and the direct children are shown.
  5512. From this state, you can move to one of the children
  5513. and zoom in further.
  5514. 3. SUBTREE: Show the entire subtree, including body text.
  5515. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5516. When point is at the beginning of an empty headline and the variable
  5517. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5518. of the headline by demoting and promoting it to likely levels. This
  5519. speeds up creation document structure by pressing `TAB' once or several
  5520. times right after creating a new headline.
  5521. When there is a numeric prefix, go up to a heading with level ARG, do
  5522. a `show-subtree' and return to the previous cursor position. If ARG
  5523. is negative, go up that many levels.
  5524. When point is not at the beginning of a headline, execute the global
  5525. binding for `TAB', which is re-indenting the line. See the option
  5526. `org-cycle-emulate-tab' for details.
  5527. As a special case, if point is at the very beginning of the buffer, if
  5528. there is no headline there, and if the variable `org-cycle-global-at-bob'
  5529. is non-nil, this function acts as if called with prefix argument \
  5530. \(`\\[universal-argument] TAB',
  5531. same as `S-TAB') also when called without prefix argument."
  5532. (interactive "P")
  5533. (org-load-modules-maybe)
  5534. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5535. (and org-cycle-level-after-item/entry-creation
  5536. (or (org-cycle-level)
  5537. (org-cycle-item-indentation))))
  5538. (let* ((limit-level
  5539. (or org-cycle-max-level
  5540. (and (boundp 'org-inlinetask-min-level)
  5541. org-inlinetask-min-level
  5542. (1- org-inlinetask-min-level))))
  5543. (nstars
  5544. (and limit-level
  5545. (if org-odd-levels-only
  5546. (1- (* 2 limit-level))
  5547. limit-level)))
  5548. (org-outline-regexp
  5549. (format "\\*%s " (if nstars (format "\\{1,%d\\}" nstars) "+"))))
  5550. (cond
  5551. ((equal arg '(16))
  5552. (setq last-command 'dummy)
  5553. (org-set-startup-visibility)
  5554. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5555. ((equal arg '(64))
  5556. (org-show-all)
  5557. (org-unlogged-message "Entire buffer visible, including drawers"))
  5558. ((equal arg '(4)) (org-cycle-internal-global))
  5559. ;; Show-subtree, ARG levels up from here.
  5560. ((integerp arg)
  5561. (save-excursion
  5562. (org-back-to-heading)
  5563. (outline-up-heading (if (< arg 0) (- arg)
  5564. (- (funcall outline-level) arg)))
  5565. (org-show-subtree)))
  5566. ;; Global cycling at BOB: delegate to `org-cycle-internal-global'.
  5567. ((and org-cycle-global-at-bob
  5568. (bobp)
  5569. (not (looking-at org-outline-regexp)))
  5570. (let ((org-cycle-hook
  5571. (remq 'org-optimize-window-after-visibility-change
  5572. org-cycle-hook)))
  5573. (org-cycle-internal-global)))
  5574. ;; Try CDLaTeX TAB completion.
  5575. ((org-try-cdlatex-tab))
  5576. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5577. ((and (featurep 'org-inlinetask)
  5578. (org-inlinetask-at-task-p)
  5579. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5580. (org-inlinetask-toggle-visibility))
  5581. (t
  5582. (let ((pos (point))
  5583. (element (org-element-at-point)))
  5584. (cond
  5585. ;; Try toggling visibility for block at point.
  5586. ((org-hide-block-toggle nil t element))
  5587. ;; Try toggling visibility for drawer at point.
  5588. ((org-hide-drawer-toggle nil t element))
  5589. ;; Table: enter it or move to the next field.
  5590. ((and (org-match-line "[ \t]*[|+]")
  5591. (org-element-lineage element '(table) t))
  5592. (if (and (eq 'table (org-element-type element))
  5593. (eq 'table.el (org-element-property :type element)))
  5594. (message (substitute-command-keys "\\<org-mode-map>\
  5595. Use `\\[org-edit-special]' to edit table.el tables"))
  5596. (org-table-justify-field-maybe)
  5597. (call-interactively #'org-table-next-field)))
  5598. ((run-hook-with-args-until-success
  5599. 'org-tab-after-check-for-table-hook))
  5600. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5601. ((and (or (and org-cycle-include-plain-lists
  5602. (let ((item (org-element-lineage element
  5603. '(item plain-list)
  5604. t)))
  5605. (and item
  5606. (= (line-beginning-position)
  5607. (org-element-property :post-affiliated
  5608. item)))))
  5609. (org-match-line org-outline-regexp))
  5610. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5611. (org-cycle-internal-local))
  5612. ;; From there: TAB emulation and template completion.
  5613. (buffer-read-only (org-back-to-heading))
  5614. ((run-hook-with-args-until-success
  5615. 'org-tab-after-check-for-cycling-hook))
  5616. ((run-hook-with-args-until-success
  5617. 'org-tab-before-tab-emulation-hook))
  5618. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5619. (or (not (bolp))
  5620. (not (looking-at org-outline-regexp))))
  5621. (call-interactively (global-key-binding (kbd "TAB"))))
  5622. ((or (eq org-cycle-emulate-tab t)
  5623. (and (memq org-cycle-emulate-tab '(white whitestart))
  5624. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5625. (or (and (eq org-cycle-emulate-tab 'white)
  5626. (= (match-end 0) (point-at-eol)))
  5627. (and (eq org-cycle-emulate-tab 'whitestart)
  5628. (>= (match-end 0) pos)))))
  5629. (call-interactively (global-key-binding (kbd "TAB"))))
  5630. (t
  5631. (save-excursion
  5632. (org-back-to-heading)
  5633. (org-cycle))))))))))
  5634. (defun org-cycle-internal-global ()
  5635. "Do the global cycling action."
  5636. ;; Hack to avoid display of messages for .org attachments in Gnus
  5637. (let ((ga (string-match-p "\\*fontification" (buffer-name))))
  5638. (cond
  5639. ((and (eq last-command this-command)
  5640. (eq org-cycle-global-status 'overview))
  5641. ;; We just created the overview - now do table of contents
  5642. ;; This can be slow in very large buffers, so indicate action
  5643. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5644. (unless ga (org-unlogged-message "CONTENTS..."))
  5645. (org-content)
  5646. (unless ga (org-unlogged-message "CONTENTS...done"))
  5647. (setq org-cycle-global-status 'contents)
  5648. (run-hook-with-args 'org-cycle-hook 'contents))
  5649. ((and (eq last-command this-command)
  5650. (eq org-cycle-global-status 'contents))
  5651. ;; We just showed the table of contents - now show everything
  5652. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5653. (org-show-all '(headings blocks))
  5654. (unless ga (org-unlogged-message "SHOW ALL"))
  5655. (setq org-cycle-global-status 'all)
  5656. (run-hook-with-args 'org-cycle-hook 'all))
  5657. (t
  5658. ;; Default action: go to overview
  5659. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5660. (org-overview)
  5661. (unless ga (org-unlogged-message "OVERVIEW"))
  5662. (setq org-cycle-global-status 'overview)
  5663. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5664. (defvar org-called-with-limited-levels nil
  5665. "Non-nil when `org-with-limited-levels' is currently active.")
  5666. (defun org-cycle-internal-local ()
  5667. "Do the local cycling action."
  5668. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5669. ;; First, determine end of headline (EOH), end of subtree or item
  5670. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5671. (save-excursion
  5672. (if (org-at-item-p)
  5673. (progn
  5674. (beginning-of-line)
  5675. (setq struct (org-list-struct))
  5676. (setq eoh (point-at-eol))
  5677. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5678. (setq has-children (org-list-has-child-p (point) struct)))
  5679. (org-back-to-heading)
  5680. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5681. (setq eos (save-excursion
  5682. (org-end-of-subtree t t)
  5683. (unless (eobp) (forward-char -1))
  5684. (point)))
  5685. (setq has-children
  5686. (or
  5687. (save-excursion
  5688. (let ((level (funcall outline-level)))
  5689. (outline-next-heading)
  5690. (and (org-at-heading-p t)
  5691. (> (funcall outline-level) level))))
  5692. (and (eq org-cycle-include-plain-lists 'integrate)
  5693. (save-excursion
  5694. (org-list-search-forward (org-item-beginning-re) eos t))))))
  5695. ;; Determine end invisible part of buffer (EOL)
  5696. (beginning-of-line 2)
  5697. (while (and (not (eobp)) ;this is like `next-line'
  5698. (get-char-property (1- (point)) 'invisible))
  5699. (goto-char (next-single-char-property-change (point) 'invisible))
  5700. (and (eolp) (beginning-of-line 2)))
  5701. (setq eol (point)))
  5702. ;; Find out what to do next and set `this-command'
  5703. (cond
  5704. ((= eos eoh)
  5705. ;; Nothing is hidden behind this heading
  5706. (unless (org-before-first-heading-p)
  5707. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5708. (org-unlogged-message "EMPTY ENTRY")
  5709. (setq org-cycle-subtree-status nil)
  5710. (save-excursion
  5711. (goto-char eos)
  5712. (outline-next-heading)
  5713. (when (org-invisible-p) (org-flag-heading nil))))
  5714. ((and (or (>= eol eos)
  5715. (not (string-match "\\S-" (buffer-substring eol eos))))
  5716. (or has-children
  5717. (not (setq children-skipped
  5718. org-cycle-skip-children-state-if-no-children))))
  5719. ;; Entire subtree is hidden in one line: children view
  5720. (unless (org-before-first-heading-p)
  5721. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5722. (if (org-at-item-p)
  5723. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5724. (org-show-entry)
  5725. (org-with-limited-levels (org-show-children))
  5726. (org-show-set-visibility 'canonical)
  5727. ;; Fold every list in subtree to top-level items.
  5728. (when (eq org-cycle-include-plain-lists 'integrate)
  5729. (save-excursion
  5730. (org-back-to-heading)
  5731. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5732. (beginning-of-line 1)
  5733. (let* ((struct (org-list-struct))
  5734. (prevs (org-list-prevs-alist struct))
  5735. (end (org-list-get-bottom-point struct)))
  5736. (dolist (e (org-list-get-all-items (point) struct prevs))
  5737. (org-list-set-item-visibility e struct 'folded))
  5738. (goto-char (if (< end eos) end eos)))))))
  5739. (org-unlogged-message "CHILDREN")
  5740. (save-excursion
  5741. (goto-char eos)
  5742. (outline-next-heading)
  5743. (when (org-invisible-p) (org-flag-heading nil)))
  5744. (setq org-cycle-subtree-status 'children)
  5745. (unless (org-before-first-heading-p)
  5746. (run-hook-with-args 'org-cycle-hook 'children)))
  5747. ((or children-skipped
  5748. (and (eq last-command this-command)
  5749. (eq org-cycle-subtree-status 'children)))
  5750. ;; We just showed the children, or no children are there,
  5751. ;; now show everything.
  5752. (unless (org-before-first-heading-p)
  5753. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5754. (org-flag-region eoh eos nil 'outline)
  5755. (org-unlogged-message
  5756. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5757. (setq org-cycle-subtree-status 'subtree)
  5758. (unless (org-before-first-heading-p)
  5759. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5760. (t
  5761. ;; Default action: hide the subtree.
  5762. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5763. (org-flag-region eoh eos t 'outline)
  5764. (org-unlogged-message "FOLDED")
  5765. (setq org-cycle-subtree-status 'folded)
  5766. (unless (org-before-first-heading-p)
  5767. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5768. ;;;###autoload
  5769. (defun org-global-cycle (&optional arg)
  5770. "Cycle the global visibility. For details see `org-cycle'.
  5771. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5772. With a numeric prefix, show all headlines up to that level."
  5773. (interactive "P")
  5774. (cond
  5775. ((integerp arg)
  5776. (org-content arg)
  5777. (setq org-cycle-global-status 'contents))
  5778. ((equal arg '(4))
  5779. (org-set-startup-visibility)
  5780. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5781. (t
  5782. (org-cycle '(4)))))
  5783. (defun org-set-startup-visibility ()
  5784. "Set the visibility required by startup options and properties."
  5785. (cond
  5786. ((eq org-startup-folded t)
  5787. (org-overview))
  5788. ((eq org-startup-folded 'content)
  5789. (org-content))
  5790. ((or (eq org-startup-folded 'showeverything)
  5791. (eq org-startup-folded nil))
  5792. (org-show-all)))
  5793. (unless (eq org-startup-folded 'showeverything)
  5794. (when org-hide-block-startup (org-hide-block-all))
  5795. (org-set-visibility-according-to-property)
  5796. (org-cycle-hide-archived-subtrees 'all)
  5797. (org-cycle-hide-drawers 'all)
  5798. (org-cycle-show-empty-lines t)))
  5799. (defun org-set-visibility-according-to-property ()
  5800. "Switch subtree visibility according to VISIBILITY property."
  5801. (interactive)
  5802. (let ((regexp (org-re-property "VISIBILITY")))
  5803. (org-with-point-at 1
  5804. (while (re-search-forward regexp nil t)
  5805. (let ((state (match-string 3)))
  5806. (if (not (org-at-property-p)) (outline-next-heading)
  5807. (save-excursion
  5808. (org-back-to-heading t)
  5809. (org-flag-subtree t)
  5810. (org-reveal)
  5811. (pcase state
  5812. ("folded"
  5813. (org-flag-subtree t))
  5814. ("children"
  5815. (org-show-hidden-entry)
  5816. (org-show-children))
  5817. ("content"
  5818. (save-excursion
  5819. (save-restriction
  5820. (org-narrow-to-subtree)
  5821. (org-content))))
  5822. ((or "all" "showall")
  5823. (outline-show-subtree))
  5824. (_ nil)))
  5825. (org-end-of-subtree)))))))
  5826. (defun org-overview ()
  5827. "Switch to overview mode, showing only top-level headlines."
  5828. (interactive)
  5829. (org-show-all '(headings drawers))
  5830. (save-excursion
  5831. (goto-char (point-min))
  5832. (when (re-search-forward org-outline-regexp-bol nil t)
  5833. (let* ((last (line-end-position))
  5834. (level (- (match-end 0) (match-beginning 0) 1))
  5835. (regexp (format "^\\*\\{1,%d\\} " level)))
  5836. (while (re-search-forward regexp nil :move)
  5837. (org-flag-region last (line-end-position 0) t 'outline)
  5838. (setq last (line-end-position))
  5839. (setq level (- (match-end 0) (match-beginning 0) 1))
  5840. (setq regexp (format "^\\*\\{1,%d\\} " level)))
  5841. (org-flag-region last (point) t 'outline)))))
  5842. (defun org-content (&optional arg)
  5843. "Show all headlines in the buffer, like a table of contents.
  5844. With numerical argument N, show content up to level N."
  5845. (interactive "p")
  5846. (org-show-all '(headings drawers))
  5847. (save-excursion
  5848. (goto-char (point-max))
  5849. (let ((regexp (if (and (wholenump arg) (> arg 0))
  5850. (format "^\\*\\{1,%d\\} " arg)
  5851. "^\\*+ "))
  5852. (last (point)))
  5853. (while (re-search-backward regexp nil t)
  5854. (org-flag-region (line-end-position) last t 'outline)
  5855. (setq last (line-end-position 0))))))
  5856. (defvar org-scroll-position-to-restore nil
  5857. "Temporarily store scroll position to restore.")
  5858. (defun org-optimize-window-after-visibility-change (state)
  5859. "Adjust the window after a change in outline visibility.
  5860. This function is the default value of the hook `org-cycle-hook'."
  5861. (when (get-buffer-window (current-buffer))
  5862. (let ((repeat (eq last-command this-command)))
  5863. (unless repeat
  5864. (setq org-scroll-position-to-restore nil))
  5865. (cond
  5866. ((eq state 'content) nil)
  5867. ((eq state 'all) nil)
  5868. ((and org-scroll-position-to-restore repeat
  5869. (eq state 'folded))
  5870. (set-window-start nil org-scroll-position-to-restore))
  5871. ((eq state 'folded) nil)
  5872. ((eq state 'children)
  5873. (setq org-scroll-position-to-restore (window-start))
  5874. (or (org-subtree-end-visible-p) (recenter 1)))
  5875. ((eq state 'subtree)
  5876. (unless repeat
  5877. (setq org-scroll-position-to-restore (window-start)))
  5878. (or (org-subtree-end-visible-p) (recenter 1)))))))
  5879. (defun org-clean-visibility-after-subtree-move ()
  5880. "Fix visibility issues after moving a subtree."
  5881. ;; First, find a reasonable region to look at:
  5882. ;; Start two siblings above, end three below
  5883. (let* ((beg (save-excursion
  5884. (and (org-get-last-sibling)
  5885. (org-get-last-sibling))
  5886. (point)))
  5887. (end (save-excursion
  5888. (and (org-get-next-sibling)
  5889. (org-get-next-sibling)
  5890. (org-get-next-sibling))
  5891. (if (org-at-heading-p)
  5892. (point-at-eol)
  5893. (point))))
  5894. (level (looking-at "\\*+"))
  5895. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5896. (save-excursion
  5897. (save-restriction
  5898. (narrow-to-region beg end)
  5899. (when re
  5900. ;; Properly fold already folded siblings
  5901. (goto-char (point-min))
  5902. (while (re-search-forward re nil t)
  5903. (when (and (not (org-invisible-p))
  5904. (org-invisible-p (line-end-position)))
  5905. (outline-hide-entry))))
  5906. (org-cycle-hide-drawers 'all)
  5907. (org-cycle-show-empty-lines 'overview)))))
  5908. (defun org-cycle-show-empty-lines (state)
  5909. "Show empty lines above all visible headlines.
  5910. The region to be covered depends on STATE when called through
  5911. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5912. entire buffer covered. Note that an empty line is only shown if there
  5913. are at least `org-cycle-separator-lines' empty lines before the headline."
  5914. (when (/= org-cycle-separator-lines 0)
  5915. (save-excursion
  5916. (let* ((n (abs org-cycle-separator-lines))
  5917. (re (cond
  5918. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5919. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5920. (t (let ((ns (number-to-string (- n 2))))
  5921. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5922. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5923. beg end)
  5924. (cond
  5925. ((memq state '(overview contents t))
  5926. (setq beg (point-min) end (point-max)))
  5927. ((memq state '(children folded))
  5928. (setq beg (point)
  5929. end (progn (org-end-of-subtree t t)
  5930. (line-beginning-position 2)))))
  5931. (when beg
  5932. (goto-char beg)
  5933. (while (re-search-forward re end t)
  5934. (unless (get-char-property (match-end 1) 'invisible)
  5935. (let ((e (match-end 1))
  5936. (b (if (>= org-cycle-separator-lines 0)
  5937. (match-beginning 1)
  5938. (save-excursion
  5939. (goto-char (match-beginning 0))
  5940. (skip-chars-backward " \t\n")
  5941. (line-end-position)))))
  5942. (org-flag-region b e nil 'outline))))))))
  5943. ;; Never hide empty lines at the end of the file.
  5944. (save-excursion
  5945. (goto-char (point-max))
  5946. (outline-previous-heading)
  5947. (outline-end-of-heading)
  5948. (when (and (looking-at "[ \t\n]+")
  5949. (= (match-end 0) (point-max)))
  5950. (org-flag-region (point) (match-end 0) nil 'outline))))
  5951. ;;;; Reveal point location
  5952. (defun org-show-context (&optional key)
  5953. "Make sure point and context are visible.
  5954. Optional argument KEY, when non-nil, is a symbol. See
  5955. `org-show-context-detail' for allowed values and how much is to
  5956. be shown."
  5957. (org-show-set-visibility
  5958. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  5959. ((cdr (assq key org-show-context-detail)))
  5960. (t (cdr (assq 'default org-show-context-detail))))))
  5961. (defun org-show-set-visibility (detail)
  5962. "Set visibility around point according to DETAIL.
  5963. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  5964. `tree', `canonical' or t. See `org-show-context-detail' for more
  5965. information."
  5966. ;; Show current heading and possibly its entry, following headline
  5967. ;; or all children.
  5968. (if (and (org-at-heading-p) (not (eq detail 'local)))
  5969. (org-flag-heading nil)
  5970. (org-show-entry)
  5971. ;; If point is hidden within a drawer or a block, make sure to
  5972. ;; expose it.
  5973. (dolist (o (overlays-at (point)))
  5974. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  5975. (delete-overlay o)))
  5976. (unless (org-before-first-heading-p)
  5977. (org-with-limited-levels
  5978. (cl-case detail
  5979. ((tree canonical t) (org-show-children))
  5980. ((nil minimal ancestors))
  5981. (t (save-excursion
  5982. (outline-next-heading)
  5983. (org-flag-heading nil)))))))
  5984. ;; Show all siblings.
  5985. (when (eq detail 'lineage) (org-show-siblings))
  5986. ;; Show ancestors, possibly with their children.
  5987. (when (memq detail '(ancestors lineage tree canonical t))
  5988. (save-excursion
  5989. (while (org-up-heading-safe)
  5990. (org-flag-heading nil)
  5991. (when (memq detail '(canonical t)) (org-show-entry))
  5992. (when (memq detail '(tree canonical t)) (org-show-children))))))
  5993. (defvar org-reveal-start-hook nil
  5994. "Hook run before revealing a location.")
  5995. (defun org-reveal (&optional siblings)
  5996. "Show current entry, hierarchy above it, and the following headline.
  5997. This can be used to show a consistent set of context around
  5998. locations exposed with `org-show-context'.
  5999. With optional argument SIBLINGS, on each level of the hierarchy all
  6000. siblings are shown. This repairs the tree structure to what it would
  6001. look like when opened with hierarchical calls to `org-cycle'.
  6002. With a \\[universal-argument] \\[universal-argument] prefix, \
  6003. go to the parent and show the entire tree."
  6004. (interactive "P")
  6005. (run-hooks 'org-reveal-start-hook)
  6006. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6007. ((equal siblings '(16))
  6008. (save-excursion
  6009. (when (org-up-heading-safe)
  6010. (org-show-subtree)
  6011. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6012. (t (org-show-set-visibility 'lineage))))
  6013. ;;; Indirect buffer display of subtrees
  6014. (defvar org-indirect-dedicated-frame nil
  6015. "This is the frame being used for indirect tree display.")
  6016. (defvar org-last-indirect-buffer nil)
  6017. (defun org-tree-to-indirect-buffer (&optional arg)
  6018. "Create indirect buffer and narrow it to current subtree.
  6019. With a numerical prefix ARG, go up to this level and then take that tree.
  6020. If ARG is negative, go up that many levels.
  6021. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6022. indirect buffer previously made with this command, to avoid proliferation of
  6023. indirect buffers. However, when you call the command with a \
  6024. `\\[universal-argument]' prefix, or
  6025. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6026. so that you can work with several indirect buffers at the same time. If
  6027. `org-indirect-buffer-display' is `dedicated-frame', the \
  6028. `\\[universal-argument]' prefix also
  6029. requests that a new frame be made for the new buffer, so that the dedicated
  6030. frame is not changed."
  6031. (interactive "P")
  6032. (let ((cbuf (current-buffer))
  6033. (cwin (selected-window))
  6034. (pos (point))
  6035. beg end level heading ibuf)
  6036. (save-excursion
  6037. (org-back-to-heading t)
  6038. (when (numberp arg)
  6039. (setq level (org-outline-level))
  6040. (when (< arg 0) (setq arg (+ level arg)))
  6041. (while (> (setq level (org-outline-level)) arg)
  6042. (org-up-heading-safe)))
  6043. (setq beg (point)
  6044. heading (org-get-heading 'no-tags))
  6045. (org-end-of-subtree t t)
  6046. (when (org-at-heading-p) (backward-char 1))
  6047. (setq end (point)))
  6048. (when (and (buffer-live-p org-last-indirect-buffer)
  6049. (not (eq org-indirect-buffer-display 'new-frame))
  6050. (not arg))
  6051. (kill-buffer org-last-indirect-buffer))
  6052. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6053. org-last-indirect-buffer ibuf)
  6054. (cond
  6055. ((or (eq org-indirect-buffer-display 'new-frame)
  6056. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6057. (select-frame (make-frame))
  6058. (delete-other-windows)
  6059. (pop-to-buffer-same-window ibuf)
  6060. (org-set-frame-title heading))
  6061. ((eq org-indirect-buffer-display 'dedicated-frame)
  6062. (raise-frame
  6063. (select-frame (or (and org-indirect-dedicated-frame
  6064. (frame-live-p org-indirect-dedicated-frame)
  6065. org-indirect-dedicated-frame)
  6066. (setq org-indirect-dedicated-frame (make-frame)))))
  6067. (delete-other-windows)
  6068. (pop-to-buffer-same-window ibuf)
  6069. (org-set-frame-title (concat "Indirect: " heading)))
  6070. ((eq org-indirect-buffer-display 'current-window)
  6071. (pop-to-buffer-same-window ibuf))
  6072. ((eq org-indirect-buffer-display 'other-window)
  6073. (pop-to-buffer ibuf))
  6074. (t (error "Invalid value")))
  6075. (narrow-to-region beg end)
  6076. (org-show-all '(headings drawers blocks))
  6077. (goto-char pos)
  6078. (run-hook-with-args 'org-cycle-hook 'all)
  6079. (and (window-live-p cwin) (select-window cwin))))
  6080. (defun org-get-indirect-buffer (&optional buffer heading)
  6081. (setq buffer (or buffer (current-buffer)))
  6082. (let ((n 1) (base (buffer-name buffer)) bname)
  6083. (while (buffer-live-p
  6084. (get-buffer
  6085. (setq bname
  6086. (concat base "-"
  6087. (if heading (concat heading "-" (number-to-string n))
  6088. (number-to-string n))))))
  6089. (setq n (1+ n)))
  6090. (condition-case nil
  6091. (make-indirect-buffer buffer bname 'clone)
  6092. (error (make-indirect-buffer buffer bname)))))
  6093. (defun org-set-frame-title (title)
  6094. "Set the title of the current frame to the string TITLE."
  6095. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6096. ;;;; Structure editing
  6097. ;;; Inserting headlines
  6098. (defun org--blank-before-heading-p (&optional parent)
  6099. "Non-nil when an empty line should precede a new heading here.
  6100. When optional argument PARENT is non-nil, consider parent
  6101. headline instead of current one."
  6102. (pcase (assq 'heading org-blank-before-new-entry)
  6103. (`(heading . auto)
  6104. (save-excursion
  6105. (org-with-limited-levels
  6106. (unless (and (org-before-first-heading-p)
  6107. (not (outline-next-heading)))
  6108. (org-back-to-heading t)
  6109. (when parent (org-up-heading-safe))
  6110. (cond ((not (bobp))
  6111. (org-previous-line-empty-p))
  6112. ((outline-next-heading)
  6113. (org-previous-line-empty-p))
  6114. ;; Ignore trailing spaces on last buffer line.
  6115. ((progn (skip-chars-backward " \t") (bolp))
  6116. (org-previous-line-empty-p))
  6117. (t nil))))))
  6118. (`(heading . ,value) value)
  6119. (_ nil)))
  6120. (defun org-insert-heading (&optional arg invisible-ok top)
  6121. "Insert a new heading or an item with the same depth at point.
  6122. If point is at the beginning of a heading, insert a new heading
  6123. or a new headline above the current one. When at the beginning
  6124. of a regular line of text, turn it into a heading.
  6125. If point is in the middle of a line, split it and create a new
  6126. headline with the text in the current line after point (see
  6127. `org-M-RET-may-split-line' on how to modify this behavior). As
  6128. a special case, on a headline, splitting can only happen on the
  6129. title itself. E.g., this excludes breaking stars or tags.
  6130. With a `\\[universal-argument]' prefix, set \
  6131. `org-insert-heading-respect-content' to
  6132. a non-nil value for the duration of the command. This forces the
  6133. insertion of a heading after the current subtree, independently
  6134. on the location of point.
  6135. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6136. insert the heading at the end of the tree
  6137. above the current heading. For example, if point is within a
  6138. 2nd-level heading, then it will insert a 2nd-level heading at
  6139. the end of the 1st-level parent subtree.
  6140. When INVISIBLE-OK is set, stop at invisible headlines when going
  6141. back. This is important for non-interactive uses of the
  6142. command.
  6143. When optional argument TOP is non-nil, insert a level 1 heading,
  6144. unconditionally."
  6145. (interactive "P")
  6146. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6147. (level (org-current-level))
  6148. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6149. (cond
  6150. ((or org-insert-heading-respect-content
  6151. (member arg '((4) (16)))
  6152. (and (not invisible-ok)
  6153. (invisible-p (max (1- (point)) (point-min)))))
  6154. ;; Position point at the location of insertion. Make sure we
  6155. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6156. (org-with-limited-levels
  6157. (if (not level) (outline-next-heading) ;before first headline
  6158. (org-back-to-heading invisible-ok)
  6159. (when (equal arg '(16)) (org-up-heading-safe))
  6160. (org-end-of-subtree)))
  6161. (unless (bolp) (insert "\n"))
  6162. (unless (and blank? (org-previous-line-empty-p))
  6163. (org-N-empty-lines-before-current (if blank? 1 0)))
  6164. (insert stars " ")
  6165. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6166. ;; is visible.
  6167. (unless invisible-ok
  6168. (pcase (get-char-property-and-overlay (point) 'invisible)
  6169. (`(outline . ,o)
  6170. (move-overlay o (overlay-start o) (line-end-position 0)))
  6171. (_ nil))))
  6172. ;; At a headline...
  6173. ((org-at-heading-p)
  6174. (cond ((bolp)
  6175. (when blank? (save-excursion (insert "\n")))
  6176. (save-excursion (insert stars " \n"))
  6177. (unless (and blank? (org-previous-line-empty-p))
  6178. (org-N-empty-lines-before-current (if blank? 1 0)))
  6179. (end-of-line))
  6180. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6181. (org-match-line org-complex-heading-regexp)
  6182. (org-pos-in-match-range (point) 4))
  6183. ;; Grab the text that should moved to the new headline.
  6184. ;; Preserve tags.
  6185. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6186. (if (looking-at "[ \t]*$") (replace-match "")
  6187. (org-align-tags))
  6188. (end-of-line)
  6189. (when blank? (insert "\n"))
  6190. (insert "\n" stars " ")
  6191. (when (org-string-nw-p split) (insert split))))
  6192. (t
  6193. (end-of-line)
  6194. (when blank? (insert "\n"))
  6195. (insert "\n" stars " "))))
  6196. ;; On regular text, turn line into a headline or split, if
  6197. ;; appropriate.
  6198. ((bolp)
  6199. (insert stars " ")
  6200. (unless (and blank? (org-previous-line-empty-p))
  6201. (org-N-empty-lines-before-current (if blank? 1 0))))
  6202. (t
  6203. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6204. (end-of-line))
  6205. (insert "\n" stars " ")
  6206. (unless (and blank? (org-previous-line-empty-p))
  6207. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6208. (run-hooks 'org-insert-heading-hook))
  6209. (defun org-N-empty-lines-before-current (n)
  6210. "Make the number of empty lines before current exactly N.
  6211. So this will delete or add empty lines."
  6212. (let ((column (current-column)))
  6213. (beginning-of-line)
  6214. (unless (bobp)
  6215. (let ((start (save-excursion
  6216. (skip-chars-backward " \r\t\n")
  6217. (line-end-position))))
  6218. (delete-region start (line-end-position 0))))
  6219. (insert (make-string n ?\n))
  6220. (move-to-column column)))
  6221. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6222. "Return the heading of the current entry, without the stars.
  6223. When NO-TAGS is non-nil, don't include tags.
  6224. When NO-TODO is non-nil, don't include TODO keywords.
  6225. When NO-PRIORITY is non-nil, don't include priority cookie.
  6226. When NO-COMMENT is non-nil, don't include COMMENT string.
  6227. Return nil before first heading."
  6228. (unless (org-before-first-heading-p)
  6229. (save-excursion
  6230. (org-back-to-heading t)
  6231. (let ((case-fold-search nil))
  6232. (looking-at org-complex-heading-regexp)
  6233. (let ((todo (and (not no-todo) (match-string 2)))
  6234. (priority (and (not no-priority) (match-string 3)))
  6235. (headline (pcase (match-string 4)
  6236. (`nil "")
  6237. ((and (guard no-comment) h)
  6238. (replace-regexp-in-string
  6239. (eval-when-compile
  6240. (format "\\`%s[ \t]+" org-comment-string))
  6241. "" h))
  6242. (h h)))
  6243. (tags (and (not no-tags) (match-string 5))))
  6244. (mapconcat #'identity
  6245. (delq nil (list todo priority headline tags))
  6246. " "))))))
  6247. (defun org-heading-components ()
  6248. "Return the components of the current heading.
  6249. This is a list with the following elements:
  6250. - the level as an integer
  6251. - the reduced level, different if `org-odd-levels-only' is set.
  6252. - the TODO keyword, or nil
  6253. - the priority character, like ?A, or nil if no priority is given
  6254. - the headline text itself, or the tags string if no headline text
  6255. - the tags string, or nil."
  6256. (save-excursion
  6257. (org-back-to-heading t)
  6258. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6259. (list (length (match-string 1))
  6260. (org-reduced-level (length (match-string 1)))
  6261. (match-string-no-properties 2)
  6262. (and (match-end 3) (aref (match-string 3) 2))
  6263. (match-string-no-properties 4)
  6264. (match-string-no-properties 5)))))
  6265. (defun org-get-entry ()
  6266. "Get the entry text, after heading, entire subtree."
  6267. (save-excursion
  6268. (org-back-to-heading t)
  6269. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6270. (defun org-edit-headline (&optional heading)
  6271. "Edit the current headline.
  6272. Set it to HEADING when provided."
  6273. (interactive)
  6274. (org-with-wide-buffer
  6275. (org-back-to-heading t)
  6276. (let ((case-fold-search nil))
  6277. (when (looking-at org-complex-heading-regexp)
  6278. (let* ((old (match-string-no-properties 4))
  6279. (new (save-match-data
  6280. (org-trim (or heading (read-string "Edit: " old))))))
  6281. (unless (equal old new)
  6282. (if old (replace-match new t t nil 4)
  6283. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6284. (insert " " new))
  6285. (org-align-tags)
  6286. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6287. (defun org-insert-heading-after-current ()
  6288. "Insert a new heading with same level as current, after current subtree."
  6289. (interactive)
  6290. (org-back-to-heading)
  6291. (org-insert-heading)
  6292. (org-move-subtree-down)
  6293. (end-of-line 1))
  6294. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6295. "Insert heading with `org-insert-heading-respect-content' set to t."
  6296. (interactive)
  6297. (org-insert-heading '(4) invisible-ok))
  6298. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6299. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6300. (interactive)
  6301. (org-insert-todo-heading force-state '(4)))
  6302. (defun org-insert-todo-heading (arg &optional force-heading)
  6303. "Insert a new heading with the same level and TODO state as current heading.
  6304. If the heading has no TODO state, or if the state is DONE, use
  6305. the first state (TODO by default). Also with one prefix arg,
  6306. force first state. With two prefix args, force inserting at the
  6307. end of the parent subtree.
  6308. When called at a plain list item, insert a new item with an
  6309. unchecked check box."
  6310. (interactive "P")
  6311. (when (or force-heading (not (org-insert-item 'checkbox)))
  6312. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6313. force-heading))
  6314. (save-excursion
  6315. (org-forward-heading-same-level -1)
  6316. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6317. (let* ((new-mark-x
  6318. (if (or (equal arg '(4))
  6319. (not (match-beginning 2))
  6320. (member (match-string 2) org-done-keywords))
  6321. (car org-todo-keywords-1)
  6322. (match-string 2)))
  6323. (new-mark
  6324. (or
  6325. (run-hook-with-args-until-success
  6326. 'org-todo-get-default-hook new-mark-x nil)
  6327. new-mark-x)))
  6328. (beginning-of-line 1)
  6329. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6330. (if org-treat-insert-todo-heading-as-state-change
  6331. (org-todo new-mark)
  6332. (insert new-mark " "))))
  6333. (when org-provide-todo-statistics
  6334. (org-update-parent-todo-statistics))))
  6335. (defun org-insert-subheading (arg)
  6336. "Insert a new subheading and demote it.
  6337. Works for outline headings and for plain lists alike."
  6338. (interactive "P")
  6339. (org-insert-heading arg)
  6340. (cond
  6341. ((org-at-heading-p) (org-do-demote))
  6342. ((org-at-item-p) (org-indent-item))))
  6343. (defun org-insert-todo-subheading (arg)
  6344. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6345. Works for outline headings and for plain lists alike."
  6346. (interactive "P")
  6347. (org-insert-todo-heading arg)
  6348. (cond
  6349. ((org-at-heading-p) (org-do-demote))
  6350. ((org-at-item-p) (org-indent-item))))
  6351. ;;; Promotion and Demotion
  6352. (defvar org-after-demote-entry-hook nil
  6353. "Hook run after an entry has been demoted.
  6354. The cursor will be at the beginning of the entry.
  6355. When a subtree is being demoted, the hook will be called for each node.")
  6356. (defvar org-after-promote-entry-hook nil
  6357. "Hook run after an entry has been promoted.
  6358. The cursor will be at the beginning of the entry.
  6359. When a subtree is being promoted, the hook will be called for each node.")
  6360. (defun org-promote-subtree ()
  6361. "Promote the entire subtree.
  6362. See also `org-promote'."
  6363. (interactive)
  6364. (save-excursion
  6365. (org-with-limited-levels (org-map-tree 'org-promote)))
  6366. (org-fix-position-after-promote))
  6367. (defun org-demote-subtree ()
  6368. "Demote the entire subtree.
  6369. See `org-demote' and `org-promote'."
  6370. (interactive)
  6371. (save-excursion
  6372. (org-with-limited-levels (org-map-tree 'org-demote)))
  6373. (org-fix-position-after-promote))
  6374. (defun org-do-promote ()
  6375. "Promote the current heading higher up the tree.
  6376. If the region is active in `transient-mark-mode', promote all
  6377. headings in the region."
  6378. (interactive)
  6379. (save-excursion
  6380. (if (org-region-active-p)
  6381. (org-map-region 'org-promote (region-beginning) (region-end))
  6382. (org-promote)))
  6383. (org-fix-position-after-promote))
  6384. (defun org-do-demote ()
  6385. "Demote the current heading lower down the tree.
  6386. If the region is active in `transient-mark-mode', demote all
  6387. headings in the region."
  6388. (interactive)
  6389. (save-excursion
  6390. (if (org-region-active-p)
  6391. (org-map-region 'org-demote (region-beginning) (region-end))
  6392. (org-demote)))
  6393. (org-fix-position-after-promote))
  6394. (defun org-fix-position-after-promote ()
  6395. "Fix cursor position and indentation after demoting/promoting."
  6396. (let ((pos (point)))
  6397. (when (save-excursion
  6398. (beginning-of-line)
  6399. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6400. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6401. (cond ((eobp) (insert " "))
  6402. ((eolp) (insert " "))
  6403. ((equal (char-after) ?\s) (forward-char 1))))))
  6404. (defun org-current-level ()
  6405. "Return the level of the current entry, or nil if before the first headline.
  6406. The level is the number of stars at the beginning of the
  6407. headline. Use `org-reduced-level' to remove the effect of
  6408. `org-odd-levels'. Unlike to `org-outline-level', this function
  6409. ignores inlinetasks."
  6410. (let ((level (org-with-limited-levels (org-outline-level))))
  6411. (and (> level 0) level)))
  6412. (defun org-get-previous-line-level ()
  6413. "Return the outline depth of the last headline before the current line.
  6414. Returns 0 for the first headline in the buffer, and nil if before the
  6415. first headline."
  6416. (and (org-current-level)
  6417. (or (and (/= (line-beginning-position) (point-min))
  6418. (save-excursion (beginning-of-line 0) (org-current-level)))
  6419. 0)))
  6420. (defun org-reduced-level (l)
  6421. "Compute the effective level of a heading.
  6422. This takes into account the setting of `org-odd-levels-only'."
  6423. (cond
  6424. ((zerop l) 0)
  6425. (org-odd-levels-only (1+ (floor (/ l 2))))
  6426. (t l)))
  6427. (defun org-level-increment ()
  6428. "Return the number of stars that will be added or removed at a
  6429. time to headlines when structure editing, based on the value of
  6430. `org-odd-levels-only'."
  6431. (if org-odd-levels-only 2 1))
  6432. (defun org-get-valid-level (level &optional change)
  6433. "Rectify a level change under the influence of `org-odd-levels-only'.
  6434. LEVEL is a current level, CHANGE is by how much the level should
  6435. be modified. Even if CHANGE is nil, LEVEL may be returned
  6436. modified because even level numbers will become the next higher
  6437. odd number. Returns values greater than 0."
  6438. (if org-odd-levels-only
  6439. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6440. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6441. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6442. (max 1 (+ level (or change 0)))))
  6443. (defun org-promote ()
  6444. "Promote the current heading higher up the tree."
  6445. (org-with-wide-buffer
  6446. (org-back-to-heading t)
  6447. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6448. after-change-functions))
  6449. (level (save-match-data (funcall outline-level)))
  6450. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6451. (diff (abs (- level (length up-head) -1))))
  6452. (cond
  6453. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6454. (replace-match "# " nil t))
  6455. ((= level 1)
  6456. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6457. (t (replace-match up-head nil t)))
  6458. (unless (= level 1)
  6459. (when org-auto-align-tags (org-align-tags))
  6460. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6461. (run-hooks 'org-after-promote-entry-hook))))
  6462. (defun org-demote ()
  6463. "Demote the current heading lower down the tree."
  6464. (org-with-wide-buffer
  6465. (org-back-to-heading t)
  6466. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6467. after-change-functions))
  6468. (level (save-match-data (funcall outline-level)))
  6469. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6470. (diff (abs (- level (length down-head) -1))))
  6471. (replace-match down-head nil t)
  6472. (when org-auto-align-tags (org-align-tags))
  6473. (when org-adapt-indentation (org-fixup-indentation diff))
  6474. (run-hooks 'org-after-demote-entry-hook))))
  6475. (defun org-cycle-level ()
  6476. "Cycle the level of an empty headline through possible states.
  6477. This goes first to child, then to parent, level, then up the hierarchy.
  6478. After top level, it switches back to sibling level."
  6479. (interactive)
  6480. (let ((org-adapt-indentation nil))
  6481. (when (org-point-at-end-of-empty-headline)
  6482. (setq this-command 'org-cycle-level) ; Only needed for caching
  6483. (let ((cur-level (org-current-level))
  6484. (prev-level (org-get-previous-line-level)))
  6485. (cond
  6486. ;; If first headline in file, promote to top-level.
  6487. ((= prev-level 0)
  6488. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6489. do (org-do-promote)))
  6490. ;; If same level as prev, demote one.
  6491. ((= prev-level cur-level)
  6492. (org-do-demote))
  6493. ;; If parent is top-level, promote to top level if not already.
  6494. ((= prev-level 1)
  6495. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6496. do (org-do-promote)))
  6497. ;; If top-level, return to prev-level.
  6498. ((= cur-level 1)
  6499. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6500. do (org-do-demote)))
  6501. ;; If less than prev-level, promote one.
  6502. ((< cur-level prev-level)
  6503. (org-do-promote))
  6504. ;; If deeper than prev-level, promote until higher than
  6505. ;; prev-level.
  6506. ((> cur-level prev-level)
  6507. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6508. do (org-do-promote))))
  6509. t))))
  6510. (defun org-map-tree (fun)
  6511. "Call FUN for every heading underneath the current one."
  6512. (org-back-to-heading t)
  6513. (let ((level (funcall outline-level)))
  6514. (save-excursion
  6515. (funcall fun)
  6516. (while (and (progn
  6517. (outline-next-heading)
  6518. (> (funcall outline-level) level))
  6519. (not (eobp)))
  6520. (funcall fun)))))
  6521. (defun org-map-region (fun beg end)
  6522. "Call FUN for every heading between BEG and END."
  6523. (let ((org-ignore-region t))
  6524. (save-excursion
  6525. (setq end (copy-marker end))
  6526. (goto-char beg)
  6527. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6528. (< (point) end))
  6529. (funcall fun))
  6530. (while (and (progn
  6531. (outline-next-heading)
  6532. (< (point) end))
  6533. (not (eobp)))
  6534. (funcall fun)))))
  6535. (defun org-fixup-indentation (diff)
  6536. "Change the indentation in the current entry by DIFF.
  6537. DIFF is an integer. Indentation is done according to the
  6538. following rules:
  6539. - Planning information and property drawers are always indented
  6540. according to the new level of the headline;
  6541. - Footnote definitions and their contents are ignored;
  6542. - Inlinetasks' boundaries are not shifted;
  6543. - Empty lines are ignored;
  6544. - Other lines' indentation are shifted by DIFF columns, unless
  6545. it would introduce a structural change in the document, in
  6546. which case no shifting is done at all.
  6547. Assume point is at a heading or an inlinetask beginning."
  6548. (org-with-wide-buffer
  6549. (narrow-to-region (line-beginning-position)
  6550. (save-excursion
  6551. (if (org-with-limited-levels (org-at-heading-p))
  6552. (org-with-limited-levels (outline-next-heading))
  6553. (org-inlinetask-goto-end))
  6554. (point)))
  6555. (forward-line)
  6556. ;; Indent properly planning info and property drawer.
  6557. (when (looking-at-p org-planning-line-re)
  6558. (org-indent-line)
  6559. (forward-line))
  6560. (when (looking-at org-property-drawer-re)
  6561. (goto-char (match-end 0))
  6562. (forward-line)
  6563. (org-indent-region (match-beginning 0) (match-end 0)))
  6564. (when (looking-at org-logbook-drawer-re)
  6565. (let ((end-marker (move-marker (make-marker) (match-end 0)))
  6566. (col (+ (current-indentation) diff)))
  6567. (when (wholenump col)
  6568. (while (< (point) end-marker)
  6569. (indent-line-to col)
  6570. (forward-line)))))
  6571. (catch 'no-shift
  6572. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  6573. (throw 'no-shift nil))
  6574. ;; If DIFF is negative, first check if a shift is possible at all
  6575. ;; (e.g., it doesn't break structure). This can only happen if
  6576. ;; some contents are not properly indented.
  6577. (let ((case-fold-search t))
  6578. (when (< diff 0)
  6579. (let ((diff (- diff))
  6580. (forbidden-re (concat org-outline-regexp
  6581. "\\|"
  6582. (substring org-footnote-definition-re 1))))
  6583. (save-excursion
  6584. (while (not (eobp))
  6585. (cond
  6586. ((looking-at-p "[ \t]*$") (forward-line))
  6587. ((and (looking-at-p org-footnote-definition-re)
  6588. (let ((e (org-element-at-point)))
  6589. (and (eq (org-element-type e) 'footnote-definition)
  6590. (goto-char (org-element-property :end e))))))
  6591. ((looking-at-p org-outline-regexp) (forward-line))
  6592. ;; Give up if shifting would move before column 0 or
  6593. ;; if it would introduce a headline or a footnote
  6594. ;; definition.
  6595. (t
  6596. (skip-chars-forward " \t")
  6597. (let ((ind (current-column)))
  6598. (when (or (< ind diff)
  6599. (and (= ind diff) (looking-at-p forbidden-re)))
  6600. (throw 'no-shift nil)))
  6601. ;; Ignore contents of example blocks and source
  6602. ;; blocks if their indentation is meant to be
  6603. ;; preserved. Jump to block's closing line.
  6604. (beginning-of-line)
  6605. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6606. (let ((e (org-element-at-point)))
  6607. (and (memq (org-element-type e)
  6608. '(example-block src-block))
  6609. (or org-src-preserve-indentation
  6610. (org-element-property :preserve-indent e))
  6611. (goto-char (org-element-property :end e))
  6612. (progn (skip-chars-backward " \r\t\n")
  6613. (beginning-of-line)
  6614. t))))
  6615. (forward-line))))))))
  6616. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6617. ;; by DIFF. Also skip contents of source or example blocks
  6618. ;; when indentation is meant to be preserved.
  6619. (while (not (eobp))
  6620. (cond
  6621. ((and (looking-at-p org-footnote-definition-re)
  6622. (let ((e (org-element-at-point)))
  6623. (and (eq (org-element-type e) 'footnote-definition)
  6624. (goto-char (org-element-property :end e))))))
  6625. ((looking-at-p org-outline-regexp) (forward-line))
  6626. ((looking-at-p "[ \t]*$") (forward-line))
  6627. (t
  6628. (indent-line-to (+ (current-indentation) diff))
  6629. (beginning-of-line)
  6630. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6631. (let ((e (org-element-at-point)))
  6632. (and (memq (org-element-type e)
  6633. '(example-block src-block))
  6634. (or org-src-preserve-indentation
  6635. (org-element-property :preserve-indent e))
  6636. (goto-char (org-element-property :end e))
  6637. (progn (skip-chars-backward " \r\t\n")
  6638. (beginning-of-line)
  6639. t))))
  6640. (forward-line)))))))))
  6641. (defun org-convert-to-odd-levels ()
  6642. "Convert an Org file with all levels allowed to one with odd levels.
  6643. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6644. level 5 etc."
  6645. (interactive)
  6646. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6647. (let ((outline-level 'org-outline-level)
  6648. (org-odd-levels-only nil) n)
  6649. (save-excursion
  6650. (goto-char (point-min))
  6651. (while (re-search-forward "^\\*\\*+ " nil t)
  6652. (setq n (- (length (match-string 0)) 2))
  6653. (while (>= (setq n (1- n)) 0)
  6654. (org-demote))
  6655. (end-of-line 1))))))
  6656. (defun org-convert-to-oddeven-levels ()
  6657. "Convert an Org file with only odd levels to one with odd/even levels.
  6658. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6659. file contains a section with an even level, conversion would
  6660. destroy the structure of the file. An error is signaled in this
  6661. case."
  6662. (interactive)
  6663. (goto-char (point-min))
  6664. ;; First check if there are no even levels
  6665. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6666. (org-show-set-visibility 'canonical)
  6667. (error "Not all levels are odd in this file. Conversion not possible"))
  6668. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6669. (let ((outline-regexp org-outline-regexp)
  6670. (outline-level 'org-outline-level)
  6671. (org-odd-levels-only nil) n)
  6672. (save-excursion
  6673. (goto-char (point-min))
  6674. (while (re-search-forward "^\\*\\*+ " nil t)
  6675. (setq n (/ (1- (length (match-string 0))) 2))
  6676. (while (>= (setq n (1- n)) 0)
  6677. (org-promote))
  6678. (end-of-line 1))))))
  6679. (defun org-tr-level (n)
  6680. "Make N odd if required."
  6681. (if org-odd-levels-only (1+ (/ n 2)) n))
  6682. ;;; Vertical tree motion, cutting and pasting of subtrees
  6683. (defun org-move-subtree-up (&optional arg)
  6684. "Move the current subtree up past ARG headlines of the same level."
  6685. (interactive "p")
  6686. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6687. (defun org-move-subtree-down (&optional arg)
  6688. "Move the current subtree down past ARG headlines of the same level."
  6689. (interactive "p")
  6690. (setq arg (prefix-numeric-value arg))
  6691. (org-preserve-local-variables
  6692. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6693. 'org-get-last-sibling))
  6694. (ins-point (make-marker))
  6695. (cnt (abs arg))
  6696. (col (current-column))
  6697. beg end txt folded)
  6698. ;; Select the tree
  6699. (org-back-to-heading)
  6700. (setq beg (point))
  6701. (save-match-data
  6702. (save-excursion (outline-end-of-heading)
  6703. (setq folded (org-invisible-p)))
  6704. (progn (org-end-of-subtree nil t)
  6705. (unless (eobp) (backward-char))))
  6706. (outline-next-heading)
  6707. (setq end (point))
  6708. (goto-char beg)
  6709. ;; Find insertion point, with error handling
  6710. (while (> cnt 0)
  6711. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6712. (goto-char beg)
  6713. (user-error "Cannot move past superior level or buffer limit"))
  6714. (setq cnt (1- cnt)))
  6715. (when (> arg 0)
  6716. ;; Moving forward - still need to move over subtree
  6717. (org-end-of-subtree t t)
  6718. (save-excursion
  6719. (org-back-over-empty-lines)
  6720. (or (bolp) (newline))))
  6721. (move-marker ins-point (point))
  6722. (setq txt (buffer-substring beg end))
  6723. (org-save-markers-in-region beg end)
  6724. (delete-region beg end)
  6725. (org-remove-empty-overlays-at beg)
  6726. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6727. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6728. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6729. (let ((bbb (point)))
  6730. (insert-before-markers txt)
  6731. (org-reinstall-markers-in-region bbb)
  6732. (move-marker ins-point bbb))
  6733. (or (bolp) (insert "\n"))
  6734. (goto-char ins-point)
  6735. (org-skip-whitespace)
  6736. (move-marker ins-point nil)
  6737. (if folded
  6738. (org-flag-subtree t)
  6739. (org-show-entry)
  6740. (org-show-children))
  6741. (org-clean-visibility-after-subtree-move)
  6742. ;; move back to the initial column we were at
  6743. (move-to-column col))))
  6744. (defvar org-subtree-clip ""
  6745. "Clipboard for cut and paste of subtrees.
  6746. This is actually only a copy of the kill, because we use the normal kill
  6747. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6748. (defvar org-subtree-clip-folded nil
  6749. "Was the last copied subtree folded?
  6750. This is used to fold the tree back after pasting.")
  6751. (defun org-cut-subtree (&optional n)
  6752. "Cut the current subtree into the clipboard.
  6753. With prefix arg N, cut this many sequential subtrees.
  6754. This is a short-hand for marking the subtree and then cutting it."
  6755. (interactive "p")
  6756. (org-copy-subtree n 'cut))
  6757. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6758. "Copy the current subtree into the clipboard.
  6759. With prefix arg N, copy this many sequential subtrees.
  6760. This is a short-hand for marking the subtree and then copying it.
  6761. If CUT is non-nil, actually cut the subtree.
  6762. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6763. of some markers in the region, even if CUT is non-nil. This is
  6764. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6765. (interactive "p")
  6766. (org-preserve-local-variables
  6767. (let (beg end folded (beg0 (point)))
  6768. (if (called-interactively-p 'any)
  6769. (org-back-to-heading nil) ; take what looks like a subtree
  6770. (org-back-to-heading t)) ; take what is really there
  6771. (setq beg (point))
  6772. (skip-chars-forward " \t\r\n")
  6773. (save-match-data
  6774. (if nosubtrees
  6775. (outline-next-heading)
  6776. (save-excursion (outline-end-of-heading)
  6777. (setq folded (org-invisible-p)))
  6778. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6779. (org-end-of-subtree t t)))
  6780. ;; Include the end of an inlinetask
  6781. (when (and (featurep 'org-inlinetask)
  6782. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6783. "END[ \t]*$")))
  6784. (end-of-line))
  6785. (setq end (point))
  6786. (goto-char beg0)
  6787. (when (> end beg)
  6788. (setq org-subtree-clip-folded folded)
  6789. (when (or cut force-store-markers)
  6790. (org-save-markers-in-region beg end))
  6791. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6792. (setq org-subtree-clip (current-kill 0))
  6793. (message "%s: Subtree(s) with %d characters"
  6794. (if cut "Cut" "Copied")
  6795. (length org-subtree-clip))))))
  6796. (defun org-paste-subtree (&optional level tree for-yank remove)
  6797. "Paste the clipboard as a subtree, with modification of headline level.
  6798. The entire subtree is promoted or demoted in order to match a new headline
  6799. level.
  6800. If the cursor is at the beginning of a headline, the same level as
  6801. that headline is used to paste the tree.
  6802. If not, the new level is derived from the *visible* headings
  6803. before and after the insertion point, and taken to be the inferior headline
  6804. level of the two. So if the previous visible heading is level 3 and the
  6805. next is level 4 (or vice versa), level 4 will be used for insertion.
  6806. This makes sure that the subtree remains an independent subtree and does
  6807. not swallow low level entries.
  6808. You can also force a different level, either by using a numeric prefix
  6809. argument, or by inserting the heading marker by hand. For example, if the
  6810. cursor is after \"*****\", then the tree will be shifted to level 5.
  6811. If optional TREE is given, use this text instead of the kill ring.
  6812. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6813. move back over whitespace before inserting, and move point to the end of
  6814. the inserted text when done.
  6815. When REMOVE is non-nil, remove the subtree from the clipboard."
  6816. (interactive "P")
  6817. (setq tree (or tree (and kill-ring (current-kill 0))))
  6818. (unless (org-kill-is-subtree-p tree)
  6819. (user-error
  6820. (substitute-command-keys
  6821. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6822. (org-with-limited-levels
  6823. (let* ((visp (not (org-invisible-p)))
  6824. (txt tree)
  6825. (old-level (if (string-match org-outline-regexp-bol txt)
  6826. (- (match-end 0) (match-beginning 0) 1)
  6827. -1))
  6828. (force-level
  6829. (cond
  6830. (level (prefix-numeric-value level))
  6831. ;; When point is after the stars in an otherwise empty
  6832. ;; headline, use the number of stars as the forced level.
  6833. ((and (org-match-line "^\\*+[ \t]*$")
  6834. (not (eq ?* (char-after))))
  6835. (org-outline-level))
  6836. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6837. (previous-level
  6838. (save-excursion
  6839. (org-previous-visible-heading 1)
  6840. (if (org-at-heading-p) (org-outline-level) 1)))
  6841. (next-level
  6842. (save-excursion
  6843. (if (org-at-heading-p) (org-outline-level)
  6844. (org-next-visible-heading 1)
  6845. (if (org-at-heading-p) (org-outline-level) 1))))
  6846. (new-level (or force-level (max previous-level next-level)))
  6847. (shift (if (or (= old-level -1)
  6848. (= new-level -1)
  6849. (= old-level new-level))
  6850. 0
  6851. (- new-level old-level)))
  6852. (delta (if (> shift 0) -1 1))
  6853. (func (if (> shift 0) #'org-demote #'org-promote))
  6854. (org-odd-levels-only nil)
  6855. beg end newend)
  6856. ;; Remove the forced level indicator.
  6857. (when (and force-level (not level))
  6858. (delete-region (line-beginning-position) (point)))
  6859. ;; Paste before the next visible heading or at end of buffer,
  6860. ;; unless point is at the beginning of a headline.
  6861. (unless (and (bolp) (org-at-heading-p))
  6862. (org-next-visible-heading 1)
  6863. (unless (bolp) (insert "\n")))
  6864. (setq beg (point))
  6865. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6866. (insert-before-markers txt)
  6867. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6868. (setq newend (point))
  6869. (org-reinstall-markers-in-region beg)
  6870. (setq end (point))
  6871. (goto-char beg)
  6872. (skip-chars-forward " \t\n\r")
  6873. (setq beg (point))
  6874. (when (and (org-invisible-p) visp)
  6875. (save-excursion (outline-show-heading)))
  6876. ;; Shift if necessary.
  6877. (unless (= shift 0)
  6878. (save-restriction
  6879. (narrow-to-region beg end)
  6880. (while (not (= shift 0))
  6881. (org-map-region func (point-min) (point-max))
  6882. (setq shift (+ delta shift)))
  6883. (goto-char (point-min))
  6884. (setq newend (point-max))))
  6885. (when (or for-yank (called-interactively-p 'interactive))
  6886. (message "Clipboard pasted as level %d subtree" new-level))
  6887. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6888. kill-ring
  6889. (equal org-subtree-clip (current-kill 0))
  6890. org-subtree-clip-folded)
  6891. ;; The tree was folded before it was killed/copied
  6892. (org-flag-subtree t))
  6893. (when for-yank (goto-char newend))
  6894. (when remove (pop kill-ring)))))
  6895. (defun org-kill-is-subtree-p (&optional txt)
  6896. "Check if the current kill is an outline subtree, or a set of trees.
  6897. Returns nil if kill does not start with a headline, or if the first
  6898. headline level is not the largest headline level in the tree.
  6899. So this will actually accept several entries of equal levels as well,
  6900. which is OK for `org-paste-subtree'.
  6901. If optional TXT is given, check this string instead of the current kill."
  6902. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6903. (re (org-get-limited-outline-regexp))
  6904. (^re (concat "^" re))
  6905. (start-level (and kill
  6906. (string-match
  6907. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6908. kill)
  6909. (- (match-end 2) (match-beginning 2) 1)))
  6910. (start (1+ (or (match-beginning 2) -1))))
  6911. (if (not start-level)
  6912. (progn
  6913. nil) ;; does not even start with a heading
  6914. (catch 'exit
  6915. (while (setq start (string-match ^re kill (1+ start)))
  6916. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6917. (throw 'exit nil)))
  6918. t))))
  6919. (defvar org-markers-to-move nil
  6920. "Markers that should be moved with a cut-and-paste operation.
  6921. Those markers are stored together with their positions relative to
  6922. the start of the region.")
  6923. (defun org-save-markers-in-region (beg end)
  6924. "Check markers in region.
  6925. If these markers are between BEG and END, record their position relative
  6926. to BEG, so that after moving the block of text, we can put the markers back
  6927. into place.
  6928. This function gets called just before an entry or tree gets cut from the
  6929. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6930. called immediately, to move the markers with the entries."
  6931. (setq org-markers-to-move nil)
  6932. (when (featurep 'org-clock)
  6933. (org-clock-save-markers-for-cut-and-paste beg end))
  6934. (when (featurep 'org-agenda)
  6935. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6936. (defun org-check-and-save-marker (marker beg end)
  6937. "Check if MARKER is between BEG and END.
  6938. If yes, remember the marker and the distance to BEG."
  6939. (when (and (marker-buffer marker)
  6940. (equal (marker-buffer marker) (current-buffer))
  6941. (>= marker beg) (< marker end))
  6942. (push (cons marker (- marker beg)) org-markers-to-move)))
  6943. (defun org-reinstall-markers-in-region (beg)
  6944. "Move all remembered markers to their position relative to BEG."
  6945. (dolist (x org-markers-to-move)
  6946. (move-marker (car x) (+ beg (cdr x))))
  6947. (setq org-markers-to-move nil))
  6948. (defun org-narrow-to-subtree ()
  6949. "Narrow buffer to the current subtree."
  6950. (interactive)
  6951. (save-excursion
  6952. (save-match-data
  6953. (org-with-limited-levels
  6954. (narrow-to-region
  6955. (progn (org-back-to-heading t) (point))
  6956. (progn (org-end-of-subtree t t)
  6957. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6958. (point)))))))
  6959. (defun org-toggle-narrow-to-subtree ()
  6960. "Narrow to the subtree at point or widen a narrowed buffer."
  6961. (interactive)
  6962. (if (buffer-narrowed-p)
  6963. (progn (widen) (message "Buffer widen"))
  6964. (org-narrow-to-subtree)
  6965. (message "Buffer narrowed to current subtree")))
  6966. (defun org-narrow-to-block ()
  6967. "Narrow buffer to the current block."
  6968. (interactive)
  6969. (let* ((case-fold-search t)
  6970. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6971. "^[ \t]*#\\+end_.*")))
  6972. (if blockp
  6973. (narrow-to-region (car blockp) (cdr blockp))
  6974. (user-error "Not in a block"))))
  6975. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6976. "Clone the task (subtree) at point N times.
  6977. The clones will be inserted as siblings.
  6978. In interactive use, the user will be prompted for the number of
  6979. clones to be produced. If the entry has a timestamp, the user
  6980. will also be prompted for a time shift, which may be a repeater
  6981. as used in time stamps, for example `+3d'. To disable this,
  6982. you can call the function with a universal prefix argument.
  6983. When a valid repeater is given and the entry contains any time
  6984. stamps, the clones will become a sequence in time, with time
  6985. stamps in the subtree shifted for each clone produced. If SHIFT
  6986. is nil or the empty string, time stamps will be left alone. The
  6987. ID property of the original subtree is removed.
  6988. In each clone, all the CLOCK entries will be removed. This
  6989. prevents Org from considering that the clocked times overlap.
  6990. If the original subtree did contain time stamps with a repeater,
  6991. the following will happen:
  6992. - the repeater will be removed in each clone
  6993. - an additional clone will be produced, with the current, unshifted
  6994. date(s) in the entry.
  6995. - the original entry will be placed *after* all the clones, with
  6996. repeater intact.
  6997. - the start days in the repeater in the original entry will be shifted
  6998. to past the last clone.
  6999. In this way you can spell out a number of instances of a repeating task,
  7000. and still retain the repeater to cover future instances of the task.
  7001. As described above, N+1 clones are produced when the original
  7002. subtree has a repeater. Setting N to 0, then, can be used to
  7003. remove the repeater from a subtree and create a shifted clone
  7004. with the original repeater."
  7005. (interactive "nNumber of clones to produce: ")
  7006. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7007. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7008. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7009. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7010. (shift
  7011. (or shift
  7012. (if (and (not (equal current-prefix-arg '(4)))
  7013. (save-excursion
  7014. (goto-char beg)
  7015. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7016. (read-from-minibuffer
  7017. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7018. ""))) ;No time shift
  7019. (doshift
  7020. (and (org-string-nw-p shift)
  7021. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7022. shift)
  7023. (user-error "Invalid shift specification %s" shift)))))
  7024. (goto-char end-of-tree)
  7025. (unless (bolp) (insert "\n"))
  7026. (let* ((end (point))
  7027. (template (buffer-substring beg end))
  7028. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7029. (shift-what (pcase (and doshift (match-string 2 shift))
  7030. (`nil nil)
  7031. ("d" 'day)
  7032. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7033. ("m" 'month)
  7034. ("y" 'year)
  7035. (_ (error "Unsupported time unit"))))
  7036. (nmin 1)
  7037. (nmax n)
  7038. (n-no-remove -1)
  7039. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  7040. (idprop (org-entry-get beg "ID")))
  7041. (when (and doshift
  7042. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7043. template))
  7044. (delete-region beg end)
  7045. (setq end beg)
  7046. (setq nmin 0)
  7047. (setq nmax (1+ nmax))
  7048. (setq n-no-remove nmax))
  7049. (goto-char end)
  7050. (cl-loop for n from nmin to nmax do
  7051. (insert
  7052. ;; Prepare clone.
  7053. (with-temp-buffer
  7054. (insert template)
  7055. (org-mode)
  7056. (goto-char (point-min))
  7057. (org-show-subtree)
  7058. (and idprop (if org-clone-delete-id
  7059. (org-entry-delete nil "ID")
  7060. (org-id-get-create t)))
  7061. (unless (= n 0)
  7062. (while (re-search-forward org-clock-line-re nil t)
  7063. (delete-region (line-beginning-position)
  7064. (line-beginning-position 2)))
  7065. (goto-char (point-min))
  7066. (while (re-search-forward org-drawer-regexp nil t)
  7067. (org-remove-empty-drawer-at (point))))
  7068. (goto-char (point-min))
  7069. (when doshift
  7070. (while (re-search-forward org-ts-regexp-both nil t)
  7071. (org-timestamp-change (* n shift-n) shift-what))
  7072. (unless (= n n-no-remove)
  7073. (goto-char (point-min))
  7074. (while (re-search-forward org-ts-regexp nil t)
  7075. (save-excursion
  7076. (goto-char (match-beginning 0))
  7077. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7078. (delete-region (match-beginning 1) (match-end 1)))))))
  7079. (buffer-string)))))
  7080. (goto-char beg)))
  7081. ;;; Outline path
  7082. (defvar org-outline-path-cache nil
  7083. "Alist between buffer positions and outline paths.
  7084. It value is an alist (POSITION . PATH) where POSITION is the
  7085. buffer position at the beginning of an entry and PATH is a list
  7086. of strings describing the outline path for that entry, in reverse
  7087. order.")
  7088. (defun org--get-outline-path-1 (&optional use-cache)
  7089. "Return outline path to current headline.
  7090. Outline path is a list of strings, in reverse order. When
  7091. optional argument USE-CACHE is non-nil, make use of a cache. See
  7092. `org-get-outline-path' for details.
  7093. Assume buffer is widened and point is on a headline."
  7094. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  7095. (let ((p (point))
  7096. (heading (let ((case-fold-search nil))
  7097. (looking-at org-complex-heading-regexp)
  7098. (if (not (match-end 4)) ""
  7099. ;; Remove statistics cookies.
  7100. (org-trim
  7101. (org-link-display-format
  7102. (replace-regexp-in-string
  7103. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  7104. (match-string-no-properties 4))))))))
  7105. (if (org-up-heading-safe)
  7106. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  7107. (when use-cache
  7108. (push (cons p path) org-outline-path-cache))
  7109. path)
  7110. ;; This is a new root node. Since we assume we are moving
  7111. ;; forward, we can drop previous cache so as to limit number
  7112. ;; of associations there.
  7113. (let ((path (list heading)))
  7114. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  7115. path)))))
  7116. (defun org-get-outline-path (&optional with-self use-cache)
  7117. "Return the outline path to the current entry.
  7118. An outline path is a list of ancestors for current headline, as
  7119. a list of strings. Statistics cookies are removed and links are
  7120. replaced with their description, if any, or their path otherwise.
  7121. When optional argument WITH-SELF is non-nil, the path also
  7122. includes the current headline.
  7123. When optional argument USE-CACHE is non-nil, cache outline paths
  7124. between calls to this function so as to avoid backtracking. This
  7125. argument is useful when planning to find more than one outline
  7126. path in the same document. In that case, there are two
  7127. conditions to satisfy:
  7128. - `org-outline-path-cache' is set to nil before starting the
  7129. process;
  7130. - outline paths are computed by increasing buffer positions."
  7131. (org-with-wide-buffer
  7132. (and (or (and with-self (org-back-to-heading t))
  7133. (org-up-heading-safe))
  7134. (reverse (org--get-outline-path-1 use-cache)))))
  7135. (defun org-format-outline-path (path &optional width prefix separator)
  7136. "Format the outline path PATH for display.
  7137. WIDTH is the maximum number of characters that is available.
  7138. PREFIX is a prefix to be included in the returned string,
  7139. such as the file name.
  7140. SEPARATOR is inserted between the different parts of the path,
  7141. the default is \"/\"."
  7142. (setq width (or width 79))
  7143. (setq path (delq nil path))
  7144. (unless (> width 0)
  7145. (user-error "Argument `width' must be positive"))
  7146. (setq separator (or separator "/"))
  7147. (let* ((org-odd-levels-only nil)
  7148. (fpath (concat
  7149. prefix (and prefix path separator)
  7150. (mapconcat
  7151. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  7152. (cl-loop for head in path
  7153. for n from 0
  7154. collect (org-add-props
  7155. head nil 'face
  7156. (nth (% n org-n-level-faces) org-level-faces)))
  7157. separator))))
  7158. (when (> (length fpath) width)
  7159. (if (< width 7)
  7160. ;; It's unlikely that `width' will be this small, but don't
  7161. ;; waste characters by adding ".." if it is.
  7162. (setq fpath (substring fpath 0 width))
  7163. (setf (substring fpath (- width 2)) "..")))
  7164. fpath))
  7165. (defun org-display-outline-path (&optional file current separator just-return-string)
  7166. "Display the current outline path in the echo area.
  7167. If FILE is non-nil, prepend the output with the file name.
  7168. If CURRENT is non-nil, append the current heading to the output.
  7169. SEPARATOR is passed through to `org-format-outline-path'. It separates
  7170. the different parts of the path and defaults to \"/\".
  7171. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  7172. (interactive "P")
  7173. (let* (case-fold-search
  7174. (bfn (buffer-file-name (buffer-base-buffer)))
  7175. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  7176. res)
  7177. (when current (setq path (append path
  7178. (save-excursion
  7179. (org-back-to-heading t)
  7180. (when (looking-at org-complex-heading-regexp)
  7181. (list (match-string 4)))))))
  7182. (setq res
  7183. (org-format-outline-path
  7184. path
  7185. (1- (frame-width))
  7186. (and file bfn (concat (file-name-nondirectory bfn) separator))
  7187. separator))
  7188. (add-face-text-property 0 (length res)
  7189. `(:height ,(face-attribute 'default :height))
  7190. nil res)
  7191. (if just-return-string
  7192. res
  7193. (org-unlogged-message "%s" res))))
  7194. ;;; Outline Sorting
  7195. (defun org-sort (&optional with-case)
  7196. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7197. Optional argument WITH-CASE means sort case-sensitively."
  7198. (interactive "P")
  7199. (org-call-with-arg
  7200. (cond ((org-at-table-p) #'org-table-sort-lines)
  7201. ((org-at-item-p) #'org-sort-list)
  7202. (t #'org-sort-entries))
  7203. with-case))
  7204. (defun org-sort-remove-invisible (s)
  7205. "Remove invisible part of links and emphasis markers from string S."
  7206. (remove-text-properties 0 (length s) org-rm-props s)
  7207. (replace-regexp-in-string
  7208. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7209. (replace-regexp-in-string
  7210. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7211. (org-link-display-format s)
  7212. t t) t t))
  7213. (defvar org-after-sorting-entries-or-items-hook nil
  7214. "Hook that is run after a bunch of entries or items have been sorted.
  7215. When children are sorted, the cursor is in the parent line when this
  7216. hook gets called. When a region or a plain list is sorted, the cursor
  7217. will be in the first entry of the sorted region/list.")
  7218. (defun org-sort-entries
  7219. (&optional with-case sorting-type getkey-func compare-func property
  7220. interactive?)
  7221. "Sort entries on a certain level of an outline tree.
  7222. If there is an active region, the entries in the region are sorted.
  7223. Else, if the cursor is before the first entry, sort the top-level items.
  7224. Else, the children of the entry at point are sorted.
  7225. Sorting can be alphabetically, numerically, by date/time as given by
  7226. a time stamp, by a property, by priority order, or by a custom function.
  7227. The command prompts for the sorting type unless it has been given to the
  7228. function through the SORTING-TYPE argument, which needs to be a character,
  7229. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7230. the precise meaning of each character:
  7231. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7232. c By creation time, which is assumed to be the first inactive time stamp
  7233. at the beginning of a line.
  7234. d By deadline date/time.
  7235. k By clocking time.
  7236. n Numerically, by converting the beginning of the entry/item to a number.
  7237. o By order of TODO keywords.
  7238. p By priority according to the cookie.
  7239. r By the value of a property.
  7240. s By scheduled date/time.
  7241. t By date/time, either the first active time stamp in the entry, or, if
  7242. none exist, by the first inactive one.
  7243. Capital letters will reverse the sort order.
  7244. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7245. called with point at the beginning of the record. It must return a
  7246. value that is compatible with COMPARE-FUNC, the function used to
  7247. compare entries.
  7248. Comparing entries ignores case by default. However, with an optional argument
  7249. WITH-CASE, the sorting considers case as well.
  7250. Sorting is done against the visible part of the headlines, it ignores hidden
  7251. links.
  7252. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7253. A non-nil value for INTERACTIVE? is used to signal that this
  7254. function is being called interactively."
  7255. (interactive (list current-prefix-arg nil nil nil nil t))
  7256. (let ((case-func (if with-case 'identity 'downcase))
  7257. start beg end stars re re2
  7258. txt what tmp)
  7259. ;; Find beginning and end of region to sort
  7260. (cond
  7261. ((org-region-active-p)
  7262. ;; we will sort the region
  7263. (setq end (region-end)
  7264. what "region")
  7265. (goto-char (region-beginning))
  7266. (unless (org-at-heading-p) (outline-next-heading))
  7267. (setq start (point)))
  7268. ((or (org-at-heading-p)
  7269. (ignore-errors (progn (org-back-to-heading) t)))
  7270. ;; we will sort the children of the current headline
  7271. (org-back-to-heading)
  7272. (setq start (point)
  7273. end (progn (org-end-of-subtree t t)
  7274. (or (bolp) (insert "\n"))
  7275. (when (>= (org-back-over-empty-lines) 1)
  7276. (forward-line 1))
  7277. (point))
  7278. what "children")
  7279. (goto-char start)
  7280. (outline-show-subtree)
  7281. (outline-next-heading))
  7282. (t
  7283. ;; we will sort the top-level entries in this file
  7284. (goto-char (point-min))
  7285. (or (org-at-heading-p) (outline-next-heading))
  7286. (setq start (point))
  7287. (goto-char (point-max))
  7288. (beginning-of-line 1)
  7289. (when (looking-at ".*?\\S-")
  7290. ;; File ends in a non-white line
  7291. (end-of-line 1)
  7292. (insert "\n"))
  7293. (setq end (point-max))
  7294. (setq what "top-level")
  7295. (goto-char start)
  7296. (org-show-all '(headings drawers blocks))))
  7297. (setq beg (point))
  7298. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7299. (looking-at "\\(\\*+\\)")
  7300. (setq stars (match-string 1)
  7301. re (concat "^" (regexp-quote stars) " +")
  7302. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7303. txt (buffer-substring beg end))
  7304. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7305. (when (and (not (equal stars "*")) (string-match re2 txt))
  7306. (user-error "Region to sort contains a level above the first entry"))
  7307. (unless sorting-type
  7308. (message
  7309. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7310. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7311. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7312. what)
  7313. (setq sorting-type (read-char-exclusive)))
  7314. (unless getkey-func
  7315. (and (= (downcase sorting-type) ?f)
  7316. (setq getkey-func
  7317. (or (and interactive?
  7318. (org-read-function
  7319. "Function for extracting keys: "))
  7320. (error "Missing key extractor")))))
  7321. (and (= (downcase sorting-type) ?r)
  7322. (not property)
  7323. (setq property
  7324. (completing-read "Property: "
  7325. (mapcar #'list (org-buffer-property-keys t))
  7326. nil t)))
  7327. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7328. (message "Sorting entries...")
  7329. (save-restriction
  7330. (narrow-to-region start end)
  7331. (let ((restore-clock?
  7332. ;; The clock marker is lost when using `sort-subr'; mark
  7333. ;; the clock with temporary `:org-clock-marker-backup'
  7334. ;; text property.
  7335. (when (and (eq (org-clock-is-active) (current-buffer))
  7336. (<= start (marker-position org-clock-marker))
  7337. (>= end (marker-position org-clock-marker)))
  7338. (with-silent-modifications
  7339. (put-text-property (1- org-clock-marker) org-clock-marker
  7340. :org-clock-marker-backup t))
  7341. t))
  7342. (dcst (downcase sorting-type))
  7343. (case-fold-search nil)
  7344. (now (current-time)))
  7345. (org-preserve-local-variables
  7346. (sort-subr
  7347. (/= dcst sorting-type)
  7348. ;; This function moves to the beginning character of the
  7349. ;; "record" to be sorted.
  7350. (lambda nil
  7351. (if (re-search-forward re nil t)
  7352. (goto-char (match-beginning 0))
  7353. (goto-char (point-max))))
  7354. ;; This function moves to the last character of the "record" being
  7355. ;; sorted.
  7356. (lambda nil
  7357. (save-match-data
  7358. (condition-case nil
  7359. (outline-forward-same-level 1)
  7360. (error
  7361. (goto-char (point-max))))))
  7362. ;; This function returns the value that gets sorted against.
  7363. (lambda ()
  7364. (cond
  7365. ((= dcst ?n)
  7366. (string-to-number
  7367. (org-sort-remove-invisible (org-get-heading t t t t))))
  7368. ((= dcst ?a)
  7369. (funcall case-func
  7370. (org-sort-remove-invisible (org-get-heading t t t t))))
  7371. ((= dcst ?k)
  7372. (or (get-text-property (point) :org-clock-minutes) 0))
  7373. ((= dcst ?t)
  7374. (let ((end (save-excursion (outline-next-heading) (point))))
  7375. (if (or (re-search-forward org-ts-regexp end t)
  7376. (re-search-forward org-ts-regexp-both end t))
  7377. (org-time-string-to-seconds (match-string 0))
  7378. (float-time now))))
  7379. ((= dcst ?c)
  7380. (let ((end (save-excursion (outline-next-heading) (point))))
  7381. (if (re-search-forward
  7382. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7383. end t)
  7384. (org-time-string-to-seconds (match-string 0))
  7385. (float-time now))))
  7386. ((= dcst ?s)
  7387. (let ((end (save-excursion (outline-next-heading) (point))))
  7388. (if (re-search-forward org-scheduled-time-regexp end t)
  7389. (org-time-string-to-seconds (match-string 1))
  7390. (float-time now))))
  7391. ((= dcst ?d)
  7392. (let ((end (save-excursion (outline-next-heading) (point))))
  7393. (if (re-search-forward org-deadline-time-regexp end t)
  7394. (org-time-string-to-seconds (match-string 1))
  7395. (float-time now))))
  7396. ((= dcst ?p)
  7397. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7398. (string-to-char (match-string 2))
  7399. org-priority-default))
  7400. ((= dcst ?r)
  7401. (or (org-entry-get nil property) ""))
  7402. ((= dcst ?o)
  7403. (when (looking-at org-complex-heading-regexp)
  7404. (let* ((m (match-string 2))
  7405. (s (if (member m org-done-keywords) '- '+)))
  7406. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7407. ((= dcst ?f)
  7408. (if getkey-func
  7409. (progn
  7410. (setq tmp (funcall getkey-func))
  7411. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7412. tmp)
  7413. (error "Invalid key function `%s'" getkey-func)))
  7414. (t (error "Invalid sorting type `%c'" sorting-type))))
  7415. nil
  7416. (cond
  7417. ((= dcst ?a) 'org-string-collate-lessp)
  7418. ((= dcst ?f)
  7419. (or compare-func
  7420. (and interactive?
  7421. (org-read-function
  7422. (concat "Function for comparing keys "
  7423. "(empty for default `sort-subr' predicate): ")
  7424. 'allow-empty))))
  7425. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7426. (org-cycle-hide-drawers 'all)
  7427. (when restore-clock?
  7428. (move-marker org-clock-marker
  7429. (1+ (next-single-property-change
  7430. start :org-clock-marker-backup)))
  7431. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7432. '(:org-clock-marker-backup t)))))
  7433. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7434. (message "Sorting entries...done")))
  7435. (defun org-contextualize-keys (alist contexts)
  7436. "Return valid elements in ALIST depending on CONTEXTS.
  7437. `org-agenda-custom-commands' or `org-capture-templates' are the
  7438. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7439. or `org-capture-templates-contexts' are the associated contexts
  7440. definitions."
  7441. (let ((contexts
  7442. ;; normalize contexts
  7443. (mapcar
  7444. (lambda(c) (cond ((listp (cadr c))
  7445. (list (car c) (car c) (nth 1 c)))
  7446. ((string= "" (cadr c))
  7447. (list (car c) (car c) (nth 2 c)))
  7448. (t c)))
  7449. contexts))
  7450. (a alist) r s)
  7451. ;; loop over all commands or templates
  7452. (dolist (c a)
  7453. (let (vrules repl)
  7454. (cond
  7455. ((not (assoc (car c) contexts))
  7456. (push c r))
  7457. ((and (assoc (car c) contexts)
  7458. (setq vrules (org-contextualize-validate-key
  7459. (car c) contexts)))
  7460. (mapc (lambda (vr)
  7461. (unless (equal (car vr) (cadr vr))
  7462. (setq repl vr)))
  7463. vrules)
  7464. (if (not repl) (push c r)
  7465. (push (cadr repl) s)
  7466. (push
  7467. (cons (car c)
  7468. (cdr (or (assoc (cadr repl) alist)
  7469. (error "Undefined key `%s' as contextual replacement for `%s'"
  7470. (cadr repl) (car c)))))
  7471. r))))))
  7472. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7473. (delq
  7474. nil
  7475. (delete-dups
  7476. (mapcar (lambda (x)
  7477. (let ((tpl (car x)))
  7478. (unless (delq
  7479. nil
  7480. (mapcar (lambda (y)
  7481. (equal y tpl))
  7482. s))
  7483. x)))
  7484. (reverse r))))))
  7485. (defun org-contextualize-validate-key (key contexts)
  7486. "Check CONTEXTS for agenda or capture KEY."
  7487. (let (res)
  7488. (dolist (r contexts)
  7489. (dolist (rr (car (last r)))
  7490. (when
  7491. (and (equal key (car r))
  7492. (if (functionp rr) (funcall rr)
  7493. (or (and (eq (car rr) 'in-file)
  7494. (buffer-file-name)
  7495. (string-match (cdr rr) (buffer-file-name)))
  7496. (and (eq (car rr) 'in-mode)
  7497. (string-match (cdr rr) (symbol-name major-mode)))
  7498. (and (eq (car rr) 'in-buffer)
  7499. (string-match (cdr rr) (buffer-name)))
  7500. (when (and (eq (car rr) 'not-in-file)
  7501. (buffer-file-name))
  7502. (not (string-match (cdr rr) (buffer-file-name))))
  7503. (when (eq (car rr) 'not-in-mode)
  7504. (not (string-match (cdr rr) (symbol-name major-mode))))
  7505. (when (eq (car rr) 'not-in-buffer)
  7506. (not (string-match (cdr rr) (buffer-name)))))))
  7507. (push r res))))
  7508. (delete-dups (delq nil res))))
  7509. ;; Defined to provide a value for defcustom, since there is no
  7510. ;; string-collate-greaterp in Emacs.
  7511. (defun org-string-collate-greaterp (s1 s2)
  7512. "Return non-nil if S1 is greater than S2 in collation order."
  7513. (not (org-string-collate-lessp s1 s2)))
  7514. ;;;###autoload
  7515. (defun org-run-like-in-org-mode (cmd)
  7516. "Run a command, pretending that the current buffer is in Org mode.
  7517. This will temporarily bind local variables that are typically bound in
  7518. Org mode to the values they have in Org mode, and then interactively
  7519. call CMD."
  7520. (org-load-modules-maybe)
  7521. (let (binds)
  7522. (dolist (var (org-get-local-variables))
  7523. (when (or (not (boundp (car var)))
  7524. (eq (symbol-value (car var))
  7525. (default-value (car var))))
  7526. (push (list (car var) `(quote ,(cadr var))) binds)))
  7527. (eval `(let ,binds
  7528. (call-interactively (quote ,cmd))))))
  7529. (defun org-get-category (&optional pos force-refresh)
  7530. "Get the category applying to position POS."
  7531. (save-match-data
  7532. (when force-refresh (org-refresh-category-properties))
  7533. (let ((pos (or pos (point))))
  7534. (or (get-text-property pos 'org-category)
  7535. (progn (org-refresh-category-properties)
  7536. (get-text-property pos 'org-category))))))
  7537. ;;; Refresh properties
  7538. (defun org-refresh-properties (dprop tprop)
  7539. "Refresh buffer text properties.
  7540. DPROP is the drawer property and TPROP is either the
  7541. corresponding text property to set, or an alist with each element
  7542. being a text property (as a symbol) and a function to apply to
  7543. the value of the drawer property."
  7544. (let* ((case-fold-search t)
  7545. (inhibit-read-only t)
  7546. (inherit? (org-property-inherit-p dprop))
  7547. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7548. (global-or-keyword (and inherit?
  7549. (org--property-global-or-keyword-value dprop nil))))
  7550. (with-silent-modifications
  7551. (org-with-point-at 1
  7552. ;; Set global and keyword based values to the whole buffer.
  7553. (when global-or-keyword
  7554. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7555. ;; Set values based on property-drawers throughout the document.
  7556. (while (re-search-forward property-re nil t)
  7557. (when (org-at-property-p)
  7558. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7559. (outline-next-heading))))))
  7560. (defun org-refresh-property (tprop p &optional inherit)
  7561. "Refresh the buffer text property TPROP from the drawer property P.
  7562. The refresh happens only for the current entry, or the whole
  7563. sub-tree if optional argument INHERIT is non-nil.
  7564. If point is before first headline, the function applies to the
  7565. part before the first headline. In that particular case, when
  7566. optional argument INHERIT is non-nil, it refreshes properties for
  7567. the whole buffer."
  7568. (save-excursion
  7569. (org-back-to-heading-or-point-min t)
  7570. (let ((start (point))
  7571. (end (save-excursion
  7572. (cond ((and inherit (org-before-first-heading-p))
  7573. (point-max))
  7574. (inherit
  7575. (org-end-of-subtree t t))
  7576. ((outline-next-heading))
  7577. ((point-max))))))
  7578. (if (symbolp tprop)
  7579. ;; TPROP is a text property symbol.
  7580. (put-text-property start end tprop p)
  7581. ;; TPROP is an alist with (property . function) elements.
  7582. (pcase-dolist (`(,prop . ,f) tprop)
  7583. (put-text-property start end prop (funcall f p)))))))
  7584. (defun org-refresh-category-properties ()
  7585. "Refresh category text properties in the buffer."
  7586. (let ((case-fold-search t)
  7587. (inhibit-read-only t)
  7588. (default-category
  7589. (cond ((null org-category)
  7590. (if buffer-file-name
  7591. (file-name-sans-extension
  7592. (file-name-nondirectory buffer-file-name))
  7593. "???"))
  7594. ((symbolp org-category) (symbol-name org-category))
  7595. (t org-category))))
  7596. (with-silent-modifications
  7597. (org-with-wide-buffer
  7598. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7599. ;; keyword. If none is found, fall-back to `org-category' or
  7600. ;; buffer file name, or set it by the document property drawer.
  7601. (put-text-property
  7602. (point-min) (point-max)
  7603. 'org-category
  7604. (catch 'buffer-category
  7605. (goto-char (point-max))
  7606. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7607. (let ((element (org-element-at-point)))
  7608. (when (eq (org-element-type element) 'keyword)
  7609. (throw 'buffer-category
  7610. (org-element-property :value element)))))
  7611. default-category))
  7612. ;; Set categories from the document property drawer or
  7613. ;; property drawers in the outline. If category is found in
  7614. ;; the property drawer for the whole buffer that value
  7615. ;; overrides the keyword-based value set above.
  7616. (goto-char (point-min))
  7617. (let ((regexp (org-re-property "CATEGORY")))
  7618. (while (re-search-forward regexp nil t)
  7619. (let ((value (match-string-no-properties 3)))
  7620. (when (org-at-property-p)
  7621. (put-text-property
  7622. (save-excursion (org-back-to-heading-or-point-min t))
  7623. (save-excursion (if (org-before-first-heading-p)
  7624. (point-max)
  7625. (org-end-of-subtree t t)))
  7626. 'org-category
  7627. value)))))))))
  7628. (defun org-refresh-stats-properties ()
  7629. "Refresh stats text properties in the buffer."
  7630. (with-silent-modifications
  7631. (org-with-point-at 1
  7632. (let ((regexp (concat org-outline-regexp-bol
  7633. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7634. (while (re-search-forward regexp nil t)
  7635. (let* ((numerator (string-to-number (match-string 1)))
  7636. (denominator (and (match-end 2)
  7637. (string-to-number (match-string 2))))
  7638. (stats (cond ((not denominator) numerator) ;percent
  7639. ((= denominator 0) 0)
  7640. (t (/ (* numerator 100) denominator)))))
  7641. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7642. 'org-stats stats)))))))
  7643. (defun org-refresh-effort-properties ()
  7644. "Refresh effort properties."
  7645. (org-refresh-properties
  7646. org-effort-property
  7647. '((effort . identity)
  7648. (effort-minutes . org-duration-to-minutes))))
  7649. (defun org-find-file-at-mouse (ev)
  7650. "Open file link or URL at mouse."
  7651. (interactive "e")
  7652. (mouse-set-point ev)
  7653. (org-open-at-point 'in-emacs))
  7654. (defun org-open-at-mouse (ev)
  7655. "Open file link or URL at mouse.
  7656. See the docstring of `org-open-file' for details."
  7657. (interactive "e")
  7658. (mouse-set-point ev)
  7659. (when (eq major-mode 'org-agenda-mode)
  7660. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7661. (org-open-at-point))
  7662. (defvar org-window-config-before-follow-link nil
  7663. "The window configuration before following a link.
  7664. This is saved in case the need arises to restore it.")
  7665. (defun org--file-default-apps ()
  7666. "Return the default applications for this operating system."
  7667. (pcase system-type
  7668. (`darwin org-file-apps-macos)
  7669. (`windows-nt org-file-apps-windowsnt)
  7670. (_ org-file-apps-gnu)))
  7671. (defun org--file-apps-entry-dlink-p (entry)
  7672. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7673. It assumes that is the case when the entry uses a regular
  7674. expression which has at least one grouping construct and the
  7675. action is either a Lisp form or a command string containing
  7676. \"%1\", i.e., using at least one subexpression match as
  7677. a parameter."
  7678. (pcase entry
  7679. (`(,selector . ,action)
  7680. (and (stringp selector)
  7681. (> (regexp-opt-depth selector) 0)
  7682. (or (and (stringp action)
  7683. (string-match "%[0-9]" action))
  7684. (consp action))))
  7685. (_ nil)))
  7686. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7687. "Convert extensions to regular expressions in the cars of LIST.
  7688. Also, weed out any non-string entries, because the return value
  7689. is used only for regexp matching.
  7690. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7691. point to the symbol `emacs', indicating that the file should be
  7692. opened in Emacs."
  7693. (append
  7694. (delq nil
  7695. (mapcar (lambda (x)
  7696. (unless (not (stringp (car x)))
  7697. (if (string-match "\\W" (car x))
  7698. x
  7699. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7700. list))
  7701. (when add-auto-mode
  7702. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7703. ;;;###autoload
  7704. (defun org-open-file (path &optional in-emacs line search)
  7705. "Open the file at PATH.
  7706. First, this expands any special file name abbreviations. Then the
  7707. configuration variable `org-file-apps' is checked if it contains an
  7708. entry for this file type, and if yes, the corresponding command is launched.
  7709. If no application is found, Emacs simply visits the file.
  7710. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7711. With a double \\[universal-argument] \\[universal-argument] \
  7712. prefix arg, Org tries to avoid opening in Emacs
  7713. and to use an external application to visit the file.
  7714. Optional LINE specifies a line to go to, optional SEARCH a string
  7715. to search for. If LINE or SEARCH is given, the file will be
  7716. opened in Emacs, unless an entry from `org-file-apps' that makes
  7717. use of groups in a regexp matches.
  7718. If you want to change the way frames are used when following a
  7719. link, please customize `org-link-frame-setup'.
  7720. If the file does not exist, throw an error."
  7721. (let* ((file (if (equal path "") buffer-file-name
  7722. (substitute-in-file-name (expand-file-name path))))
  7723. (file-apps (append org-file-apps (org--file-default-apps)))
  7724. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7725. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7726. file-apps))
  7727. (remp (and (assq 'remote apps) (file-remote-p file)))
  7728. (dirp (unless remp (file-directory-p file)))
  7729. (file (if (and dirp org-open-directory-means-index-dot-org)
  7730. (concat (file-name-as-directory file) "index.org")
  7731. file))
  7732. (a-m-a-p (assq 'auto-mode apps))
  7733. (dfile (downcase file))
  7734. ;; Reconstruct the original link from the PATH, LINE and
  7735. ;; SEARCH args.
  7736. (link (cond (line (concat file "::" (number-to-string line)))
  7737. (search (concat file "::" search))
  7738. (t file)))
  7739. (dlink (downcase link))
  7740. (ext
  7741. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7742. (match-string 1 dfile)))
  7743. (save-position-maybe
  7744. (let ((old-buffer (current-buffer))
  7745. (old-pos (point))
  7746. (old-mode major-mode))
  7747. (lambda ()
  7748. (and (derived-mode-p 'org-mode)
  7749. (eq old-mode 'org-mode)
  7750. (or (not (eq old-buffer (current-buffer)))
  7751. (not (eq old-pos (point))))
  7752. (org-mark-ring-push old-pos old-buffer)))))
  7753. cmd link-match-data)
  7754. (cond
  7755. ((member in-emacs '((16) system))
  7756. (setq cmd (cdr (assq 'system apps))))
  7757. (in-emacs (setq cmd 'emacs))
  7758. (t
  7759. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7760. (and dirp (cdr (assq 'directory apps)))
  7761. ;; First, try matching against apps-dlink if we
  7762. ;; get a match here, store the match data for
  7763. ;; later.
  7764. (let ((match (assoc-default dlink apps-dlink
  7765. 'string-match)))
  7766. (if match
  7767. (progn (setq link-match-data (match-data))
  7768. match)
  7769. (progn (setq in-emacs (or in-emacs line search))
  7770. nil))) ; if we have no match in apps-dlink,
  7771. ; always open the file in emacs if line or search
  7772. ; is given (for backwards compatibility)
  7773. (assoc-default dfile
  7774. (org--file-apps-regexp-alist apps a-m-a-p)
  7775. 'string-match)
  7776. (cdr (assoc ext apps))
  7777. (cdr (assq t apps))))))
  7778. (when (eq cmd 'system)
  7779. (setq cmd (cdr (assq 'system apps))))
  7780. (when (eq cmd 'default)
  7781. (setq cmd (cdr (assoc t apps))))
  7782. (when (eq cmd 'mailcap)
  7783. (require 'mailcap)
  7784. (mailcap-parse-mailcaps)
  7785. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7786. (command (mailcap-mime-info mime-type)))
  7787. (if (stringp command)
  7788. (setq cmd command)
  7789. (setq cmd 'emacs))))
  7790. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7791. (not (file-exists-p file))
  7792. (not org-open-non-existing-files))
  7793. (user-error "No such file: %s" file))
  7794. (cond
  7795. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7796. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7797. (while (string-match "['\"]%s['\"]" cmd)
  7798. (setq cmd (replace-match "%s" t t cmd)))
  7799. (setq cmd (replace-regexp-in-string
  7800. "%s"
  7801. (shell-quote-argument (convert-standard-filename file))
  7802. cmd
  7803. nil t))
  7804. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7805. (save-match-data
  7806. (let ((match-index 1)
  7807. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7808. (set-match-data link-match-data)
  7809. (while (<= match-index number-of-groups)
  7810. (let ((regex (concat "%" (number-to-string match-index)))
  7811. (replace-with (match-string match-index dlink)))
  7812. (while (string-match regex cmd)
  7813. (setq cmd (replace-match replace-with t t cmd))))
  7814. (setq match-index (+ match-index 1)))))
  7815. (save-window-excursion
  7816. (message "Running %s...done" cmd)
  7817. (start-process-shell-command cmd nil cmd)
  7818. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7819. ((or (stringp cmd)
  7820. (eq cmd 'emacs))
  7821. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7822. (widen)
  7823. (cond (line (org-goto-line line)
  7824. (when (derived-mode-p 'org-mode) (org-reveal)))
  7825. (search (condition-case err
  7826. (org-link-search search)
  7827. ;; Save position before error-ing out so user
  7828. ;; can easily move back to the original buffer.
  7829. (error (funcall save-position-maybe)
  7830. (error (nth 1 err)))))))
  7831. ((functionp cmd)
  7832. (save-match-data
  7833. (set-match-data link-match-data)
  7834. (condition-case nil
  7835. (funcall cmd file link)
  7836. ;; FIXME: Remove this check when most default installations
  7837. ;; of Emacs have at least Org 9.0.
  7838. ((debug wrong-number-of-arguments wrong-type-argument
  7839. invalid-function)
  7840. (user-error "Please see Org News for version 9.0 about \
  7841. `org-file-apps'--Lisp error: %S" cmd)))))
  7842. ((consp cmd)
  7843. ;; FIXME: Remove this check when most default installations of
  7844. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7845. ;; fall back to `org-link-frame-setup' for an old usage of
  7846. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7847. (user-error "Please see Org News for version 9.0 about \
  7848. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7849. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7850. (funcall save-position-maybe)))
  7851. ;;;###autoload
  7852. (defun org-open-at-point-global ()
  7853. "Follow a link or a time-stamp like Org mode does.
  7854. Also follow links and emails as seen by `thing-at-point'.
  7855. This command can be called in any mode to follow an external
  7856. link or a time-stamp that has Org mode syntax. Its behavior
  7857. is undefined when called on internal links like fuzzy links.
  7858. Raise a user error when there is nothing to follow."
  7859. (interactive)
  7860. (let ((tap-url (thing-at-point 'url))
  7861. (tap-email (thing-at-point 'email)))
  7862. (cond ((org-in-regexp org-link-any-re)
  7863. (org-link-open-from-string (match-string-no-properties 0)))
  7864. ((or (org-in-regexp org-ts-regexp-both nil t)
  7865. (org-in-regexp org-tsr-regexp-both nil t))
  7866. (org-follow-timestamp-link))
  7867. (tap-url (org-link-open-from-string tap-url))
  7868. (tap-email (org-link-open-from-string
  7869. (concat "mailto:" tap-email)))
  7870. (t (user-error "No link found")))))
  7871. (defvar org-open-at-point-functions nil
  7872. "Hook that is run when following a link at point.
  7873. Functions in this hook must return t if they identify and follow
  7874. a link at point. If they don't find anything interesting at point,
  7875. they must return nil.")
  7876. (defun org-open-at-point (&optional arg)
  7877. "Open link, timestamp, footnote or tags at point.
  7878. When point is on a link, follow it. Normally, files will be
  7879. opened by an appropriate application. If the optional prefix
  7880. argument ARG is non-nil, Emacs will visit the file. With
  7881. a double prefix argument, try to open outside of Emacs, in the
  7882. application the system uses for this file type.
  7883. When point is on a timestamp, open the agenda at the day
  7884. specified.
  7885. When point is a footnote definition, move to the first reference
  7886. found. If it is on a reference, move to the associated
  7887. definition.
  7888. When point is on a headline, display a list of every link in the
  7889. entry, so it is possible to pick one, or all, of them. If point
  7890. is on a tag, call `org-tags-view' instead.
  7891. On top of syntactically correct links, this function also tries
  7892. to open links and time-stamps in comments, node properties, and
  7893. keywords if point is on something looking like a timestamp or
  7894. a link."
  7895. (interactive "P")
  7896. (org-load-modules-maybe)
  7897. (setq org-window-config-before-follow-link (current-window-configuration))
  7898. (org-remove-occur-highlights nil nil t)
  7899. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7900. (let* ((context
  7901. ;; Only consider supported types, even if they are not the
  7902. ;; closest one.
  7903. (org-element-lineage
  7904. (org-element-context)
  7905. '(clock comment comment-block footnote-definition
  7906. footnote-reference headline inline-src-block inlinetask
  7907. keyword link node-property planning src-block timestamp)
  7908. t))
  7909. (type (org-element-type context))
  7910. (value (org-element-property :value context)))
  7911. (cond
  7912. ((not type) (user-error "No link found"))
  7913. ;; No valid link at point. For convenience, look if something
  7914. ;; looks like a link under point in some specific places.
  7915. ((memq type '(comment comment-block node-property keyword))
  7916. (call-interactively #'org-open-at-point-global))
  7917. ;; On a headline or an inlinetask, but not on a timestamp,
  7918. ;; a link, a footnote reference.
  7919. ((memq type '(headline inlinetask))
  7920. (org-match-line org-complex-heading-regexp)
  7921. (let ((tags-beg (match-beginning 5))
  7922. (tags-end (match-end 5)))
  7923. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7924. ;; On tags.
  7925. (org-tags-view
  7926. arg
  7927. (save-excursion
  7928. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7929. (end-tag (search-forward ":" tags-end nil 2)))
  7930. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7931. ;; Not on tags.
  7932. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7933. (`(nil . ,_)
  7934. (require 'org-attach)
  7935. (when (org-attach-dir)
  7936. (message "Opening attachment")
  7937. (if (equal arg '(4))
  7938. (org-attach-reveal-in-emacs)
  7939. (org-attach-reveal))))
  7940. (`(,links . ,links-end)
  7941. (dolist (link (if (stringp links) (list links) links))
  7942. (search-forward link nil links-end)
  7943. (goto-char (match-beginning 0))
  7944. (org-open-at-point arg)))))))
  7945. ;; On a footnote reference or at definition's label.
  7946. ((or (eq type 'footnote-reference)
  7947. (and (eq type 'footnote-definition)
  7948. (save-excursion
  7949. ;; Do not validate action when point is on the
  7950. ;; spaces right after the footnote label, in order
  7951. ;; to be on par with behavior on links.
  7952. (skip-chars-forward " \t")
  7953. (let ((begin
  7954. (org-element-property :contents-begin context)))
  7955. (if begin (< (point) begin)
  7956. (= (org-element-property :post-affiliated context)
  7957. (line-beginning-position)))))))
  7958. (org-footnote-action))
  7959. ;; On a planning line. Check if we are really on a timestamp.
  7960. ((and (eq type 'planning)
  7961. (org-in-regexp org-ts-regexp-both nil t))
  7962. (org-follow-timestamp-link))
  7963. ;; On a clock line, make sure point is on the timestamp
  7964. ;; before opening it.
  7965. ((and (eq type 'clock)
  7966. value
  7967. (>= (point) (org-element-property :begin value))
  7968. (<= (point) (org-element-property :end value)))
  7969. (org-follow-timestamp-link))
  7970. ((eq type 'src-block) (org-babel-open-src-block-result))
  7971. ;; Do nothing on white spaces after an object.
  7972. ((>= (point)
  7973. (save-excursion
  7974. (goto-char (org-element-property :end context))
  7975. (skip-chars-backward " \t")
  7976. (point)))
  7977. (user-error "No link found"))
  7978. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7979. ((eq type 'timestamp) (org-follow-timestamp-link))
  7980. ((eq type 'link) (org-link-open context arg))
  7981. (t (user-error "No link found")))))
  7982. (run-hook-with-args 'org-follow-link-hook))
  7983. ;;;###autoload
  7984. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7985. "Offer links in the current entry and return the selected link.
  7986. If there is only one link, return it.
  7987. If NTH is an integer, return the NTH link found.
  7988. If ZERO is a string, check also this string for a link, and if
  7989. there is one, return it."
  7990. (with-current-buffer buffer
  7991. (org-with-wide-buffer
  7992. (goto-char marker)
  7993. (let ((cnt ?0)
  7994. have-zero end links link c)
  7995. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7996. (push (match-string 0 zero) links)
  7997. (setq cnt (1- cnt) have-zero t))
  7998. (save-excursion
  7999. (org-back-to-heading t)
  8000. (setq end (save-excursion (outline-next-heading) (point)))
  8001. (while (re-search-forward org-link-any-re end t)
  8002. (push (match-string 0) links))
  8003. (setq links (org-uniquify (reverse links))))
  8004. (cond
  8005. ((null links)
  8006. (message "No links"))
  8007. ((equal (length links) 1)
  8008. (setq link (car links)))
  8009. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  8010. (setq link (nth (if have-zero nth (1- nth)) links)))
  8011. (t ; we have to select a link
  8012. (save-excursion
  8013. (save-window-excursion
  8014. (delete-other-windows)
  8015. (with-output-to-temp-buffer "*Select Link*"
  8016. (dolist (l links)
  8017. (cond
  8018. ((not (string-match org-link-bracket-re l))
  8019. (princ (format "[%c] %s\n" (cl-incf cnt)
  8020. (org-unbracket-string "<" ">" l))))
  8021. ((match-end 2)
  8022. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  8023. (match-string 2 l) (match-string 1 l))))
  8024. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  8025. (match-string 1 l)))))))
  8026. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  8027. (message "Select link to open, RET to open all:")
  8028. (setq c (read-char-exclusive))
  8029. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  8030. (when (equal c ?q) (user-error "Abort"))
  8031. (if (equal c ?\C-m)
  8032. (setq link links)
  8033. (setq nth (- c ?0))
  8034. (when have-zero (setq nth (1+ nth)))
  8035. (unless (and (integerp nth) (>= (length links) nth))
  8036. (user-error "Invalid link selection"))
  8037. (setq link (nth (1- nth) links)))))
  8038. (cons link end)))))
  8039. ;;; File search
  8040. (defun org-do-occur (regexp &optional cleanup)
  8041. "Call the Emacs command `occur'.
  8042. If CLEANUP is non-nil, remove the printout of the regular expression
  8043. in the *Occur* buffer. This is useful if the regex is long and not useful
  8044. to read."
  8045. (occur regexp)
  8046. (when cleanup
  8047. (let ((cwin (selected-window)) win beg end)
  8048. (when (setq win (get-buffer-window "*Occur*"))
  8049. (select-window win))
  8050. (goto-char (point-min))
  8051. (when (re-search-forward "match[a-z]+" nil t)
  8052. (setq beg (match-end 0))
  8053. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  8054. (setq end (1- (match-beginning 0)))))
  8055. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  8056. (goto-char (point-min))
  8057. (select-window cwin))))
  8058. ;;; The Mark Ring
  8059. (defvar org-mark-ring nil
  8060. "Mark ring for positions before jumps in Org mode.")
  8061. (defvar org-mark-ring-last-goto nil
  8062. "Last position in the mark ring used to go back.")
  8063. ;; Fill and close the ring
  8064. (setq org-mark-ring nil)
  8065. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  8066. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  8067. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  8068. org-mark-ring)
  8069. (defun org-mark-ring-push (&optional pos buffer)
  8070. "Put the current position into the mark ring and rotate it.
  8071. Also push position into the Emacs mark ring. If optional
  8072. argument POS and BUFFER are not nil, mark this location instead."
  8073. (interactive)
  8074. (let ((pos (or pos (point)))
  8075. (buffer (or buffer (current-buffer))))
  8076. (with-current-buffer buffer
  8077. (org-with-point-at pos (push-mark nil t)))
  8078. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  8079. (move-marker (car org-mark-ring) pos buffer))
  8080. (message
  8081. (substitute-command-keys
  8082. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  8083. (defun org-mark-ring-goto (&optional n)
  8084. "Jump to the previous position in the mark ring.
  8085. With prefix arg N, jump back that many stored positions. When
  8086. called several times in succession, walk through the entire ring.
  8087. Org mode commands jumping to a different position in the current file,
  8088. or to another Org file, automatically push the old position onto the ring."
  8089. (interactive "p")
  8090. (let (p m)
  8091. (if (eq last-command this-command)
  8092. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  8093. (setq p org-mark-ring))
  8094. (setq org-mark-ring-last-goto p)
  8095. (setq m (car p))
  8096. (pop-to-buffer-same-window (marker-buffer m))
  8097. (goto-char m)
  8098. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  8099. ;;; Following specific links
  8100. (defvar org-agenda-buffer-tmp-name)
  8101. (defvar org-agenda-start-on-weekday)
  8102. (defun org-follow-timestamp-link ()
  8103. "Open an agenda view for the time-stamp date/range at point."
  8104. (cond
  8105. ((org-at-date-range-p t)
  8106. (let ((org-agenda-start-on-weekday)
  8107. (t1 (match-string 1))
  8108. (t2 (match-string 2)) tt1 tt2)
  8109. (setq tt1 (time-to-days (org-time-string-to-time t1))
  8110. tt2 (time-to-days (org-time-string-to-time t2)))
  8111. (let ((org-agenda-buffer-tmp-name
  8112. (format "*Org Agenda(a:%s)"
  8113. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  8114. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  8115. ((org-at-timestamp-p 'lax)
  8116. (let ((org-agenda-buffer-tmp-name
  8117. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  8118. (org-agenda-list nil (time-to-days (org-time-string-to-time
  8119. (substring (match-string 1) 0 10)))
  8120. 1)))
  8121. (t (error "This should not happen"))))
  8122. ;;; Following file links
  8123. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  8124. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  8125. (declare-function mailcap-mime-info
  8126. "mailcap" (string &optional request no-decode))
  8127. (defvar org-wait nil)
  8128. ;;;; Refiling
  8129. (defun org-get-org-file ()
  8130. "Read a filename, with default directory `org-directory'."
  8131. (let ((default (or org-default-notes-file remember-data-file)))
  8132. (read-file-name (format "File name [%s]: " default)
  8133. (file-name-as-directory org-directory)
  8134. default)))
  8135. (defun org-notes-order-reversed-p ()
  8136. "Check if the current file should receive notes in reversed order."
  8137. (cond
  8138. ((not org-reverse-note-order) nil)
  8139. ((eq t org-reverse-note-order) t)
  8140. ((not (listp org-reverse-note-order)) nil)
  8141. (t (catch 'exit
  8142. (dolist (entry org-reverse-note-order)
  8143. (when (string-match (car entry) buffer-file-name)
  8144. (throw 'exit (cdr entry))))))))
  8145. (defvar org-agenda-new-buffers nil
  8146. "Buffers created to visit agenda files.")
  8147. (declare-function org-string-nw-p "org-macs" (s))
  8148. ;;;; Dynamic blocks
  8149. (defun org-find-dblock (name)
  8150. "Find the first dynamic block with name NAME in the buffer.
  8151. If not found, stay at current position and return nil."
  8152. (let ((case-fold-search t) pos)
  8153. (save-excursion
  8154. (goto-char (point-min))
  8155. (setq pos (and (re-search-forward
  8156. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8157. (match-beginning 0))))
  8158. (when pos (goto-char pos))
  8159. pos))
  8160. (defun org-create-dblock (plist)
  8161. "Create a dynamic block section, with parameters taken from PLIST.
  8162. PLIST must contain a :name entry which is used as the name of the block."
  8163. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8164. (end-of-line 1)
  8165. (newline))
  8166. (let ((col (current-column))
  8167. (name (plist-get plist :name)))
  8168. (insert "#+BEGIN: " name)
  8169. (while plist
  8170. (if (eq (car plist) :name)
  8171. (setq plist (cddr plist))
  8172. (insert " " (prin1-to-string (pop plist)))))
  8173. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8174. (beginning-of-line -2)))
  8175. (defun org-prepare-dblock ()
  8176. "Prepare dynamic block for refresh.
  8177. This empties the block, puts the cursor at the insert position and returns
  8178. the property list including an extra property :name with the block name."
  8179. (unless (looking-at org-dblock-start-re)
  8180. (user-error "Not at a dynamic block"))
  8181. (let* ((begdel (1+ (match-end 0)))
  8182. (name (org-no-properties (match-string 1)))
  8183. (params (append (list :name name)
  8184. (read (concat "(" (match-string 3) ")")))))
  8185. (save-excursion
  8186. (beginning-of-line 1)
  8187. (skip-chars-forward " \t")
  8188. (setq params (plist-put params :indentation-column (current-column))))
  8189. (unless (re-search-forward org-dblock-end-re nil t)
  8190. (error "Dynamic block not terminated"))
  8191. (setq params
  8192. (append params
  8193. (list :content (buffer-substring
  8194. begdel (match-beginning 0)))))
  8195. (delete-region begdel (match-beginning 0))
  8196. (goto-char begdel)
  8197. (open-line 1)
  8198. params))
  8199. (defun org-map-dblocks (&optional command)
  8200. "Apply COMMAND to all dynamic blocks in the current buffer.
  8201. If COMMAND is not given, use `org-update-dblock'."
  8202. (let ((cmd (or command 'org-update-dblock)))
  8203. (save-excursion
  8204. (goto-char (point-min))
  8205. (while (re-search-forward org-dblock-start-re nil t)
  8206. (goto-char (match-beginning 0))
  8207. (save-excursion
  8208. (condition-case nil
  8209. (funcall cmd)
  8210. (error (message "Error during update of dynamic block"))))
  8211. (unless (re-search-forward org-dblock-end-re nil t)
  8212. (error "Dynamic block not terminated"))))))
  8213. (defvar org-dynamic-block-alist nil
  8214. "Alist defining all the Org dynamic blocks.
  8215. The key is the dynamic block type name, as a string. The value
  8216. is the function used to insert the dynamic block.
  8217. Use `org-dynamic-block-define' to populate it.")
  8218. (defun org-dynamic-block-function (type)
  8219. "Return function associated to a given dynamic block type.
  8220. TYPE is the dynamic block type, as a string."
  8221. (cdr (assoc type org-dynamic-block-alist)))
  8222. (defun org-dynamic-block-types ()
  8223. "List all defined dynamic block types."
  8224. (mapcar #'car org-dynamic-block-alist))
  8225. (defun org-dynamic-block-define (type func)
  8226. "Define dynamic block TYPE with FUNC.
  8227. TYPE is a string. FUNC is the function creating the dynamic
  8228. block of such type."
  8229. (pcase (assoc type org-dynamic-block-alist)
  8230. (`nil (push (cons type func) org-dynamic-block-alist))
  8231. (def (setcdr def func))))
  8232. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  8233. "Insert a dynamic block of type TYPE.
  8234. When used interactively, select the dynamic block types among
  8235. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  8236. is non-nil, call the dynamic block function interactively."
  8237. (interactive (list (completing-read "Dynamic block: "
  8238. (org-dynamic-block-types))
  8239. t))
  8240. (pcase (org-dynamic-block-function type)
  8241. (`nil (error "No such dynamic block: %S" type))
  8242. ((and f (pred functionp))
  8243. (if interactive-p (call-interactively f) (funcall f)))
  8244. (_ (error "Invalid function for dynamic block %S" type))))
  8245. (defun org-dblock-update (&optional arg)
  8246. "User command for updating dynamic blocks.
  8247. Update the dynamic block at point. With prefix ARG, update all dynamic
  8248. blocks in the buffer."
  8249. (interactive "P")
  8250. (if arg
  8251. (org-update-all-dblocks)
  8252. (or (looking-at org-dblock-start-re)
  8253. (org-beginning-of-dblock))
  8254. (org-update-dblock)))
  8255. (defun org-update-dblock ()
  8256. "Update the dynamic block at point.
  8257. This means to empty the block, parse for parameters and then call
  8258. the correct writing function."
  8259. (interactive)
  8260. (save-excursion
  8261. (let* ((win (selected-window))
  8262. (pos (point))
  8263. (line (org-current-line))
  8264. (params (org-prepare-dblock))
  8265. (name (plist-get params :name))
  8266. (indent (plist-get params :indentation-column))
  8267. (cmd (intern (concat "org-dblock-write:" name))))
  8268. (message "Updating dynamic block `%s' at line %d..." name line)
  8269. (funcall cmd params)
  8270. (message "Updating dynamic block `%s' at line %d...done" name line)
  8271. (goto-char pos)
  8272. (when (and indent (> indent 0))
  8273. (setq indent (make-string indent ?\ ))
  8274. (save-excursion
  8275. (select-window win)
  8276. (org-beginning-of-dblock)
  8277. (forward-line 1)
  8278. (while (not (looking-at org-dblock-end-re))
  8279. (insert indent)
  8280. (beginning-of-line 2))
  8281. (when (looking-at org-dblock-end-re)
  8282. (and (looking-at "[ \t]+")
  8283. (replace-match ""))
  8284. (insert indent)))))))
  8285. (defun org-beginning-of-dblock ()
  8286. "Find the beginning of the dynamic block at point.
  8287. Error if there is no such block at point."
  8288. (let ((pos (point))
  8289. beg)
  8290. (end-of-line 1)
  8291. (if (and (re-search-backward org-dblock-start-re nil t)
  8292. (setq beg (match-beginning 0))
  8293. (re-search-forward org-dblock-end-re nil t)
  8294. (> (match-end 0) pos))
  8295. (goto-char beg)
  8296. (goto-char pos)
  8297. (error "Not in a dynamic block"))))
  8298. (defun org-update-all-dblocks ()
  8299. "Update all dynamic blocks in the buffer.
  8300. This function can be used in a hook."
  8301. (interactive)
  8302. (when (derived-mode-p 'org-mode)
  8303. (org-map-dblocks 'org-update-dblock)))
  8304. ;;;; Completion
  8305. (declare-function org-export-backend-options "ox" (cl-x) t)
  8306. (defun org-get-export-keywords ()
  8307. "Return a list of all currently understood export keywords.
  8308. Export keywords include options, block names, attributes and
  8309. keywords relative to each registered export back-end."
  8310. (let (keywords)
  8311. (dolist (backend
  8312. (bound-and-true-p org-export-registered-backends)
  8313. (delq nil keywords))
  8314. ;; Back-end name (for keywords, like #+LATEX:)
  8315. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8316. (dolist (option-entry (org-export-backend-options backend))
  8317. ;; Back-end options.
  8318. (push (nth 1 option-entry) keywords)))))
  8319. (defconst org-options-keywords
  8320. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8321. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8322. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8323. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8324. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8325. (defcustom org-structure-template-alist
  8326. '(("a" . "export ascii")
  8327. ("c" . "center")
  8328. ("C" . "comment")
  8329. ("e" . "example")
  8330. ("E" . "export")
  8331. ("h" . "export html")
  8332. ("l" . "export latex")
  8333. ("q" . "quote")
  8334. ("s" . "src")
  8335. ("v" . "verse"))
  8336. "An alist of keys and block types.
  8337. `org-insert-structure-template' will display a menu with this
  8338. list of templates to choose from. The block type is inserted,
  8339. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8340. The menu keys are defined by the car of each entry in this alist.
  8341. If two entries have the keys \"a\" and \"aa\" respectively, the
  8342. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8343. latter will be inserted by typing \"aa\". If an entry with the
  8344. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8345. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8346. block can be inserted by pressing TAB after the string \"<KEY\"."
  8347. :group 'org-edit-structure
  8348. :type '(repeat
  8349. (cons (string :tag "Key")
  8350. (string :tag "Template")))
  8351. :package-version '(Org . "9.2"))
  8352. (defun org--check-org-structure-template-alist (&optional checklist)
  8353. "Check whether `org-structure-template-alist' is set up correctly.
  8354. In particular, check if the Org 9.2 format is used as opposed to
  8355. previous format."
  8356. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8357. (or (eval checklist)
  8358. org-structure-template-alist))))
  8359. (when elm
  8360. (org-display-warning
  8361. (format "
  8362. Please update the entries of `%s'.
  8363. In Org 9.2 the format was changed from something like
  8364. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8365. to something like
  8366. (\"s\" . \"src\")
  8367. Please refer to the documentation of `org-structure-template-alist'.
  8368. The following entries must be updated:
  8369. %s"
  8370. (or checklist 'org-structure-template-alist)
  8371. (pp-to-string elm))))))
  8372. (defun org--insert-structure-template-mks ()
  8373. "Present `org-structure-template-alist' with `org-mks'.
  8374. Menus are added if keys require more than one keystroke. Tabs
  8375. are added to single key entries when more than one stroke is
  8376. needed. Keys longer than two characters are reduced to two
  8377. characters."
  8378. (org--check-org-structure-template-alist)
  8379. (let* (case-fold-search
  8380. (templates (append org-structure-template-alist
  8381. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8382. (keys (mapcar #'car templates))
  8383. (start-letters
  8384. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8385. ;; Sort each element of `org-structure-template-alist' into
  8386. ;; sublists according to the first letter.
  8387. (superlist
  8388. (mapcar (lambda (letter)
  8389. (list letter
  8390. (cl-remove-if-not
  8391. (apply-partially #'string-match-p (concat "^" letter))
  8392. templates :key #'car)))
  8393. start-letters)))
  8394. (org-mks
  8395. (apply #'append
  8396. ;; Make an `org-mks' table. If only one element is
  8397. ;; present in a sublist, make it part of the top-menu,
  8398. ;; otherwise make a submenu according to the starting
  8399. ;; letter and populate it.
  8400. (mapcar (lambda (sublist)
  8401. (if (eq 1 (length (cadr sublist)))
  8402. (mapcar (lambda (elm)
  8403. (list (substring (car elm) 0 1)
  8404. (cdr elm) ""))
  8405. (cadr sublist))
  8406. ;; Create submenu.
  8407. (let* ((topkey (car sublist))
  8408. (elms (cadr sublist))
  8409. (keys (mapcar #'car elms))
  8410. (long (> (length elms) 3)))
  8411. (append
  8412. (list
  8413. ;; Make a description of the submenu.
  8414. (list topkey
  8415. (concat
  8416. (mapconcat #'cdr
  8417. (cl-subseq elms 0 (if long 3 (length elms)))
  8418. ", ")
  8419. (when long ", ..."))))
  8420. ;; List of entries in submenu.
  8421. (cl-mapcar #'list
  8422. (org--insert-structure-template-unique-keys keys)
  8423. (mapcar #'cdr elms)
  8424. (make-list (length elms) ""))))))
  8425. superlist))
  8426. "Select a key\n============"
  8427. "Key: ")))
  8428. (defun org--insert-structure-template-unique-keys (keys)
  8429. "Make a list of unique, two characters long elements from KEYS.
  8430. Elements of length one have a tab appended. Elements of length
  8431. two are kept as is. Longer elements are truncated to length two.
  8432. If an element cannot be made unique, an error is raised."
  8433. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8434. menu-keys)
  8435. (dolist (key ordered-keys)
  8436. (let ((potential-key
  8437. (cl-case (length key)
  8438. (1 (concat key "\t"))
  8439. (2 key)
  8440. (otherwise
  8441. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8442. (mapcar (apply-partially #'concat (substring key 0 1))
  8443. (split-string (substring key 1) "" t)))))))
  8444. (if (or (not potential-key) (assoc potential-key menu-keys))
  8445. (user-error "Could not make unique key for %s." key)
  8446. (push (cons potential-key key) menu-keys))))
  8447. (mapcar #'car
  8448. (cl-sort menu-keys #'<
  8449. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8450. (defun org-insert-structure-template (type)
  8451. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8452. Select a block from `org-structure-template-alist' then type
  8453. either RET, TAB or SPC to write the block type. With an active
  8454. region, wrap the region in the block. Otherwise, insert an empty
  8455. block."
  8456. (interactive
  8457. (list (pcase (org--insert-structure-template-mks)
  8458. (`("\t" . ,_) (read-string "Structure type: "))
  8459. (`(,_ ,choice . ,_) choice))))
  8460. (let* ((region? (use-region-p))
  8461. (region-start (and region? (region-beginning)))
  8462. (region-end (and region? (copy-marker (region-end))))
  8463. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8464. (verbatim? (string-match-p
  8465. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8466. type)))
  8467. (when region? (goto-char region-start))
  8468. (let ((column (current-indentation)))
  8469. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8470. (beginning-of-line)
  8471. (insert "\n"))
  8472. (save-excursion
  8473. (indent-to column)
  8474. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8475. (when region?
  8476. (when verbatim? (org-escape-code-in-region (point) region-end))
  8477. (goto-char region-end)
  8478. ;; Ignore empty lines at the end of the region.
  8479. (skip-chars-backward " \r\t\n")
  8480. (end-of-line))
  8481. (unless (bolp) (insert "\n"))
  8482. (indent-to column)
  8483. (insert (format "#+end_%s" (car (split-string type))))
  8484. (if (looking-at "[ \t]*$") (replace-match "")
  8485. (insert "\n"))
  8486. (when (and (eobp) (not (bolp))) (insert "\n")))
  8487. (if extended? (end-of-line)
  8488. (forward-line)
  8489. (skip-chars-forward " \t")))))
  8490. ;;;; TODO, DEADLINE, Comments
  8491. (defun org-toggle-comment ()
  8492. "Change the COMMENT state of an entry."
  8493. (interactive)
  8494. (save-excursion
  8495. (org-back-to-heading)
  8496. (let ((case-fold-search nil))
  8497. (looking-at org-complex-heading-regexp))
  8498. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8499. (skip-chars-forward " \t")
  8500. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8501. (if (org-in-commented-heading-p t)
  8502. (delete-region (point)
  8503. (progn (search-forward " " (line-end-position) 'move)
  8504. (skip-chars-forward " \t")
  8505. (point)))
  8506. (insert org-comment-string)
  8507. (unless (eolp) (insert " ")))))
  8508. (defvar org-last-todo-state-is-todo nil
  8509. "This is non-nil when the last TODO state change led to a TODO state.
  8510. If the last change removed the TODO tag or switched to DONE, then
  8511. this is nil.")
  8512. (defvar org-todo-setup-filter-hook nil
  8513. "Hook for functions that pre-filter todo specs.
  8514. Each function takes a todo spec and returns either nil or the spec
  8515. transformed into canonical form." )
  8516. (defvar org-todo-get-default-hook nil
  8517. "Hook for functions that get a default item for todo.
  8518. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8519. nil or a string to be used for the todo mark." )
  8520. (defvar org-agenda-headline-snapshot-before-repeat)
  8521. (defun org-current-effective-time ()
  8522. "Return current time adjusted for `org-extend-today-until' variable."
  8523. (let* ((ct (org-current-time))
  8524. (dct (decode-time ct))
  8525. (ct1
  8526. (cond
  8527. (org-use-last-clock-out-time-as-effective-time
  8528. (or (org-clock-get-last-clock-out-time) ct))
  8529. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8530. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8531. (t ct))))
  8532. ct1))
  8533. (defun org-todo-yesterday (&optional arg)
  8534. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8535. (interactive "P")
  8536. (if (eq major-mode 'org-agenda-mode)
  8537. (apply 'org-agenda-todo-yesterday arg)
  8538. (let* ((org-use-effective-time t)
  8539. (hour (nth 2 (decode-time (org-current-time))))
  8540. (org-extend-today-until (1+ hour)))
  8541. (org-todo arg))))
  8542. (defvar org-block-entry-blocking ""
  8543. "First entry preventing the TODO state change.")
  8544. (defun org-cancel-repeater ()
  8545. "Cancel a repeater by setting its numeric value to zero."
  8546. (interactive)
  8547. (save-excursion
  8548. (org-back-to-heading t)
  8549. (let ((bound1 (point))
  8550. (bound0 (save-excursion (outline-next-heading) (point))))
  8551. (when (and (re-search-forward
  8552. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8553. org-deadline-time-regexp "\\)\\|\\("
  8554. org-ts-regexp "\\)")
  8555. bound0 t)
  8556. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8557. bound1 t))
  8558. (replace-match "0" t nil nil 1)))))
  8559. (defvar org-state)
  8560. (defvar org-blocked-by-checkboxes)
  8561. (defun org-todo (&optional arg)
  8562. "Change the TODO state of an item.
  8563. The state of an item is given by a keyword at the start of the heading,
  8564. like
  8565. *** TODO Write paper
  8566. *** DONE Call mom
  8567. The different keywords are specified in the variable `org-todo-keywords'.
  8568. By default the available states are \"TODO\" and \"DONE\". So, for this
  8569. example: when the item starts with TODO, it is changed to DONE.
  8570. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8571. DONE are present, add TODO at the beginning of the heading.
  8572. You can set up single-character keys to fast-select the new state. See the
  8573. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8574. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8575. and take a
  8576. logging note.
  8577. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8578. next set of TODO \
  8579. keywords (nextset).
  8580. Another way to achieve this is `S-C-<right>'.
  8581. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8582. prefix, circumvent any state blocking.
  8583. With numeric prefix arg, switch to the Nth state.
  8584. With a numeric prefix arg of 0, inhibit note taking for the change.
  8585. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8586. When called through ELisp, arg is also interpreted in the following way:
  8587. `none' -> empty state
  8588. \"\" -> switch to empty state
  8589. `done' -> switch to DONE
  8590. `nextset' -> switch to the next set of keywords
  8591. `previousset' -> switch to the previous set of keywords
  8592. \"WAITING\" -> switch to the specified keyword, but only if it
  8593. really is a member of `org-todo-keywords'."
  8594. (interactive "P")
  8595. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8596. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8597. 'region-start-level 'region))
  8598. org-loop-over-headlines-in-active-region)
  8599. (org-map-entries
  8600. (lambda () (org-todo arg))
  8601. nil cl
  8602. (when (org-invisible-p) (org-end-of-subtree nil t))))
  8603. (when (equal arg '(16)) (setq arg 'nextset))
  8604. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  8605. (let ((org-blocker-hook org-blocker-hook)
  8606. commentp
  8607. case-fold-search)
  8608. (when (equal arg '(64))
  8609. (setq arg nil org-blocker-hook nil))
  8610. (when (and org-blocker-hook
  8611. (or org-inhibit-blocking
  8612. (org-entry-get nil "NOBLOCKING")))
  8613. (setq org-blocker-hook nil))
  8614. (save-excursion
  8615. (catch 'exit
  8616. (org-back-to-heading t)
  8617. (when (org-in-commented-heading-p t)
  8618. (org-toggle-comment)
  8619. (setq commentp t))
  8620. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8621. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8622. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8623. (let* ((match-data (match-data))
  8624. (startpos (copy-marker (line-beginning-position)))
  8625. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8626. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8627. (org-log-done org-log-done)
  8628. (org-log-repeat org-log-repeat)
  8629. (org-todo-log-states org-todo-log-states)
  8630. (org-inhibit-logging
  8631. (if (equal arg 0)
  8632. (progn (setq arg nil) 'note) org-inhibit-logging))
  8633. (this (match-string 1))
  8634. (hl-pos (match-beginning 0))
  8635. (head (org-get-todo-sequence-head this))
  8636. (ass (assoc head org-todo-kwd-alist))
  8637. (interpret (nth 1 ass))
  8638. (done-word (nth 3 ass))
  8639. (final-done-word (nth 4 ass))
  8640. (org-last-state (or this ""))
  8641. (completion-ignore-case t)
  8642. (member (member this org-todo-keywords-1))
  8643. (tail (cdr member))
  8644. (org-state (cond
  8645. ((eq arg 'right)
  8646. ;; Next state
  8647. (if this
  8648. (if tail (car tail) nil)
  8649. (car org-todo-keywords-1)))
  8650. ((eq arg 'left)
  8651. ;; Previous state
  8652. (unless (equal member org-todo-keywords-1)
  8653. (if this
  8654. (nth (- (length org-todo-keywords-1)
  8655. (length tail) 2)
  8656. org-todo-keywords-1)
  8657. (org-last org-todo-keywords-1))))
  8658. (arg
  8659. ;; User or caller requests a specific state.
  8660. (cond
  8661. ((equal arg "") nil)
  8662. ((eq arg 'none) nil)
  8663. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8664. ((eq arg 'nextset)
  8665. (or (car (cdr (member head org-todo-heads)))
  8666. (car org-todo-heads)))
  8667. ((eq arg 'previousset)
  8668. (let ((org-todo-heads (reverse org-todo-heads)))
  8669. (or (car (cdr (member head org-todo-heads)))
  8670. (car org-todo-heads))))
  8671. ((car (member arg org-todo-keywords-1)))
  8672. ((stringp arg)
  8673. (user-error "State `%s' not valid in this file" arg))
  8674. ((nth (1- (prefix-numeric-value arg))
  8675. org-todo-keywords-1))))
  8676. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8677. ;; Use fast selection.
  8678. (org-fast-todo-selection this))
  8679. ((null member) (or head (car org-todo-keywords-1)))
  8680. ((equal this final-done-word) nil) ;-> make empty
  8681. ((null tail) nil) ;-> first entry
  8682. ((memq interpret '(type priority))
  8683. (if (eq this-command last-command)
  8684. (car tail)
  8685. (if (> (length tail) 0)
  8686. (or done-word (car org-done-keywords))
  8687. nil)))
  8688. (t
  8689. (car tail))))
  8690. (org-state (or
  8691. (run-hook-with-args-until-success
  8692. 'org-todo-get-default-hook org-state org-last-state)
  8693. org-state))
  8694. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8695. (change-plist (list :type 'todo-state-change :from this :to org-state
  8696. :position startpos))
  8697. dolog now-done-p)
  8698. (when org-blocker-hook
  8699. (let (org-blocked-by-checkboxes block-reason)
  8700. (setq org-last-todo-state-is-todo
  8701. (not (member this org-done-keywords)))
  8702. (unless (save-excursion
  8703. (save-match-data
  8704. (org-with-wide-buffer
  8705. (run-hook-with-args-until-failure
  8706. 'org-blocker-hook change-plist))))
  8707. (setq block-reason (if org-blocked-by-checkboxes
  8708. "contained checkboxes"
  8709. (format "\"%s\"" org-block-entry-blocking)))
  8710. (if (called-interactively-p 'interactive)
  8711. (user-error "TODO state change from %s to %s blocked (by %s)"
  8712. this org-state block-reason)
  8713. ;; Fail silently.
  8714. (message "TODO state change from %s to %s blocked (by %s)"
  8715. this org-state block-reason)
  8716. (throw 'exit nil)))))
  8717. (store-match-data match-data)
  8718. (replace-match next t t)
  8719. (cond ((and org-state (equal this org-state))
  8720. (message "TODO state was already %s" (org-trim next)))
  8721. ((not (pos-visible-in-window-p hl-pos))
  8722. (message "TODO state changed to %s" (org-trim next))))
  8723. (unless head
  8724. (setq head (org-get-todo-sequence-head org-state)
  8725. ass (assoc head org-todo-kwd-alist)
  8726. interpret (nth 1 ass)
  8727. done-word (nth 3 ass)
  8728. final-done-word (nth 4 ass)))
  8729. (when (memq arg '(nextset previousset))
  8730. (message "Keyword-Set %d/%d: %s"
  8731. (- (length org-todo-sets) -1
  8732. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8733. (length org-todo-sets)
  8734. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8735. (setq org-last-todo-state-is-todo
  8736. (not (member org-state org-done-keywords)))
  8737. (setq now-done-p (and (member org-state org-done-keywords)
  8738. (not (member this org-done-keywords))))
  8739. (and logging (org-local-logging logging))
  8740. (when (or (and (or org-todo-log-states org-log-done)
  8741. (not (eq org-inhibit-logging t))
  8742. (not (memq arg '(nextset previousset))))
  8743. force-log)
  8744. ;; We need to look at recording a time and note.
  8745. (setq dolog (or (if force-log 'note)
  8746. (nth 1 (assoc org-state org-todo-log-states))
  8747. (nth 2 (assoc this org-todo-log-states))))
  8748. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8749. (setq dolog 'time))
  8750. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8751. (and org-state
  8752. (member org-state org-not-done-keywords)
  8753. (not (member this org-not-done-keywords))))
  8754. ;; This is now a todo state and was not one before
  8755. ;; If there was a CLOSED time stamp, get rid of it.
  8756. (org-add-planning-info nil nil 'closed))
  8757. (when (and now-done-p org-log-done)
  8758. ;; It is now done, and it was not done before.
  8759. (org-add-planning-info 'closed (org-current-effective-time))
  8760. (when (and (not dolog) (eq 'note org-log-done))
  8761. (org-add-log-setup 'done org-state this 'note)))
  8762. (when (and org-state dolog)
  8763. ;; This is a non-nil state, and we need to log it.
  8764. (org-add-log-setup 'state org-state this dolog)))
  8765. ;; Fixup tag positioning.
  8766. (org-todo-trigger-tag-changes org-state)
  8767. (when org-auto-align-tags (org-align-tags))
  8768. (when org-provide-todo-statistics
  8769. (org-update-parent-todo-statistics))
  8770. (when (bound-and-true-p org-clock-out-when-done)
  8771. (org-clock-out-if-current))
  8772. (run-hooks 'org-after-todo-state-change-hook)
  8773. (when (and arg (not (member org-state org-done-keywords)))
  8774. (setq head (org-get-todo-sequence-head org-state)))
  8775. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  8776. ;; Do we need to trigger a repeat?
  8777. (when now-done-p
  8778. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8779. ;; This is for the agenda, take a snapshot of the headline.
  8780. (save-match-data
  8781. (setq org-agenda-headline-snapshot-before-repeat
  8782. (org-get-heading))))
  8783. (org-auto-repeat-maybe org-state))
  8784. ;; Fixup cursor location if close to the keyword.
  8785. (when (and (outline-on-heading-p)
  8786. (not (bolp))
  8787. (save-excursion (beginning-of-line 1)
  8788. (looking-at org-todo-line-regexp))
  8789. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8790. (goto-char (or (match-end 2) (match-end 1)))
  8791. (and (looking-at " ")
  8792. (not (looking-at " *:"))
  8793. (just-one-space)))
  8794. (when org-trigger-hook
  8795. (save-excursion
  8796. (run-hook-with-args 'org-trigger-hook change-plist)))
  8797. (when commentp (org-toggle-comment))))))))
  8798. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8799. "Block turning an entry into a TODO, using the hierarchy.
  8800. This checks whether the current task should be blocked from state
  8801. changes. Such blocking occurs when:
  8802. 1. The task has children which are not all in a completed state.
  8803. 2. A task has a parent with the property :ORDERED:, and there
  8804. are siblings prior to the current task with incomplete
  8805. status.
  8806. 3. The parent of the task is blocked because it has siblings that should
  8807. be done first, or is child of a block grandparent TODO entry."
  8808. (if (not org-enforce-todo-dependencies)
  8809. t ; if locally turned off don't block
  8810. (catch 'dont-block
  8811. ;; If this is not a todo state change, or if this entry is already DONE,
  8812. ;; do not block
  8813. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8814. (member (plist-get change-plist :from)
  8815. (cons 'done org-done-keywords))
  8816. (member (plist-get change-plist :to)
  8817. (cons 'todo org-not-done-keywords))
  8818. (not (plist-get change-plist :to)))
  8819. (throw 'dont-block t))
  8820. ;; If this task has children, and any are undone, it's blocked
  8821. (save-excursion
  8822. (org-back-to-heading t)
  8823. (let ((this-level (funcall outline-level)))
  8824. (outline-next-heading)
  8825. (let ((child-level (funcall outline-level)))
  8826. (while (and (not (eobp))
  8827. (> child-level this-level))
  8828. ;; this todo has children, check whether they are all
  8829. ;; completed
  8830. (when (and (not (org-entry-is-done-p))
  8831. (org-entry-is-todo-p))
  8832. (setq org-block-entry-blocking (org-get-heading))
  8833. (throw 'dont-block nil))
  8834. (outline-next-heading)
  8835. (setq child-level (funcall outline-level))))))
  8836. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8837. ;; any previous siblings are undone, it's blocked
  8838. (save-excursion
  8839. (org-back-to-heading t)
  8840. (let* ((pos (point))
  8841. (parent-pos (and (org-up-heading-safe) (point)))
  8842. (case-fold-search nil))
  8843. (unless parent-pos (throw 'dont-block t)) ; no parent
  8844. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8845. (forward-line 1)
  8846. (re-search-forward org-not-done-heading-regexp pos t))
  8847. (setq org-block-entry-blocking (match-string 0))
  8848. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8849. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8850. (while t
  8851. (goto-char parent-pos)
  8852. (unless (looking-at org-not-done-heading-regexp)
  8853. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8854. (setq pos (point))
  8855. (setq parent-pos (and (org-up-heading-safe) (point)))
  8856. (unless parent-pos (throw 'dont-block t)) ; no parent
  8857. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8858. (forward-line 1)
  8859. (re-search-forward org-not-done-heading-regexp pos t)
  8860. (setq org-block-entry-blocking (org-get-heading)))
  8861. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8862. (defcustom org-track-ordered-property-with-tag nil
  8863. "Should the ORDERED property also be shown as a tag?
  8864. The ORDERED property decides if an entry should require subtasks to be
  8865. completed in sequence. Since a property is not very visible, setting
  8866. this option means that toggling the ORDERED property with the command
  8867. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8868. not relevant for the behavior, but it makes things more visible.
  8869. Note that toggling the tag with tags commands will not change the property
  8870. and therefore not influence behavior!
  8871. This can be t, meaning the tag ORDERED should be used. It can also be a
  8872. string to select a different tag for this task."
  8873. :group 'org-todo
  8874. :type '(choice
  8875. (const :tag "No tracking" nil)
  8876. (const :tag "Track with ORDERED tag" t)
  8877. (string :tag "Use other tag")))
  8878. (defun org-toggle-ordered-property ()
  8879. "Toggle the ORDERED property of the current entry.
  8880. For better visibility, you can track the value of this property with a tag.
  8881. See variable `org-track-ordered-property-with-tag'."
  8882. (interactive)
  8883. (let* ((t1 org-track-ordered-property-with-tag)
  8884. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  8885. (save-excursion
  8886. (org-back-to-heading)
  8887. (if (org-entry-get nil "ORDERED")
  8888. (progn
  8889. (org-delete-property "ORDERED")
  8890. (and tag (org-toggle-tag tag 'off))
  8891. (message "Subtasks can be completed in arbitrary order"))
  8892. (org-entry-put nil "ORDERED" "t")
  8893. (and tag (org-toggle-tag tag 'on))
  8894. (message "Subtasks must be completed in sequence")))))
  8895. (defun org-block-todo-from-checkboxes (change-plist)
  8896. "Block turning an entry into a TODO, using checkboxes.
  8897. This checks whether the current task should be blocked from state
  8898. changes because there are unchecked boxes in this entry."
  8899. (if (not org-enforce-todo-checkbox-dependencies)
  8900. t ; if locally turned off don't block
  8901. (catch 'dont-block
  8902. ;; If this is not a todo state change, or if this entry is already DONE,
  8903. ;; do not block
  8904. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8905. (member (plist-get change-plist :from)
  8906. (cons 'done org-done-keywords))
  8907. (member (plist-get change-plist :to)
  8908. (cons 'todo org-not-done-keywords))
  8909. (not (plist-get change-plist :to)))
  8910. (throw 'dont-block t))
  8911. ;; If this task has checkboxes that are not checked, it's blocked
  8912. (save-excursion
  8913. (org-back-to-heading t)
  8914. (let ((beg (point)) end)
  8915. (outline-next-heading)
  8916. (setq end (point))
  8917. (goto-char beg)
  8918. (when (org-list-search-forward
  8919. (concat (org-item-beginning-re)
  8920. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  8921. "\\[[- ]\\]")
  8922. end t)
  8923. (when (boundp 'org-blocked-by-checkboxes)
  8924. (setq org-blocked-by-checkboxes t))
  8925. (throw 'dont-block nil))))
  8926. t))) ; do not block
  8927. (defun org-entry-blocked-p ()
  8928. "Non-nil if entry at point is blocked."
  8929. (and (not (org-entry-get nil "NOBLOCKING"))
  8930. (member (org-entry-get nil "TODO") org-not-done-keywords)
  8931. (not (run-hook-with-args-until-failure
  8932. 'org-blocker-hook
  8933. (list :type 'todo-state-change
  8934. :position (point)
  8935. :from 'todo
  8936. :to 'done)))))
  8937. (defun org-update-statistics-cookies (all)
  8938. "Update the statistics cookie, either from TODO or from checkboxes.
  8939. This should be called with the cursor in a line with a statistics
  8940. cookie. When called with a \\[universal-argument] prefix, update
  8941. all statistics cookies in the buffer."
  8942. (interactive "P")
  8943. (if all
  8944. (progn
  8945. (org-update-checkbox-count 'all)
  8946. (org-map-entries 'org-update-parent-todo-statistics))
  8947. (if (not (org-at-heading-p))
  8948. (org-update-checkbox-count)
  8949. (let ((pos (point-marker))
  8950. end l1 l2)
  8951. (ignore-errors (org-back-to-heading t))
  8952. (if (not (org-at-heading-p))
  8953. (org-update-checkbox-count)
  8954. (setq l1 (org-outline-level))
  8955. (setq end (save-excursion
  8956. (outline-next-heading)
  8957. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  8958. (point)))
  8959. (if (and (save-excursion
  8960. (re-search-forward
  8961. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  8962. (not (save-excursion (re-search-forward
  8963. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  8964. (org-update-checkbox-count)
  8965. (if (and l2 (> l2 l1))
  8966. (progn
  8967. (goto-char end)
  8968. (org-update-parent-todo-statistics))
  8969. (goto-char pos)
  8970. (beginning-of-line 1)
  8971. (while (re-search-forward
  8972. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  8973. (point-at-eol) t)
  8974. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  8975. (goto-char pos)
  8976. (move-marker pos nil)))))
  8977. (defvar org-entry-property-inherited-from) ;; defined below
  8978. (defun org-update-parent-todo-statistics ()
  8979. "Update any statistics cookie in the parent of the current headline.
  8980. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  8981. the entire subtree and this will travel up the hierarchy and update
  8982. statistics everywhere."
  8983. (let* ((prop (save-excursion (org-up-heading-safe)
  8984. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  8985. (recursive (or (not org-hierarchical-todo-statistics)
  8986. (and prop (string-match "\\<recursive\\>" prop))))
  8987. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  8988. 0))
  8989. (first t)
  8990. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  8991. level ltoggle l1 new ndel
  8992. (cnt-all 0) (cnt-done 0) is-percent kwd
  8993. checkbox-beg cookie-present)
  8994. (catch 'exit
  8995. (save-excursion
  8996. (beginning-of-line 1)
  8997. (setq ltoggle (funcall outline-level))
  8998. ;; Three situations are to consider:
  8999. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  9000. ;; to the top-level ancestor on the headline;
  9001. ;; 2. If parent has "recursive" property, repeat up to the
  9002. ;; headline setting that property, taking inheritance into
  9003. ;; account;
  9004. ;; 3. Else, move up to direct parent and proceed only once.
  9005. (while (and (setq level (org-up-heading-safe))
  9006. (or recursive first)
  9007. (>= (point) lim))
  9008. (setq first nil cookie-present nil)
  9009. (unless (and level
  9010. (not (string-match
  9011. "\\<checkbox\\>"
  9012. (downcase (or (org-entry-get nil "COOKIE_DATA")
  9013. "")))))
  9014. (throw 'exit nil))
  9015. (while (re-search-forward box-re (point-at-eol) t)
  9016. (setq cnt-all 0 cnt-done 0 cookie-present t)
  9017. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  9018. (save-match-data
  9019. (unless (outline-next-heading) (throw 'exit nil))
  9020. (while (and (looking-at org-complex-heading-regexp)
  9021. (> (setq l1 (length (match-string 1))) level))
  9022. (setq kwd (and (or recursive (= l1 ltoggle))
  9023. (match-string 2)))
  9024. (if (or (eq org-provide-todo-statistics 'all-headlines)
  9025. (and (eq org-provide-todo-statistics t)
  9026. (or (member kwd org-done-keywords)))
  9027. (and (listp org-provide-todo-statistics)
  9028. (stringp (car org-provide-todo-statistics))
  9029. (or (member kwd org-provide-todo-statistics)
  9030. (member kwd org-done-keywords)))
  9031. (and (listp org-provide-todo-statistics)
  9032. (listp (car org-provide-todo-statistics))
  9033. (or (member kwd (car org-provide-todo-statistics))
  9034. (and (member kwd org-done-keywords)
  9035. (member kwd (cadr org-provide-todo-statistics))))))
  9036. (setq cnt-all (1+ cnt-all))
  9037. (and (eq org-provide-todo-statistics t)
  9038. kwd
  9039. (setq cnt-all (1+ cnt-all))))
  9040. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  9041. (member kwd org-done-keywords))
  9042. (and (listp org-provide-todo-statistics)
  9043. (listp (car org-provide-todo-statistics))
  9044. (member kwd org-done-keywords)
  9045. (member kwd (cadr org-provide-todo-statistics)))
  9046. (and (listp org-provide-todo-statistics)
  9047. (stringp (car org-provide-todo-statistics))
  9048. (member kwd org-done-keywords)))
  9049. (setq cnt-done (1+ cnt-done)))
  9050. (outline-next-heading)))
  9051. (setq new
  9052. (if is-percent
  9053. (format "[%d%%]" (floor (* 100.0 cnt-done)
  9054. (max 1 cnt-all)))
  9055. (format "[%d/%d]" cnt-done cnt-all))
  9056. ndel (- (match-end 0) checkbox-beg))
  9057. (goto-char checkbox-beg)
  9058. (insert new)
  9059. (delete-region (point) (+ (point) ndel))
  9060. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  9061. (when cookie-present
  9062. (run-hook-with-args 'org-after-todo-statistics-hook
  9063. cnt-done (- cnt-all cnt-done))))))
  9064. (run-hooks 'org-todo-statistics-hook)))
  9065. (defvar org-after-todo-statistics-hook nil
  9066. "Hook that is called after a TODO statistics cookie has been updated.
  9067. Each function is called with two arguments: the number of not-done entries
  9068. and the number of done entries.
  9069. For example, the following function, when added to this hook, will switch
  9070. an entry to DONE when all children are done, and back to TODO when new
  9071. entries are set to a TODO status. Note that this hook is only called
  9072. when there is a statistics cookie in the headline!
  9073. (defun org-summary-todo (n-done n-not-done)
  9074. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9075. (let (org-log-done org-log-states) ; turn off logging
  9076. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
  9077. (defvar org-todo-statistics-hook nil
  9078. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9079. This hook runs even if there is no statistics cookie present, in which case
  9080. `org-after-todo-statistics-hook' would not run.")
  9081. (defun org-todo-trigger-tag-changes (state)
  9082. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9083. (let ((l org-todo-state-tags-triggers)
  9084. changes)
  9085. (when (or (not state) (equal state ""))
  9086. (setq changes (append changes (cdr (assoc "" l)))))
  9087. (when (and (stringp state) (> (length state) 0))
  9088. (setq changes (append changes (cdr (assoc state l)))))
  9089. (when (member state org-not-done-keywords)
  9090. (setq changes (append changes (cdr (assq 'todo l)))))
  9091. (when (member state org-done-keywords)
  9092. (setq changes (append changes (cdr (assq 'done l)))))
  9093. (dolist (c changes)
  9094. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9095. (defun org-local-logging (value)
  9096. "Get logging settings from a property VALUE."
  9097. ;; Directly set the variables, they are already local.
  9098. (setq org-log-done nil
  9099. org-log-repeat nil
  9100. org-todo-log-states nil)
  9101. (dolist (w (split-string value))
  9102. (let (a)
  9103. (cond
  9104. ((setq a (assoc w org-startup-options))
  9105. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9106. (set (nth 1 a) (nth 2 a))))
  9107. ((setq a (org-extract-log-state-settings w))
  9108. (and (member (car a) org-todo-keywords-1)
  9109. (push a org-todo-log-states)))))))
  9110. (defun org-get-todo-sequence-head (kwd)
  9111. "Return the head of the TODO sequence to which KWD belongs.
  9112. If KWD is not set, check if there is a text property remembering the
  9113. right sequence."
  9114. (let (p)
  9115. (cond
  9116. ((not kwd)
  9117. (or (get-text-property (point-at-bol) 'org-todo-head)
  9118. (progn
  9119. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9120. nil (point-at-eol)))
  9121. (get-text-property p 'org-todo-head))))
  9122. ((not (member kwd org-todo-keywords-1))
  9123. (car org-todo-keywords-1))
  9124. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9125. (defun org-fast-todo-selection (&optional current-state)
  9126. "Fast TODO keyword selection with single keys.
  9127. Returns the new TODO keyword, or nil if no state change should occur.
  9128. When CURRENT-STATE is given and selection letters are not unique globally,
  9129. prefer a state in the current sequence over on in another sequence."
  9130. (let* ((fulltable org-todo-key-alist)
  9131. (head (org-get-todo-sequence-head current-state))
  9132. (done-keywords org-done-keywords) ;; needed for the faces.
  9133. (maxlen (apply 'max (mapcar
  9134. (lambda (x)
  9135. (if (stringp (car x)) (string-width (car x)) 0))
  9136. fulltable)))
  9137. (expert (equal org-use-fast-todo-selection 'expert))
  9138. (prompt "")
  9139. (fwidth (+ maxlen 3 1 3))
  9140. (ncol (/ (- (window-width) 4) fwidth))
  9141. tg cnt e c tbl subtable
  9142. groups ingroup in-current-sequence)
  9143. (save-excursion
  9144. (save-window-excursion
  9145. (if expert
  9146. (set-buffer (get-buffer-create " *Org todo*"))
  9147. (delete-other-windows)
  9148. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9149. (org-switch-to-buffer-other-window " *Org todo*"))
  9150. (erase-buffer)
  9151. (setq-local org-done-keywords done-keywords)
  9152. (setq tbl fulltable cnt 0)
  9153. (while (setq e (pop tbl))
  9154. (cond
  9155. ((equal e '(:startgroup))
  9156. (push '() groups) (setq ingroup t)
  9157. (unless (= cnt 0)
  9158. (setq cnt 0)
  9159. (insert "\n"))
  9160. (setq prompt (concat prompt "{"))
  9161. (insert "{ "))
  9162. ((equal e '(:endgroup))
  9163. (setq ingroup nil cnt 0 in-current-sequence nil)
  9164. (setq prompt (concat prompt "}"))
  9165. (insert "}\n"))
  9166. ((equal e '(:newline))
  9167. (unless (= cnt 0)
  9168. (setq cnt 0)
  9169. (insert "\n")
  9170. (setq e (car tbl))
  9171. (while (equal (car tbl) '(:newline))
  9172. (insert "\n")
  9173. (setq tbl (cdr tbl)))))
  9174. (t
  9175. (setq tg (car e) c (cdr e))
  9176. (if (equal tg head) (setq in-current-sequence t))
  9177. (when ingroup (push tg (car groups)))
  9178. (when in-current-sequence (push e subtable))
  9179. (setq tg (org-add-props tg nil 'face
  9180. (org-get-todo-face tg)))
  9181. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9182. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9183. (insert "[" c "] " tg (make-string
  9184. (- fwidth 4 (length tg)) ?\ ))
  9185. (when (and (= (setq cnt (1+ cnt)) ncol)
  9186. ;; Avoid lines with just a closing delimiter.
  9187. (not (equal (car tbl) '(:endgroup))))
  9188. (insert "\n")
  9189. (when ingroup (insert " "))
  9190. (setq cnt 0)))))
  9191. (insert "\n")
  9192. (goto-char (point-min))
  9193. (unless expert (org-fit-window-to-buffer))
  9194. (message (concat "[a-z..]:Set [SPC]:clear"
  9195. (if expert (concat "\n" prompt) "")))
  9196. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9197. (setq subtable (nreverse subtable))
  9198. (cond
  9199. ((or (= c ?\C-g)
  9200. (and (= c ?q) (not (rassoc c fulltable))))
  9201. (setq quit-flag t))
  9202. ((= c ?\ ) nil)
  9203. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9204. tg (car e))
  9205. tg)
  9206. (t (setq quit-flag t)))))))
  9207. (defun org-entry-is-todo-p ()
  9208. (member (org-get-todo-state) org-not-done-keywords))
  9209. (defun org-entry-is-done-p ()
  9210. (member (org-get-todo-state) org-done-keywords))
  9211. (defun org-get-todo-state ()
  9212. "Return the TODO keyword of the current subtree."
  9213. (save-excursion
  9214. (org-back-to-heading t)
  9215. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9216. (match-end 2)
  9217. (match-string 2))))
  9218. (defun org-at-date-range-p (&optional inactive-ok)
  9219. "Non-nil if point is inside a date range.
  9220. When optional argument INACTIVE-OK is non-nil, also consider
  9221. inactive time ranges.
  9222. When this function returns a non-nil value, match data is set
  9223. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9224. on INACTIVE-OK."
  9225. (interactive)
  9226. (save-excursion
  9227. (catch 'exit
  9228. (let ((pos (point)))
  9229. (skip-chars-backward "^[<\r\n")
  9230. (skip-chars-backward "<[")
  9231. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9232. (>= (match-end 0) pos)
  9233. (throw 'exit t))
  9234. (skip-chars-backward "^<[\r\n")
  9235. (skip-chars-backward "<[")
  9236. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9237. (>= (match-end 0) pos)
  9238. (throw 'exit t)))
  9239. nil)))
  9240. (defun org-get-repeat (&optional timestamp)
  9241. "Check if there is a time-stamp with repeater in this entry.
  9242. Return the repeater, as a string, or nil. Also return nil when
  9243. this function is called before first heading.
  9244. When optional argument TIMESTAMP is a string, extract the
  9245. repeater from there instead."
  9246. (save-match-data
  9247. (cond (timestamp
  9248. (and (string-match org-repeat-re timestamp)
  9249. (match-string-no-properties 1 timestamp)))
  9250. ((org-before-first-heading-p) nil)
  9251. (t
  9252. (save-excursion
  9253. (org-back-to-heading t)
  9254. (let ((end (org-entry-end-position)))
  9255. (catch :repeat
  9256. (while (re-search-forward org-repeat-re end t)
  9257. (when (save-match-data (org-at-timestamp-p 'agenda))
  9258. (throw :repeat (match-string-no-properties 1)))))))))))
  9259. (defvar org-last-changed-timestamp)
  9260. (defvar org-last-inserted-timestamp)
  9261. (defvar org-log-post-message)
  9262. (defvar org-log-note-purpose)
  9263. (defvar org-log-note-how nil)
  9264. (defvar org-log-note-extra)
  9265. (defun org-auto-repeat-maybe (done-word)
  9266. "Check if the current headline contains a repeated time-stamp.
  9267. If yes, set TODO state back to what it was and change the base date
  9268. of repeating deadline/scheduled time stamps to new date.
  9269. This function is run automatically after each state change to a DONE state."
  9270. (let* ((repeat (org-get-repeat))
  9271. (aa (assoc org-last-state org-todo-kwd-alist))
  9272. (interpret (nth 1 aa))
  9273. (head (nth 2 aa))
  9274. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9275. (msg "Entry repeats: ")
  9276. (org-log-done nil)
  9277. (org-todo-log-states nil)
  9278. (end (copy-marker (org-entry-end-position))))
  9279. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9280. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9281. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9282. (and (stringp org-todo-repeat-to-state)
  9283. org-todo-repeat-to-state)
  9284. (and org-todo-repeat-to-state org-last-state))))
  9285. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9286. to-state)
  9287. ((eq interpret 'type) org-last-state)
  9288. (head)
  9289. (t 'none))))
  9290. (org-back-to-heading t)
  9291. (org-add-planning-info nil nil 'closed)
  9292. ;; When `org-log-repeat' is non-nil or entry contains
  9293. ;; a clock, set LAST_REPEAT property.
  9294. (when (or org-log-repeat
  9295. (catch :clock
  9296. (save-excursion
  9297. (while (re-search-forward org-clock-line-re end t)
  9298. (when (org-at-clock-log-p) (throw :clock t))))))
  9299. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9300. (org-time-stamp-format t t))))
  9301. (when org-log-repeat
  9302. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  9303. (memq 'org-add-log-note post-command-hook))
  9304. ;; We are already setup for some record.
  9305. (when (eq org-log-repeat 'note)
  9306. ;; Make sure we take a note, not only a time stamp.
  9307. (setq org-log-note-how 'note))
  9308. ;; Set up for taking a record.
  9309. (org-add-log-setup 'state
  9310. (or done-word (car org-done-keywords))
  9311. org-last-state
  9312. org-log-repeat)))
  9313. ;; Time-stamps without a repeater are usually skipped. However,
  9314. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9315. ;; longer relevant.
  9316. (save-excursion
  9317. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9318. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9319. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9320. ;; Update every time-stamp with a repeater in the entry.
  9321. (let ((planning-re (regexp-opt
  9322. (list org-scheduled-string org-deadline-string))))
  9323. (while (re-search-forward org-repeat-re end t)
  9324. (let* ((ts (match-string 0))
  9325. (type (if (not (org-at-planning-p)) "Plain:"
  9326. (save-excursion
  9327. (re-search-backward
  9328. planning-re (line-beginning-position) t)
  9329. (match-string 0)))))
  9330. (when (and (org-at-timestamp-p 'agenda)
  9331. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9332. (let ((n (string-to-number (match-string 2 ts)))
  9333. (what (match-string 3 ts)))
  9334. (when (equal what "w") (setq n (* n 7) what "d"))
  9335. (when (and (equal what "h")
  9336. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9337. ts)))
  9338. (user-error
  9339. "Cannot repeat in %d hour(s) because no hour has been set"
  9340. n))
  9341. ;; Preparation, see if we need to modify the start
  9342. ;; date for the change.
  9343. (when (match-end 1)
  9344. (let ((time (save-match-data (org-time-string-to-time ts)))
  9345. (repeater-type (match-string 1 ts)))
  9346. (cond
  9347. ((equal "." repeater-type)
  9348. ;; Shift starting date to today, or now if
  9349. ;; repeater is by hours.
  9350. (if (equal what "h")
  9351. (org-timestamp-change
  9352. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  9353. (org-timestamp-change
  9354. (- (org-today) (time-to-days time)) 'day)))
  9355. ((equal "+" repeater-type)
  9356. (let ((nshiftmax 10)
  9357. (nshift 0))
  9358. (while (or (= nshift 0)
  9359. (not (org-time-less-p nil time)))
  9360. (when (= nshiftmax (cl-incf nshift))
  9361. (or (y-or-n-p
  9362. (format "%d repeater intervals were not \
  9363. enough to shift date past today. Continue? "
  9364. nshift))
  9365. (user-error "Abort")))
  9366. (org-timestamp-change n (cdr (assoc what whata)))
  9367. (org-in-regexp org-ts-regexp3)
  9368. (setq ts (match-string 1))
  9369. (setq time
  9370. (save-match-data
  9371. (org-time-string-to-time ts)))))
  9372. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9373. ;; Rematch, so that we have everything in place
  9374. ;; for the real shift.
  9375. (org-in-regexp org-ts-regexp3)
  9376. (setq ts (match-string 1))
  9377. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9378. ts)))))
  9379. (save-excursion
  9380. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9381. (setq msg
  9382. (concat msg type " " org-last-changed-timestamp " ")))))))
  9383. (run-hooks 'org-todo-repeat-hook)
  9384. (setq org-log-post-message msg)
  9385. (message msg))))
  9386. (defun org-show-todo-tree (arg)
  9387. "Make a compact tree which shows all headlines marked with TODO.
  9388. The tree will show the lines where the regexp matches, and all higher
  9389. headlines above the match.
  9390. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9391. With a numeric prefix N, construct a sparse tree for the Nth element
  9392. of `org-todo-keywords-1'."
  9393. (interactive "P")
  9394. (let ((case-fold-search nil)
  9395. (kwd-re
  9396. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9397. ((equal arg '(4))
  9398. (let ((kwd
  9399. (completing-read "Keyword (or KWD1|KWD2|...): "
  9400. (mapcar #'list org-todo-keywords-1))))
  9401. (concat "\\("
  9402. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9403. "\\)\\>")))
  9404. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9405. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9406. org-todo-keywords-1)))
  9407. (t (user-error "Invalid prefix argument: %s" arg)))))
  9408. (message "%d TODO entries found"
  9409. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9410. (defun org--deadline-or-schedule (arg type time)
  9411. "Insert DEADLINE or SCHEDULE information in current entry.
  9412. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9413. `org-schedule' for information about ARG and TIME arguments."
  9414. (let* ((deadline? (eq type 'deadline))
  9415. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9416. (log (if deadline? org-log-redeadline org-log-reschedule))
  9417. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9418. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9419. ;; Save repeater cookie from either TIME or current scheduled
  9420. ;; time stamp. We are going to insert it back at the end of
  9421. ;; the process.
  9422. (repeater (or (and (org-string-nw-p time)
  9423. ;; We use `org-repeat-re' because we need
  9424. ;; to tell the difference between a real
  9425. ;; repeater and a time delta, e.g. "+2d".
  9426. (string-match org-repeat-re time)
  9427. (match-string 1 time))
  9428. (and (org-string-nw-p old-date)
  9429. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9430. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9431. old-date)
  9432. (match-string 1 old-date)))))
  9433. (pcase arg
  9434. (`(4)
  9435. (if (not old-date)
  9436. (message (if deadline? "Entry had no deadline to remove"
  9437. "Entry was not scheduled"))
  9438. (when (and old-date log)
  9439. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9440. nil old-date log))
  9441. (org-remove-timestamp-with-keyword keyword)
  9442. (message (if deadline? "Entry no longer has a deadline."
  9443. "Entry is no longer scheduled."))))
  9444. (`(16)
  9445. (save-excursion
  9446. (org-back-to-heading t)
  9447. (let ((regexp (if deadline? org-deadline-time-regexp
  9448. org-scheduled-time-regexp)))
  9449. (if (not (re-search-forward regexp (line-end-position 2) t))
  9450. (user-error (if deadline? "No deadline information to update"
  9451. "No scheduled information to update"))
  9452. (let* ((rpl0 (match-string 1))
  9453. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9454. (msg (if deadline? "Warn starting from" "Delay until")))
  9455. (replace-match
  9456. (concat keyword
  9457. " <" rpl
  9458. (format " -%dd"
  9459. (abs (- (time-to-days
  9460. (save-match-data
  9461. (org-read-date
  9462. nil t nil msg old-date-time)))
  9463. (time-to-days old-date-time))))
  9464. ">") t t))))))
  9465. (_
  9466. (org-add-planning-info type time 'closed)
  9467. (when (and old-date
  9468. log
  9469. (not (equal old-date org-last-inserted-timestamp)))
  9470. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9471. org-last-inserted-timestamp
  9472. old-date
  9473. log))
  9474. (when repeater
  9475. (save-excursion
  9476. (org-back-to-heading t)
  9477. (when (re-search-forward
  9478. (concat keyword " " org-last-inserted-timestamp)
  9479. (line-end-position 2)
  9480. t)
  9481. (goto-char (1- (match-end 0)))
  9482. (insert " " repeater)
  9483. (setq org-last-inserted-timestamp
  9484. (concat (substring org-last-inserted-timestamp 0 -1)
  9485. " " repeater
  9486. (substring org-last-inserted-timestamp -1))))))
  9487. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9488. org-last-inserted-timestamp)))))
  9489. (defun org-deadline (arg &optional time)
  9490. "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  9491. When called interactively, this command pops up the Emacs calendar to let
  9492. the user select a date.
  9493. With one universal prefix argument, remove any deadline from the item.
  9494. With two universal prefix arguments, prompt for a warning delay.
  9495. With argument TIME, set the deadline at the corresponding date. TIME
  9496. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9497. (interactive "P")
  9498. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9499. (org-map-entries
  9500. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9501. nil
  9502. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9503. 'region-start-level
  9504. 'region)
  9505. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9506. (org--deadline-or-schedule arg 'deadline time)))
  9507. (defun org-schedule (arg &optional time)
  9508. "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  9509. When called interactively, this command pops up the Emacs calendar to let
  9510. the user select a date.
  9511. With one universal prefix argument, remove any scheduling date from the item.
  9512. With two universal prefix arguments, prompt for a delay cookie.
  9513. With argument TIME, scheduled at the corresponding date. TIME can
  9514. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9515. (interactive "P")
  9516. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9517. (org-map-entries
  9518. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9519. nil
  9520. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9521. 'region-start-level
  9522. 'region)
  9523. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9524. (org--deadline-or-schedule arg 'scheduled time)))
  9525. (defun org-get-scheduled-time (pom &optional inherit)
  9526. "Get the scheduled time as a time tuple, of a format suitable
  9527. for calling org-schedule with, or if there is no scheduling,
  9528. returns nil."
  9529. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9530. (when time
  9531. (org-time-string-to-time time))))
  9532. (defun org-get-deadline-time (pom &optional inherit)
  9533. "Get the deadline as a time tuple, of a format suitable for
  9534. calling org-deadline with, or if there is no scheduling, returns
  9535. nil."
  9536. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9537. (when time
  9538. (org-time-string-to-time time))))
  9539. (defun org-remove-timestamp-with-keyword (keyword)
  9540. "Remove all time stamps with KEYWORD in the current entry."
  9541. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9542. beg)
  9543. (save-excursion
  9544. (org-back-to-heading t)
  9545. (setq beg (point))
  9546. (outline-next-heading)
  9547. (while (re-search-backward re beg t)
  9548. (replace-match "")
  9549. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9550. (equal (char-before) ?\ ))
  9551. (backward-delete-char 1)
  9552. (when (string-match "^[ \t]*$" (buffer-substring
  9553. (point-at-bol) (point-at-eol)))
  9554. (delete-region (point-at-bol)
  9555. (min (point-max) (1+ (point-at-eol))))))))))
  9556. (defvar org-time-was-given) ; dynamically scoped parameter
  9557. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9558. (defun org-at-planning-p ()
  9559. "Non-nil when point is on a planning info line."
  9560. ;; This is as accurate and faster than `org-element-at-point' since
  9561. ;; planning info location is fixed in the section.
  9562. (org-with-wide-buffer
  9563. (beginning-of-line)
  9564. (and (looking-at-p org-planning-line-re)
  9565. (eq (point)
  9566. (ignore-errors
  9567. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9568. (org-back-to-heading t)
  9569. (org-with-limited-levels (org-back-to-heading t)))
  9570. (line-beginning-position 2))))))
  9571. (defun org-add-planning-info (what &optional time &rest remove)
  9572. "Insert new timestamp with keyword in the planning line.
  9573. WHAT indicates what kind of time stamp to add. It is a symbol
  9574. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9575. the time to use. If none is given, the user is prompted for
  9576. a date. REMOVE indicates what kind of entries to remove. An old
  9577. WHAT entry will also be removed."
  9578. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9579. (when (and (memq what '(scheduled deadline))
  9580. (or (not time)
  9581. (and (stringp time)
  9582. (string-match "^[-+]+[0-9]" time))))
  9583. ;; Try to get a default date/time from existing timestamp
  9584. (save-excursion
  9585. (org-back-to-heading t)
  9586. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9587. (when (re-search-forward (if (eq what 'scheduled)
  9588. org-scheduled-time-regexp
  9589. org-deadline-time-regexp)
  9590. end t)
  9591. (setq ts (match-string 1)
  9592. default-time (org-time-string-to-time ts)
  9593. default-input (and ts (org-get-compact-tod ts)))))))
  9594. (when what
  9595. (setq time
  9596. (if (stringp time)
  9597. ;; This is a string (relative or absolute), set
  9598. ;; proper date.
  9599. (apply #'encode-time
  9600. (org-read-date-analyze
  9601. time default-time (decode-time default-time)))
  9602. ;; If necessary, get the time from the user
  9603. (or time (org-read-date nil 'to-time nil
  9604. (cl-case what
  9605. (deadline "DEADLINE")
  9606. (scheduled "SCHEDULED")
  9607. (otherwise nil))
  9608. default-time default-input)))))
  9609. (org-with-wide-buffer
  9610. (org-back-to-heading t)
  9611. (let ((planning? (save-excursion
  9612. (forward-line)
  9613. (looking-at-p org-planning-line-re))))
  9614. (cond
  9615. (planning?
  9616. (forward-line)
  9617. ;; Move to current indentation.
  9618. (skip-chars-forward " \t")
  9619. ;; Check if we have to remove something.
  9620. (dolist (type (if what (cons what remove) remove))
  9621. (save-excursion
  9622. (when (re-search-forward
  9623. (cl-case type
  9624. (closed org-closed-time-regexp)
  9625. (deadline org-deadline-time-regexp)
  9626. (scheduled org-scheduled-time-regexp)
  9627. (otherwise (error "Invalid planning type: %s" type)))
  9628. (line-end-position)
  9629. t)
  9630. ;; Delete until next keyword or end of line.
  9631. (delete-region
  9632. (match-beginning 0)
  9633. (if (re-search-forward org-keyword-time-not-clock-regexp
  9634. (line-end-position)
  9635. t)
  9636. (match-beginning 0)
  9637. (line-end-position))))))
  9638. ;; If there is nothing more to add and no more keyword is
  9639. ;; left, remove the line completely.
  9640. (if (and (looking-at-p "[ \t]*$") (not what))
  9641. (delete-region (line-end-position 0)
  9642. (line-end-position))
  9643. ;; If we removed last keyword, do not leave trailing white
  9644. ;; space at the end of line.
  9645. (let ((p (point)))
  9646. (save-excursion
  9647. (end-of-line)
  9648. (unless (= (skip-chars-backward " \t" p) 0)
  9649. (delete-region (point) (line-end-position)))))))
  9650. (what
  9651. (end-of-line)
  9652. (insert "\n")
  9653. (when org-adapt-indentation
  9654. (indent-to-column (1+ (org-outline-level)))))
  9655. (t nil)))
  9656. (when what
  9657. ;; Insert planning keyword.
  9658. (insert (cl-case what
  9659. (closed org-closed-string)
  9660. (deadline org-deadline-string)
  9661. (scheduled org-scheduled-string)
  9662. (otherwise (error "Invalid planning type: %s" what)))
  9663. " ")
  9664. ;; Insert associated timestamp.
  9665. (let ((ts (org-insert-time-stamp
  9666. time
  9667. (or org-time-was-given
  9668. (and (eq what 'closed) org-log-done-with-time))
  9669. (eq what 'closed)
  9670. nil nil (list org-end-time-was-given))))
  9671. (unless (eolp) (insert " "))
  9672. ts)))))
  9673. (defvar org-log-note-marker (make-marker)
  9674. "Marker pointing at the entry where the note is to be inserted.")
  9675. (defvar org-log-note-purpose nil)
  9676. (defvar org-log-note-state nil)
  9677. (defvar org-log-note-previous-state nil)
  9678. (defvar org-log-note-extra nil)
  9679. (defvar org-log-note-window-configuration nil)
  9680. (defvar org-log-note-return-to (make-marker))
  9681. (defvar org-log-note-effective-time nil
  9682. "Remembered current time.
  9683. So that dynamically scoped `org-extend-today-until' affects
  9684. timestamps in state change log.")
  9685. (defvar org-log-post-message nil
  9686. "Message to be displayed after a log note has been stored.
  9687. The auto-repeater uses this.")
  9688. (defun org-add-note ()
  9689. "Add a note to the current entry.
  9690. This is done in the same way as adding a state change note."
  9691. (interactive)
  9692. (org-add-log-setup 'note))
  9693. (defun org-log-beginning (&optional create)
  9694. "Return expected start of log notes in current entry.
  9695. When optional argument CREATE is non-nil, the function creates
  9696. a drawer to store notes, if necessary. Returned position ignores
  9697. narrowing."
  9698. (org-with-wide-buffer
  9699. (let ((drawer (org-log-into-drawer)))
  9700. (cond
  9701. (drawer
  9702. (org-end-of-meta-data)
  9703. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9704. (end (if (org-at-heading-p) (point)
  9705. (save-excursion (outline-next-heading) (point))))
  9706. (case-fold-search t))
  9707. (catch 'exit
  9708. ;; Try to find existing drawer.
  9709. (while (re-search-forward regexp end t)
  9710. (let ((element (org-element-at-point)))
  9711. (when (eq (org-element-type element) 'drawer)
  9712. (let ((cend (org-element-property :contents-end element)))
  9713. (when (and (not org-log-states-order-reversed) cend)
  9714. (goto-char cend)))
  9715. (throw 'exit nil))))
  9716. ;; No drawer found. Create one, if permitted.
  9717. (when create
  9718. (unless (bolp) (insert "\n"))
  9719. (let ((beg (point)))
  9720. (insert ":" drawer ":\n:END:\n")
  9721. (org-indent-region beg (point))
  9722. (org-flag-region (line-end-position -1) (1- (point)) t 'outline))
  9723. (end-of-line -1)))))
  9724. (t
  9725. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9726. (skip-chars-forward " \t\n")
  9727. (beginning-of-line)
  9728. (unless org-log-states-order-reversed
  9729. (org-skip-over-state-notes)
  9730. (skip-chars-backward " \t\n")
  9731. (forward-line)))))
  9732. (if (bolp) (point) (line-beginning-position 2))))
  9733. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9734. "Set up the post command hook to take a note.
  9735. If this is about to TODO state change, the new state is expected in STATE.
  9736. HOW is an indicator what kind of note should be created.
  9737. EXTRA is additional text that will be inserted into the notes buffer."
  9738. (move-marker org-log-note-marker (point))
  9739. (setq org-log-note-purpose purpose
  9740. org-log-note-state state
  9741. org-log-note-previous-state prev-state
  9742. org-log-note-how how
  9743. org-log-note-extra extra
  9744. org-log-note-effective-time (org-current-effective-time))
  9745. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9746. (defun org-skip-over-state-notes ()
  9747. "Skip past the list of State notes in an entry."
  9748. (when (ignore-errors (goto-char (org-in-item-p)))
  9749. (let* ((struct (org-list-struct))
  9750. (prevs (org-list-prevs-alist struct))
  9751. (regexp
  9752. (concat "[ \t]*- +"
  9753. (replace-regexp-in-string
  9754. " +" " +"
  9755. (org-replace-escapes
  9756. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9757. `(("%d" . ,org-ts-regexp-inactive)
  9758. ("%D" . ,org-ts-regexp)
  9759. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9760. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9761. ("%t" . ,org-ts-regexp-inactive)
  9762. ("%T" . ,org-ts-regexp)
  9763. ("%u" . ".*?")
  9764. ("%U" . ".*?")))))))
  9765. (while (looking-at-p regexp)
  9766. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9767. (org-list-get-item-end (point) struct)))))))
  9768. (defun org-add-log-note (&optional _purpose)
  9769. "Pop up a window for taking a note, and add this note later."
  9770. (remove-hook 'post-command-hook 'org-add-log-note)
  9771. (setq org-log-note-window-configuration (current-window-configuration))
  9772. (delete-other-windows)
  9773. (move-marker org-log-note-return-to (point))
  9774. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9775. (goto-char org-log-note-marker)
  9776. (org-switch-to-buffer-other-window "*Org Note*")
  9777. (erase-buffer)
  9778. (if (memq org-log-note-how '(time state))
  9779. (org-store-log-note)
  9780. (let ((org-inhibit-startup t)) (org-mode))
  9781. (insert (format "# Insert note for %s.
  9782. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9783. (cl-case org-log-note-purpose
  9784. (clock-out "stopped clock")
  9785. (done "closed todo item")
  9786. (reschedule "rescheduling")
  9787. (delschedule "no longer scheduled")
  9788. (redeadline "changing deadline")
  9789. (deldeadline "removing deadline")
  9790. (refile "refiling")
  9791. (note "this entry")
  9792. (state
  9793. (format "state change from \"%s\" to \"%s\""
  9794. (or org-log-note-previous-state "")
  9795. (or org-log-note-state "")))
  9796. (t (error "This should not happen")))))
  9797. (when org-log-note-extra (insert org-log-note-extra))
  9798. (setq-local org-finish-function 'org-store-log-note)
  9799. (run-hooks 'org-log-buffer-setup-hook)))
  9800. (defvar org-note-abort nil) ; dynamically scoped
  9801. (defun org-store-log-note ()
  9802. "Finish taking a log note, and insert it to where it belongs."
  9803. (let ((txt (prog1 (buffer-string)
  9804. (kill-buffer)))
  9805. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9806. lines)
  9807. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9808. (setq txt (replace-match "" t t txt)))
  9809. (when (string-match "\\s-+\\'" txt)
  9810. (setq txt (replace-match "" t t txt)))
  9811. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9812. (when (org-string-nw-p note)
  9813. (setq note
  9814. (org-replace-escapes
  9815. note
  9816. (list (cons "%u" (user-login-name))
  9817. (cons "%U" user-full-name)
  9818. (cons "%t" (format-time-string
  9819. (org-time-stamp-format 'long 'inactive)
  9820. org-log-note-effective-time))
  9821. (cons "%T" (format-time-string
  9822. (org-time-stamp-format 'long nil)
  9823. org-log-note-effective-time))
  9824. (cons "%d" (format-time-string
  9825. (org-time-stamp-format nil 'inactive)
  9826. org-log-note-effective-time))
  9827. (cons "%D" (format-time-string
  9828. (org-time-stamp-format nil nil)
  9829. org-log-note-effective-time))
  9830. (cons "%s" (cond
  9831. ((not org-log-note-state) "")
  9832. ((string-match-p org-ts-regexp
  9833. org-log-note-state)
  9834. (format "\"[%s]\""
  9835. (substring org-log-note-state 1 -1)))
  9836. (t (format "\"%s\"" org-log-note-state))))
  9837. (cons "%S"
  9838. (cond
  9839. ((not org-log-note-previous-state) "")
  9840. ((string-match-p org-ts-regexp
  9841. org-log-note-previous-state)
  9842. (format "\"[%s]\""
  9843. (substring
  9844. org-log-note-previous-state 1 -1)))
  9845. (t (format "\"%s\""
  9846. org-log-note-previous-state)))))))
  9847. (when lines (setq note (concat note " \\\\")))
  9848. (push note lines))
  9849. (when (and lines (not org-note-abort))
  9850. (with-current-buffer (marker-buffer org-log-note-marker)
  9851. (org-with-wide-buffer
  9852. ;; Find location for the new note.
  9853. (goto-char org-log-note-marker)
  9854. (set-marker org-log-note-marker nil)
  9855. ;; Note associated to a clock is to be located right after
  9856. ;; the clock. Do not move point.
  9857. (unless (eq org-log-note-purpose 'clock-out)
  9858. (goto-char (org-log-beginning t)))
  9859. ;; Make sure point is at the beginning of an empty line.
  9860. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  9861. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  9862. ;; In an existing list, add a new item at the top level.
  9863. ;; Otherwise, indent line like a regular one.
  9864. (let ((itemp (org-in-item-p)))
  9865. (if itemp
  9866. (indent-line-to
  9867. (let ((struct (save-excursion
  9868. (goto-char itemp) (org-list-struct))))
  9869. (org-list-get-ind (org-list-get-top-point struct) struct)))
  9870. (org-indent-line)))
  9871. (insert (org-list-bullet-string "-") (pop lines))
  9872. (let ((ind (org-list-item-body-column (line-beginning-position))))
  9873. (dolist (line lines)
  9874. (insert "\n")
  9875. (indent-line-to ind)
  9876. (insert line)))
  9877. (message "Note stored")
  9878. (org-back-to-heading t))
  9879. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  9880. ;; from within `org-add-log-note' because `buffer-undo-list'
  9881. ;; is then modified outside of `org-with-remote-undo'.
  9882. (when (eq this-command 'org-agenda-todo)
  9883. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  9884. ;; Don't add undo information when called from `org-agenda-todo'.
  9885. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  9886. (set-window-configuration org-log-note-window-configuration)
  9887. (with-current-buffer (marker-buffer org-log-note-return-to)
  9888. (goto-char org-log-note-return-to))
  9889. (move-marker org-log-note-return-to nil)
  9890. (when org-log-post-message (message "%s" org-log-post-message))))
  9891. (defun org-remove-empty-drawer-at (pos)
  9892. "Remove an empty drawer at position POS.
  9893. POS may also be a marker."
  9894. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  9895. (org-with-wide-buffer
  9896. (goto-char pos)
  9897. (let ((drawer (org-element-at-point)))
  9898. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  9899. (not (org-element-property :contents-begin drawer)))
  9900. (delete-region (org-element-property :begin drawer)
  9901. (progn (goto-char (org-element-property :end drawer))
  9902. (skip-chars-backward " \r\t\n")
  9903. (forward-line)
  9904. (point))))))))
  9905. (defvar org-ts-type nil)
  9906. (defun org-sparse-tree (&optional arg type)
  9907. "Create a sparse tree, prompt for the details.
  9908. This command can create sparse trees. You first need to select the type
  9909. of match used to create the tree:
  9910. t Show all TODO entries.
  9911. T Show entries with a specific TODO keyword.
  9912. m Show entries selected by a tags/property match.
  9913. p Enter a property name and its value (both with completion on existing
  9914. names/values) and show entries with that property.
  9915. r Show entries matching a regular expression (`/' can be used as well).
  9916. b Show deadlines and scheduled items before a date.
  9917. a Show deadlines and scheduled items after a date.
  9918. d Show deadlines due within `org-deadline-warning-days'.
  9919. D Show deadlines and scheduled items between a date range."
  9920. (interactive "P")
  9921. (setq type (or type org-sparse-tree-default-date-type))
  9922. (setq org-ts-type type)
  9923. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  9924. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  9925. [c]ycle through date types: %s"
  9926. (cl-case type
  9927. (all "all timestamps")
  9928. (scheduled "only scheduled")
  9929. (deadline "only deadline")
  9930. (active "only active timestamps")
  9931. (inactive "only inactive timestamps")
  9932. (closed "with a closed time-stamp")
  9933. (otherwise "scheduled/deadline")))
  9934. (let ((answer (read-char-exclusive)))
  9935. (cl-case answer
  9936. (?c
  9937. (org-sparse-tree
  9938. arg
  9939. (cadr
  9940. (memq type '(nil all scheduled deadline active inactive closed)))))
  9941. (?d (call-interactively 'org-check-deadlines))
  9942. (?b (call-interactively 'org-check-before-date))
  9943. (?a (call-interactively 'org-check-after-date))
  9944. (?D (call-interactively 'org-check-dates-range))
  9945. (?t (call-interactively 'org-show-todo-tree))
  9946. (?T (org-show-todo-tree '(4)))
  9947. (?m (call-interactively 'org-match-sparse-tree))
  9948. ((?p ?P)
  9949. (let* ((kwd (completing-read
  9950. "Property: " (mapcar #'list (org-buffer-property-keys))))
  9951. (value (completing-read
  9952. "Value: " (mapcar #'list (org-property-values kwd)))))
  9953. (unless (string-match "\\`{.*}\\'" value)
  9954. (setq value (concat "\"" value "\"")))
  9955. (org-match-sparse-tree arg (concat kwd "=" value))))
  9956. ((?r ?R ?/) (call-interactively 'org-occur))
  9957. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  9958. (defvar-local org-occur-highlights nil
  9959. "List of overlays used for occur matches.")
  9960. (defvar-local org-occur-parameters nil
  9961. "Parameters of the active org-occur calls.
  9962. This is a list, each call to org-occur pushes as cons cell,
  9963. containing the regular expression and the callback, onto the list.
  9964. The list can contain several entries if `org-occur' has been called
  9965. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  9966. will only contain one set of parameters. When the highlights are
  9967. removed (for example with `C-c C-c', or with the next edit (depending
  9968. on `org-remove-highlights-with-change'), this variable is emptied
  9969. as well.")
  9970. (defun org-occur (regexp &optional keep-previous callback)
  9971. "Make a compact tree showing all matches of REGEXP.
  9972. The tree will show the lines where the regexp matches, and any other context
  9973. defined in `org-show-context-detail', which see.
  9974. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  9975. done by a previous call to `org-occur' will be kept, to allow stacking of
  9976. calls to this command.
  9977. Optional argument CALLBACK can be a function of no argument. In this case,
  9978. it is called with point at the end of the match, match data being set
  9979. accordingly. Current match is shown only if the return value is non-nil.
  9980. The function must neither move point nor alter narrowing."
  9981. (interactive "sRegexp: \nP")
  9982. (when (equal regexp "")
  9983. (user-error "Regexp cannot be empty"))
  9984. (unless keep-previous
  9985. (org-remove-occur-highlights nil nil t))
  9986. (push (cons regexp callback) org-occur-parameters)
  9987. (let ((cnt 0))
  9988. (save-excursion
  9989. (goto-char (point-min))
  9990. (when (or (not keep-previous) ; do not want to keep
  9991. (not org-occur-highlights)) ; no previous matches
  9992. ;; hide everything
  9993. (org-overview))
  9994. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  9995. (isearch-no-upper-case-p regexp t)
  9996. org-occur-case-fold-search)))
  9997. (while (re-search-forward regexp nil t)
  9998. (when (or (not callback)
  9999. (save-match-data (funcall callback)))
  10000. (setq cnt (1+ cnt))
  10001. (when org-highlight-sparse-tree-matches
  10002. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  10003. (org-show-context 'occur-tree)))))
  10004. (when org-remove-highlights-with-change
  10005. (add-hook 'before-change-functions 'org-remove-occur-highlights
  10006. nil 'local))
  10007. (unless org-sparse-tree-open-archived-trees
  10008. (org-hide-archived-subtrees (point-min) (point-max)))
  10009. (run-hooks 'org-occur-hook)
  10010. (when (called-interactively-p 'interactive)
  10011. (message "%d match(es) for regexp %s" cnt regexp))
  10012. cnt))
  10013. (defun org-occur-next-match (&optional n _reset)
  10014. "Function for `next-error-function' to find sparse tree matches.
  10015. N is the number of matches to move, when negative move backwards.
  10016. This function always goes back to the starting point when no
  10017. match is found."
  10018. (let* ((limit (if (< n 0) (point-min) (point-max)))
  10019. (search-func (if (< n 0)
  10020. 'previous-single-char-property-change
  10021. 'next-single-char-property-change))
  10022. (n (abs n))
  10023. (pos (point))
  10024. p1)
  10025. (catch 'exit
  10026. (while (setq p1 (funcall search-func (point) 'org-type))
  10027. (when (equal p1 limit)
  10028. (goto-char pos)
  10029. (user-error "No more matches"))
  10030. (when (equal (get-char-property p1 'org-type) 'org-occur)
  10031. (setq n (1- n))
  10032. (when (= n 0)
  10033. (goto-char p1)
  10034. (throw 'exit (point))))
  10035. (goto-char p1))
  10036. (goto-char p1)
  10037. (user-error "No more matches"))))
  10038. (defun org-highlight-new-match (beg end)
  10039. "Highlight from BEG to END and mark the highlight is an occur headline."
  10040. (let ((ov (make-overlay beg end)))
  10041. (overlay-put ov 'face 'secondary-selection)
  10042. (overlay-put ov 'org-type 'org-occur)
  10043. (push ov org-occur-highlights)))
  10044. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10045. "Remove the occur highlights from the buffer.
  10046. BEG and END are ignored. If NOREMOVE is nil, remove this function
  10047. from the `before-change-functions' in the current buffer."
  10048. (interactive)
  10049. (unless org-inhibit-highlight-removal
  10050. (mapc #'delete-overlay org-occur-highlights)
  10051. (setq org-occur-highlights nil)
  10052. (setq org-occur-parameters nil)
  10053. (unless noremove
  10054. (remove-hook 'before-change-functions
  10055. 'org-remove-occur-highlights 'local))))
  10056. ;;;; Priorities
  10057. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  10058. "Regular expression matching the priority indicator.
  10059. A priority indicator can be e.g. [#A] or [#1].
  10060. This regular expression matches these groups:
  10061. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  10062. 1 : the priority cookie, e.g. \"[#A]\"
  10063. 2 : the value of the priority cookie, e.g. \"A\".")
  10064. (defun org-priority-up ()
  10065. "Increase the priority of the current item."
  10066. (interactive)
  10067. (org-priority 'up))
  10068. (defun org-priority-down ()
  10069. "Decrease the priority of the current item."
  10070. (interactive)
  10071. (org-priority 'down))
  10072. (defun org-priority (&optional action show)
  10073. "Change the priority of an item.
  10074. When called interactively with a `\\[universal-argument]' prefix,
  10075. show the priority in the minibuffer instead of changing it.
  10076. When called programmatically, ACTION can be `set', `up', `down',
  10077. or a character."
  10078. (interactive "P")
  10079. (when show
  10080. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10081. ;; passed the SHOW argument should be removed.
  10082. (warn "`org-priority' called with deprecated SHOW argument"))
  10083. (if (equal action '(4))
  10084. (org-priority-show)
  10085. (unless org-priority-enable-commands
  10086. (user-error "Priority commands are disabled"))
  10087. (setq action (or action 'set))
  10088. (let ((nump (< org-priority-lowest 65))
  10089. current new news have remove)
  10090. (save-excursion
  10091. (org-back-to-heading t)
  10092. (when (looking-at org-priority-regexp)
  10093. (let ((ms (match-string 2)))
  10094. (setq current (org-priority-to-value ms)
  10095. have t)))
  10096. (cond
  10097. ((eq action 'remove)
  10098. (setq remove t new ?\ ))
  10099. ((or (eq action 'set)
  10100. (integerp action))
  10101. (if (not (eq action 'set))
  10102. (setq new action)
  10103. (setq
  10104. new
  10105. (if nump
  10106. (string-to-number
  10107. (read-string (format "Priority %s-%s, SPC to remove: "
  10108. (number-to-string org-priority-highest)
  10109. (number-to-string org-priority-lowest))))
  10110. (progn (message "Priority %c-%c, SPC to remove: "
  10111. org-priority-highest org-priority-lowest)
  10112. (save-match-data
  10113. (setq new (read-char-exclusive)))))))
  10114. (when (and (= (upcase org-priority-highest) org-priority-highest)
  10115. (= (upcase org-priority-lowest) org-priority-lowest))
  10116. (setq new (upcase new)))
  10117. (cond ((equal new ?\s) (setq remove t))
  10118. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  10119. (user-error
  10120. (if nump
  10121. "Priority must be between `%s' and `%s'"
  10122. "Priority must be between `%c' and `%c'")
  10123. org-priority-highest org-priority-lowest))))
  10124. ((eq action 'up)
  10125. (setq new (if have
  10126. (1- current) ; normal cycling
  10127. ;; last priority was empty
  10128. (if (eq last-command this-command)
  10129. org-priority-lowest ; wrap around empty to lowest
  10130. ;; default
  10131. (if org-priority-start-cycle-with-default
  10132. org-priority-default
  10133. (1- org-priority-default))))))
  10134. ((eq action 'down)
  10135. (setq new (if have
  10136. (1+ current) ; normal cycling
  10137. ;; last priority was empty
  10138. (if (eq last-command this-command)
  10139. org-priority-highest ; wrap around empty to highest
  10140. ;; default
  10141. (if org-priority-start-cycle-with-default
  10142. org-priority-default
  10143. (1+ org-priority-default))))))
  10144. (t (user-error "Invalid action")))
  10145. (when (or (< (upcase new) org-priority-highest)
  10146. (> (upcase new) org-priority-lowest))
  10147. (if (and (memq action '(up down))
  10148. (not have) (not (eq last-command this-command)))
  10149. ;; `new' is from default priority
  10150. (error
  10151. "The default can not be set, see `org-priority-default' why")
  10152. ;; normal cycling: `new' is beyond highest/lowest priority
  10153. ;; and is wrapped around to the empty priority
  10154. (setq remove t)))
  10155. ;; Numerical priorities are limited to 64, beyond that number,
  10156. ;; assume the priority cookie is a character.
  10157. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  10158. (if have
  10159. (if remove
  10160. (replace-match "" t t nil 1)
  10161. (replace-match news t t nil 2))
  10162. (if remove
  10163. (user-error "No priority cookie found in line")
  10164. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10165. (if (match-end 2)
  10166. (progn
  10167. (goto-char (match-end 2))
  10168. (insert " [#" news "]"))
  10169. (goto-char (match-beginning 3))
  10170. (insert "[#" news "] "))))
  10171. (org-align-tags))
  10172. (if remove
  10173. (message "Priority removed")
  10174. (message "Priority of current item set to %s" news)))))
  10175. (defalias 'org-show-priority 'org-priority-show)
  10176. (defun org-priority-show ()
  10177. "Show the priority of the current item.
  10178. This priority is composed of the main priority given with the [#A] cookies,
  10179. and by additional input from the age of a schedules or deadline entry."
  10180. (interactive)
  10181. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10182. (org-get-at-bol 'priority)
  10183. (save-excursion
  10184. (save-match-data
  10185. (beginning-of-line)
  10186. (and (looking-at org-heading-regexp)
  10187. (org-get-priority (match-string 0))))))))
  10188. (message "Priority is %d" (if pri pri -1000))))
  10189. (defun org-get-priority (s)
  10190. "Find priority cookie and return priority.
  10191. S is a string against which you can match `org-priority-regexp'.
  10192. If `org-priority-get-priority-function' is set to a custom
  10193. function, use it. Otherwise process S and output the priority
  10194. value, an integer."
  10195. (save-match-data
  10196. (if (functionp org-priority-get-priority-function)
  10197. (funcall org-priority-get-priority-function s)
  10198. (if (not (string-match org-priority-regexp s))
  10199. (* 1000 (- org-priority-lowest org-priority-default))
  10200. (* 1000 (- org-priority-lowest
  10201. (org-priority-to-value (match-string 2 s))))))))
  10202. ;;;; Tags
  10203. (defvar org-agenda-archives-mode)
  10204. (defvar org-map-continue-from nil
  10205. "Position from where mapping should continue.
  10206. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10207. (defvar org-scanner-tags nil
  10208. "The current tag list while the tags scanner is running.")
  10209. (defvar org-trust-scanner-tags nil
  10210. "Should `org-get-tags' use the tags for the scanner.
  10211. This is for internal dynamical scoping only.
  10212. When this is non-nil, the function `org-get-tags' will return the value
  10213. of `org-scanner-tags' instead of building the list by itself. This
  10214. can lead to large speed-ups when the tags scanner is used in a file with
  10215. many entries, and when the list of tags is retrieved, for example to
  10216. obtain a list of properties. Building the tags list for each entry in such
  10217. a file becomes an N^2 operation - but with this variable set, it scales
  10218. as N.")
  10219. (defvar org--matcher-tags-todo-only nil)
  10220. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10221. "Scan headline tags with inheritance and produce output ACTION.
  10222. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10223. or `agenda' to produce an entry list for an agenda view. It can also be
  10224. a Lisp form or a function that should be called at each matched headline, in
  10225. this case the return value is a list of all return values from these calls.
  10226. MATCHER is a function accepting three arguments, returning
  10227. a non-nil value whenever a given set of tags qualifies a headline
  10228. for inclusion. See `org-make-tags-matcher' for more information.
  10229. As a special case, it can also be set to t (respectively nil) in
  10230. order to match all (respectively none) headline.
  10231. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10232. included in the output.
  10233. START-LEVEL can be a string with asterisks, reducing the scope to
  10234. headlines matching this string."
  10235. (require 'org-agenda)
  10236. (let* ((re (concat "^"
  10237. (if start-level
  10238. ;; Get the correct level to match
  10239. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10240. org-outline-regexp)
  10241. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10242. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10243. (props (list 'face 'default
  10244. 'done-face 'org-agenda-done
  10245. 'undone-face 'default
  10246. 'mouse-face 'highlight
  10247. 'org-not-done-regexp org-not-done-regexp
  10248. 'org-todo-regexp org-todo-regexp
  10249. 'org-complex-heading-regexp org-complex-heading-regexp
  10250. 'help-echo
  10251. (format "mouse-2 or RET jump to Org file %S"
  10252. (abbreviate-file-name
  10253. (or (buffer-file-name (buffer-base-buffer))
  10254. (buffer-name (buffer-base-buffer)))))))
  10255. (org-map-continue-from nil)
  10256. lspos tags tags-list
  10257. (tags-alist (list (cons 0 org-file-tags)))
  10258. (llast 0) rtn rtn1 level category i txt
  10259. todo marker entry priority
  10260. ts-date ts-date-type ts-date-pair)
  10261. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10262. (setq action (list 'lambda nil action)))
  10263. (save-excursion
  10264. (goto-char (point-min))
  10265. (when (eq action 'sparse-tree)
  10266. (org-overview)
  10267. (org-remove-occur-highlights))
  10268. (while (let (case-fold-search)
  10269. (re-search-forward re nil t))
  10270. (setq org-map-continue-from nil)
  10271. (catch :skip
  10272. ;; Ignore closing parts of inline tasks.
  10273. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10274. (throw :skip t))
  10275. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10276. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10277. (goto-char (setq lspos (match-beginning 0)))
  10278. (setq level (org-reduced-level (org-outline-level))
  10279. category (org-get-category))
  10280. (when (eq action 'agenda)
  10281. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10282. ts-date (car ts-date-pair)
  10283. ts-date-type (cdr ts-date-pair)))
  10284. (setq i llast llast level)
  10285. ;; remove tag lists from same and sublevels
  10286. (while (>= i level)
  10287. (when (setq entry (assoc i tags-alist))
  10288. (setq tags-alist (delete entry tags-alist)))
  10289. (setq i (1- i)))
  10290. ;; add the next tags
  10291. (when tags
  10292. (setq tags (org-split-string tags ":")
  10293. tags-alist
  10294. (cons (cons level tags) tags-alist)))
  10295. ;; compile tags for current headline
  10296. (setq tags-list
  10297. (if org-use-tag-inheritance
  10298. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10299. tags)
  10300. org-scanner-tags tags-list)
  10301. (when org-use-tag-inheritance
  10302. (setcdr (car tags-alist)
  10303. (mapcar (lambda (x)
  10304. (setq x (copy-sequence x))
  10305. (org-add-prop-inherited x))
  10306. (cdar tags-alist))))
  10307. (when (and tags org-use-tag-inheritance
  10308. (or (not (eq t org-use-tag-inheritance))
  10309. org-tags-exclude-from-inheritance))
  10310. ;; Selective inheritance, remove uninherited ones.
  10311. (setcdr (car tags-alist)
  10312. (org-remove-uninherited-tags (cdar tags-alist))))
  10313. (when (and
  10314. ;; eval matcher only when the todo condition is OK
  10315. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10316. (if (functionp matcher)
  10317. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10318. (funcall matcher todo tags-list level))
  10319. matcher))
  10320. ;; Call the skipper, but return t if it does not
  10321. ;; skip, so that the `and' form continues evaluating.
  10322. (progn
  10323. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10324. t)
  10325. ;; Check if timestamps are deselecting this entry
  10326. (or (not todo-only)
  10327. (and (member todo org-todo-keywords-1)
  10328. (or (not org-agenda-tags-todo-honor-ignore-options)
  10329. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10330. ;; select this headline
  10331. (cond
  10332. ((eq action 'sparse-tree)
  10333. (and org-highlight-sparse-tree-matches
  10334. (org-get-heading) (match-end 0)
  10335. (org-highlight-new-match
  10336. (match-beginning 1) (match-end 1)))
  10337. (org-show-context 'tags-tree))
  10338. ((eq action 'agenda)
  10339. (setq txt (org-agenda-format-item
  10340. ""
  10341. (concat
  10342. (if (eq org-tags-match-list-sublevels 'indented)
  10343. (make-string (1- level) ?.) "")
  10344. (org-get-heading))
  10345. (make-string level ?\s)
  10346. category
  10347. tags-list)
  10348. priority (org-get-priority txt))
  10349. (goto-char lspos)
  10350. (setq marker (org-agenda-new-marker))
  10351. (org-add-props txt props
  10352. 'org-marker marker 'org-hd-marker marker 'org-category category
  10353. 'todo-state todo
  10354. 'ts-date ts-date
  10355. 'priority priority
  10356. 'type (concat "tagsmatch" ts-date-type))
  10357. (push txt rtn))
  10358. ((functionp action)
  10359. (setq org-map-continue-from nil)
  10360. (save-excursion
  10361. (setq rtn1 (funcall action))
  10362. (push rtn1 rtn)))
  10363. (t (user-error "Invalid action")))
  10364. ;; if we are to skip sublevels, jump to end of subtree
  10365. (unless org-tags-match-list-sublevels
  10366. (org-end-of-subtree t)
  10367. (backward-char 1))))
  10368. ;; Get the correct position from where to continue
  10369. (if org-map-continue-from
  10370. (goto-char org-map-continue-from)
  10371. (and (= (point) lspos) (end-of-line 1)))))
  10372. (when (and (eq action 'sparse-tree)
  10373. (not org-sparse-tree-open-archived-trees))
  10374. (org-hide-archived-subtrees (point-min) (point-max)))
  10375. (nreverse rtn)))
  10376. (defun org-remove-uninherited-tags (tags)
  10377. "Remove all tags that are not inherited from the list TAGS."
  10378. (cond
  10379. ((eq org-use-tag-inheritance t)
  10380. (if org-tags-exclude-from-inheritance
  10381. (org-delete-all org-tags-exclude-from-inheritance tags)
  10382. tags))
  10383. ((not org-use-tag-inheritance) nil)
  10384. ((stringp org-use-tag-inheritance)
  10385. (delq nil (mapcar
  10386. (lambda (x)
  10387. (if (and (string-match org-use-tag-inheritance x)
  10388. (not (member x org-tags-exclude-from-inheritance)))
  10389. x nil))
  10390. tags)))
  10391. ((listp org-use-tag-inheritance)
  10392. (delq nil (mapcar
  10393. (lambda (x)
  10394. (if (member x org-use-tag-inheritance) x nil))
  10395. tags)))))
  10396. (defun org-match-sparse-tree (&optional todo-only match)
  10397. "Create a sparse tree according to tags string MATCH.
  10398. MATCH is a string with match syntax. It can contain a selection
  10399. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10400. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10401. those. See the manual for details.
  10402. If optional argument TODO-ONLY is non-nil, only select lines that
  10403. are also TODO tasks."
  10404. (interactive "P")
  10405. (org-agenda-prepare-buffers (list (current-buffer)))
  10406. (let ((org--matcher-tags-todo-only todo-only))
  10407. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  10408. org--matcher-tags-todo-only)))
  10409. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10410. (defvar org-cached-props nil)
  10411. (defun org-cached-entry-get (pom property)
  10412. (if (or (eq t org-use-property-inheritance)
  10413. (and (stringp org-use-property-inheritance)
  10414. (let ((case-fold-search t))
  10415. (string-match-p org-use-property-inheritance property)))
  10416. (and (listp org-use-property-inheritance)
  10417. (member-ignore-case property org-use-property-inheritance)))
  10418. ;; Caching is not possible, check it directly.
  10419. (org-entry-get pom property 'inherit)
  10420. ;; Get all properties, so we can do complicated checks easily.
  10421. (cdr (assoc-string property
  10422. (or org-cached-props
  10423. (setq org-cached-props (org-entry-properties pom)))
  10424. t))))
  10425. (defun org-global-tags-completion-table (&optional files)
  10426. "Return the list of all tags in all agenda buffer/files.
  10427. Optional FILES argument is a list of files which can be used
  10428. instead of the agenda files."
  10429. (save-excursion
  10430. (org-uniquify
  10431. (delq nil
  10432. (apply #'append
  10433. (mapcar
  10434. (lambda (file)
  10435. (set-buffer (find-file-noselect file))
  10436. (org--tag-add-to-alist
  10437. (org-get-buffer-tags)
  10438. (mapcar (lambda (x)
  10439. (and (stringp (car-safe x))
  10440. (list (car-safe x))))
  10441. org-current-tag-alist)))
  10442. (if (car-safe files) files
  10443. (org-agenda-files))))))))
  10444. (defun org-make-tags-matcher (match &optional only-local-tags)
  10445. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10446. Returns a cons of the selection string MATCH and a function
  10447. implementing the matcher.
  10448. The matcher is to be called at an Org entry, with point on the
  10449. headline, and returns non-nil if the entry matches the selection
  10450. string MATCH. It must be called with three arguments: the TODO
  10451. keyword at the entry (or nil if none), the list of all tags at
  10452. the entry including inherited ones and the reduced level of the
  10453. headline. Additionally, the category of the entry, if any, must
  10454. be specified as the text property `org-category' on the headline.
  10455. This function sets the variable `org--matcher-tags-todo-only' to
  10456. a non-nil value if the matcher restricts matching to TODO
  10457. entries, otherwise it is not touched.
  10458. When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  10459. table, only get buffer tags.
  10460. See also `org-scan-tags'."
  10461. (unless match
  10462. ;; Get a new match request, with completion against the global
  10463. ;; tags table and the local tags in current buffer.
  10464. (let ((org-last-tags-completion-table
  10465. (org--tag-add-to-alist
  10466. (org-get-buffer-tags)
  10467. (unless only-local-tags
  10468. (org-global-tags-completion-table)))))
  10469. (setq match
  10470. (completing-read
  10471. "Match: "
  10472. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10473. (let ((match0 match)
  10474. (re (concat
  10475. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10476. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10477. "\\([<>=]\\{1,2\\}\\)"
  10478. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10479. "\\|" org-tag-re "\\)"))
  10480. (start 0)
  10481. tagsmatch todomatch tagsmatcher todomatcher)
  10482. ;; Expand group tags.
  10483. (setq match (org-tags-expand match))
  10484. ;; Check if there is a TODO part of this match, which would be the
  10485. ;; part after a "/". To make sure that this slash is not part of
  10486. ;; a property value to be matched against, we also check that
  10487. ;; there is no / after that slash. First, find the last slash.
  10488. (let ((s 0))
  10489. (while (string-match "/+" match s)
  10490. (setq start (match-beginning 0))
  10491. (setq s (match-end 0))))
  10492. (if (and (string-match "/+" match start)
  10493. (not (string-match-p "\"" match start)))
  10494. ;; Match contains also a TODO-matching request.
  10495. (progn
  10496. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10497. (setq todomatch (substring match (match-end 0)))
  10498. (when (string-prefix-p "!" todomatch)
  10499. (setq org--matcher-tags-todo-only t)
  10500. (setq todomatch (substring todomatch 1)))
  10501. (when (string-match "\\`\\s-*\\'" todomatch)
  10502. (setq todomatch nil)))
  10503. ;; Only matching tags.
  10504. (setq tagsmatch match)
  10505. (setq todomatch nil))
  10506. ;; Make the tags matcher.
  10507. (when (org-string-nw-p tagsmatch)
  10508. (let ((orlist nil)
  10509. (orterms (org-split-string tagsmatch "|"))
  10510. term)
  10511. (while (setq term (pop orterms))
  10512. (while (and (equal (substring term -1) "\\") orterms)
  10513. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10514. (while (string-match re term)
  10515. (let* ((rest (substring term (match-end 0)))
  10516. (minus (and (match-end 1)
  10517. (equal (match-string 1 term) "-")))
  10518. (tag (save-match-data
  10519. (replace-regexp-in-string
  10520. "\\\\-" "-" (match-string 2 term))))
  10521. (regexp (eq (string-to-char tag) ?{))
  10522. (levelp (match-end 4))
  10523. (propp (match-end 5))
  10524. (mm
  10525. (cond
  10526. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10527. (levelp
  10528. `(,(org-op-to-function (match-string 3 term))
  10529. level
  10530. ,(string-to-number (match-string 4 term))))
  10531. (propp
  10532. (let* ((gv (pcase (upcase (match-string 5 term))
  10533. ("CATEGORY"
  10534. '(get-text-property (point) 'org-category))
  10535. ("TODO" 'todo)
  10536. (p `(org-cached-entry-get nil ,p))))
  10537. (pv (match-string 7 term))
  10538. (regexp (eq (string-to-char pv) ?{))
  10539. (strp (eq (string-to-char pv) ?\"))
  10540. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10541. (po (org-op-to-function (match-string 6 term)
  10542. (if timep 'time strp))))
  10543. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10544. (when timep (setq pv (org-matcher-time pv)))
  10545. (cond ((and regexp (eq po '/=))
  10546. `(not (string-match ,pv (or ,gv ""))))
  10547. (regexp `(string-match ,pv (or ,gv "")))
  10548. (strp `(,po (or ,gv "") ,pv))
  10549. (t
  10550. `(,po
  10551. (string-to-number (or ,gv ""))
  10552. ,(string-to-number pv))))))
  10553. (t `(member ,tag tags-list)))))
  10554. (push (if minus `(not ,mm) mm) tagsmatcher)
  10555. (setq term rest)))
  10556. (push `(and ,@tagsmatcher) orlist)
  10557. (setq tagsmatcher nil))
  10558. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10559. ;; Make the TODO matcher.
  10560. (when (org-string-nw-p todomatch)
  10561. (let ((orlist nil))
  10562. (dolist (term (org-split-string todomatch "|"))
  10563. (while (string-match re term)
  10564. (let* ((minus (and (match-end 1)
  10565. (equal (match-string 1 term) "-")))
  10566. (kwd (match-string 2 term))
  10567. (regexp (eq (string-to-char kwd) ?{))
  10568. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10569. `(equal todo ,kwd))))
  10570. (push (if minus `(not ,mm) mm) todomatcher))
  10571. (setq term (substring term (match-end 0))))
  10572. (push (if (> (length todomatcher) 1)
  10573. (cons 'and todomatcher)
  10574. (car todomatcher))
  10575. orlist)
  10576. (setq todomatcher nil))
  10577. (setq todomatcher (cons 'or orlist))))
  10578. ;; Return the string and function of the matcher. If no
  10579. ;; tags-specific or todo-specific matcher exists, match
  10580. ;; everything.
  10581. (let ((matcher (if (and tagsmatcher todomatcher)
  10582. `(and ,tagsmatcher ,todomatcher)
  10583. (or tagsmatcher todomatcher t))))
  10584. (when org--matcher-tags-todo-only
  10585. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10586. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10587. (defun org--tags-expand-group (group tag-groups expanded)
  10588. "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  10589. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10590. an accumulator used in recursive calls."
  10591. (dolist (tag group)
  10592. (unless (member tag expanded)
  10593. (let ((group (assoc tag tag-groups)))
  10594. (push tag expanded)
  10595. (when group
  10596. (setq expanded
  10597. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10598. expanded)
  10599. (defun org-tags-expand (match &optional single-as-list downcased)
  10600. "Expand group tags in MATCH.
  10601. This replaces every group tag in MATCH with a regexp tag search.
  10602. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10603. will be replaced like this:
  10604. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10605. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10606. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10607. Replacing by a regexp preserves the structure of the match.
  10608. E.g., this expansion
  10609. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10610. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10611. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10612. A group tag in MATCH can contain regular expressions of its own.
  10613. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10614. will be replaced like this:
  10615. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10616. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10617. assumed to be a single group tag, and the function will return
  10618. the list of tags in this group.
  10619. When DOWNCASED is non-nil, expand downcased TAGS."
  10620. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10621. (let ((tag-groups
  10622. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10623. (if (not downcased) g
  10624. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  10625. (cond
  10626. (single-as-list (org--tags-expand-group
  10627. (list (if downcased (downcase match) match))
  10628. tag-groups nil))
  10629. (org-group-tags
  10630. (let* ((case-fold-search t)
  10631. (tag-syntax org-mode-syntax-table)
  10632. (group-keys (mapcar #'car tag-groups))
  10633. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10634. (return-match (if downcased (downcase match) match)))
  10635. ;; Mark regexp-expressions in the match-expression so that we
  10636. ;; do not replace them later on.
  10637. (let ((s 0))
  10638. (while (string-match "{.+?}" return-match s)
  10639. (setq s (match-end 0))
  10640. (add-text-properties
  10641. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10642. ;; @ and _ are allowed as word-components in tags.
  10643. (modify-syntax-entry ?@ "w" tag-syntax)
  10644. (modify-syntax-entry ?_ "w" tag-syntax)
  10645. ;; For each tag token found in MATCH, compute a regexp and it
  10646. (with-syntax-table tag-syntax
  10647. (replace-regexp-in-string
  10648. key-regexp
  10649. (lambda (m)
  10650. (if (get-text-property (match-beginning 2) 'regexp m)
  10651. m ;regexp tag: ignore
  10652. (let* ((operator (match-string 1 m))
  10653. (tag-token (let ((tag (match-string 2 m)))
  10654. (list (if downcased (downcase tag) tag))))
  10655. regexp-tags regular-tags)
  10656. ;; Partition tags between regexp and regular tags.
  10657. ;; Remove curly bracket syntax from regexp tags.
  10658. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10659. (save-match-data
  10660. (if (string-match "{\\(.+?\\)}" tag)
  10661. (push (match-string 1 tag) regexp-tags)
  10662. (push tag regular-tags))))
  10663. ;; Replace tag token by the appropriate regexp.
  10664. ;; Regular tags need to be regexp-quoted, whereas
  10665. ;; regexp-tags are inserted as-is.
  10666. (let ((regular (regexp-opt regular-tags))
  10667. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10668. (concat operator
  10669. (cond
  10670. ((null regular-tags) (format "{%s}" regexp))
  10671. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10672. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10673. return-match
  10674. t t))))
  10675. (t match))))
  10676. (defun org-op-to-function (op &optional stringp)
  10677. "Turn an operator into the appropriate function."
  10678. (setq op
  10679. (cond
  10680. ((equal op "<" ) '(< org-string< org-time<))
  10681. ((equal op ">" ) '(> org-string> org-time>))
  10682. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10683. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10684. ((member op '("=" "==")) '(= string= org-time=))
  10685. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10686. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10687. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10688. (defvar org-tags-overlay (make-overlay 1 1))
  10689. (delete-overlay org-tags-overlay)
  10690. (defun org-add-prop-inherited (s)
  10691. (add-text-properties 0 (length s) '(inherited t) s)
  10692. s)
  10693. (defun org-toggle-tag (tag &optional onoff)
  10694. "Toggle the tag TAG for the current line.
  10695. If ONOFF is `on' or `off', don't toggle but set to this state."
  10696. (save-excursion
  10697. (org-back-to-heading t)
  10698. (let ((current
  10699. ;; Reverse the tags list so any new tag is appended to the
  10700. ;; current list of tags.
  10701. (nreverse (org-get-tags nil t)))
  10702. res)
  10703. (pcase onoff
  10704. (`off (setq current (delete tag current)))
  10705. ((or `on (guard (not (member tag current))))
  10706. (setq res t)
  10707. (cl-pushnew tag current :test #'equal))
  10708. (_ (setq current (delete tag current))))
  10709. (org-set-tags (nreverse current))
  10710. res)))
  10711. (defun org--align-tags-here (to-col)
  10712. "Align tags on the current headline to TO-COL.
  10713. Assume point is on a headline. Preserve point when aligning
  10714. tags."
  10715. (when (org-match-line org-tag-line-re)
  10716. (let* ((tags-start (match-beginning 1))
  10717. (blank-start (save-excursion
  10718. (goto-char tags-start)
  10719. (skip-chars-backward " \t")
  10720. (point)))
  10721. (new (max (if (>= to-col 0) to-col
  10722. (- (abs to-col) (string-width (match-string 1))))
  10723. ;; Introduce at least one space after the heading
  10724. ;; or the stars.
  10725. (save-excursion
  10726. (goto-char blank-start)
  10727. (1+ (current-column)))))
  10728. (current
  10729. (save-excursion (goto-char tags-start) (current-column)))
  10730. (origin (point-marker))
  10731. (column (current-column))
  10732. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10733. (when (/= new current)
  10734. (delete-region blank-start tags-start)
  10735. (goto-char blank-start)
  10736. (let ((indent-tabs-mode nil)) (indent-to new))
  10737. ;; Try to move back to original position. If point was in the
  10738. ;; blanks before the tags, ORIGIN marker is of no use because
  10739. ;; it now points to BLANK-START. Use COLUMN instead.
  10740. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10741. (defun org-set-tags-command (&optional arg)
  10742. "Set the tags for the current visible entry.
  10743. When called with `\\[universal-argument]' prefix argument ARG, \
  10744. realign all tags
  10745. in the current buffer.
  10746. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10747. unconditionally do not
  10748. offer the fast tag selection interface.
  10749. If a region is active, set tags in the region according to the
  10750. setting of `org-loop-over-headlines-in-active-region'.
  10751. This function is for interactive use only;
  10752. in Lisp code use `org-set-tags' instead."
  10753. (interactive "P")
  10754. (let ((org-use-fast-tag-selection
  10755. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10756. (cond
  10757. ((equal '(4) arg) (org-align-tags t))
  10758. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10759. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10760. (org-map-entries
  10761. #'org-set-tags-command
  10762. nil
  10763. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10764. 'region-start-level
  10765. 'region)
  10766. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10767. (t
  10768. (save-excursion
  10769. (org-back-to-heading)
  10770. (let* ((all-tags (org-get-tags))
  10771. (table (setq org-last-tags-completion-table
  10772. (org--tag-add-to-alist
  10773. (and org-complete-tags-always-offer-all-agenda-tags
  10774. (org-global-tags-completion-table
  10775. (org-agenda-files)))
  10776. (or org-current-tag-alist (org-get-buffer-tags)))))
  10777. (current-tags
  10778. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10779. all-tags))
  10780. (inherited-tags
  10781. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10782. all-tags))
  10783. (tags
  10784. (replace-regexp-in-string
  10785. ;; Ignore all forbidden characters in tags.
  10786. "[^[:alnum:]_@#%]+" ":"
  10787. (if (or (eq t org-use-fast-tag-selection)
  10788. (and org-use-fast-tag-selection
  10789. (delq nil (mapcar #'cdr table))))
  10790. (org-fast-tag-selection
  10791. current-tags
  10792. inherited-tags
  10793. table
  10794. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10795. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  10796. (org-trim (completing-read
  10797. "Tags: "
  10798. #'org-tags-completion-function
  10799. nil nil (org-make-tag-string current-tags)
  10800. 'org-tags-history)))))))
  10801. (org-set-tags tags)))))
  10802. ;; `save-excursion' may not replace the point at the right
  10803. ;; position.
  10804. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  10805. (looking-at-p " "))
  10806. (forward-char))))
  10807. (defun org-align-tags (&optional all)
  10808. "Align tags in current entry.
  10809. When optional argument ALL is non-nil, align all tags in the
  10810. visible part of the buffer."
  10811. (let ((get-indent-column
  10812. (lambda ()
  10813. (let ((offset (if (bound-and-true-p org-indent-mode)
  10814. (* (1- org-indent-indentation-per-level)
  10815. (1- (org-current-level)))
  10816. 0)))
  10817. (+ org-tags-column
  10818. (if (> org-tags-column 0) (- offset) offset))))))
  10819. (if (and (not all) (org-at-heading-p))
  10820. (org--align-tags-here (funcall get-indent-column))
  10821. (save-excursion
  10822. (if all
  10823. (progn
  10824. (goto-char (point-min))
  10825. (while (re-search-forward org-tag-line-re nil t)
  10826. (org--align-tags-here (funcall get-indent-column))))
  10827. (org-back-to-heading t)
  10828. (org--align-tags-here (funcall get-indent-column)))))))
  10829. (defun org-set-tags (tags)
  10830. "Set the tags of the current entry to TAGS, replacing current tags.
  10831. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10832. If TAGS is nil or the empty string, all tags are removed.
  10833. This function assumes point is on a headline."
  10834. (org-with-wide-buffer
  10835. (let ((tags (pcase tags
  10836. ((pred listp) tags)
  10837. ((pred stringp) (split-string (org-trim tags) ":" t))
  10838. (_ (error "Invalid tag specification: %S" tags))))
  10839. (old-tags (org-get-tags nil t))
  10840. (tags-change? nil))
  10841. (when (functionp org-tags-sort-function)
  10842. (setq tags (sort tags org-tags-sort-function)))
  10843. (setq tags-change? (not (equal tags old-tags)))
  10844. (when tags-change?
  10845. ;; Delete previous tags and any trailing white space.
  10846. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10847. (line-end-position)))
  10848. (skip-chars-backward " \t")
  10849. (delete-region (point) (line-end-position))
  10850. ;; Deleting white spaces may break an otherwise empty headline.
  10851. ;; Re-introduce one space in this case.
  10852. (unless (org-at-heading-p) (insert " "))
  10853. (when tags
  10854. (save-excursion (insert " " (org-make-tag-string tags)))
  10855. ;; When text is being inserted on an invisible region
  10856. ;; boundary, it can be inadvertently sucked into
  10857. ;; invisibility.
  10858. (unless (org-invisible-p (line-beginning-position))
  10859. (org-flag-region (point) (line-end-position) nil 'outline))))
  10860. ;; Align tags, if any.
  10861. (when tags (org-align-tags))
  10862. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  10863. (defun org-change-tag-in-region (beg end tag off)
  10864. "Add or remove TAG for each entry in the region.
  10865. This works in the agenda, and also in an Org buffer."
  10866. (interactive
  10867. (list (region-beginning) (region-end)
  10868. (let ((org-last-tags-completion-table
  10869. (if (derived-mode-p 'org-mode)
  10870. (org--tag-add-to-alist
  10871. (org-get-buffer-tags)
  10872. (org-global-tags-completion-table))
  10873. (org-global-tags-completion-table))))
  10874. (completing-read
  10875. "Tag: " 'org-tags-completion-function nil nil nil
  10876. 'org-tags-history))
  10877. (progn
  10878. (message "[s]et or [r]emove? ")
  10879. (equal (read-char-exclusive) ?r))))
  10880. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10881. (let ((agendap (equal major-mode 'org-agenda-mode))
  10882. l1 l2 m buf pos newhead (cnt 0))
  10883. (goto-char end)
  10884. (setq l2 (1- (org-current-line)))
  10885. (goto-char beg)
  10886. (setq l1 (org-current-line))
  10887. (cl-loop for l from l1 to l2 do
  10888. (org-goto-line l)
  10889. (setq m (get-text-property (point) 'org-hd-marker))
  10890. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  10891. (and agendap m))
  10892. (setq buf (if agendap (marker-buffer m) (current-buffer))
  10893. pos (if agendap m (point)))
  10894. (with-current-buffer buf
  10895. (save-excursion
  10896. (save-restriction
  10897. (goto-char pos)
  10898. (setq cnt (1+ cnt))
  10899. (org-toggle-tag tag (if off 'off 'on))
  10900. (setq newhead (org-get-heading)))))
  10901. (and agendap (org-agenda-change-all-lines newhead m))))
  10902. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  10903. (defun org-tags-completion-function (string _predicate &optional flag)
  10904. "Complete tag STRING.
  10905. FLAG specifies the type of completion operation to perform. This
  10906. function is passed as a collection function to `completing-read',
  10907. which see."
  10908. (let ((completion-ignore-case nil) ;tags are case-sensitive
  10909. (confirm (lambda (x) (stringp (car x))))
  10910. (prefix ""))
  10911. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  10912. (setq prefix (match-string 1 string))
  10913. (setq string (match-string 2 string)))
  10914. (pcase flag
  10915. (`t (all-completions string org-last-tags-completion-table confirm))
  10916. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  10917. (`nil
  10918. (pcase (try-completion string org-last-tags-completion-table confirm)
  10919. ((and completion (pred stringp))
  10920. (concat prefix
  10921. completion
  10922. (if (and org-add-colon-after-tag-completion
  10923. (assoc completion org-last-tags-completion-table))
  10924. ":"
  10925. "")))
  10926. (completion completion)))
  10927. (_ nil))))
  10928. (defun org-fast-tag-insert (kwd tags face &optional end)
  10929. "Insert KWD, and the TAGS, the latter with face FACE.
  10930. Also insert END."
  10931. (insert (format "%-12s" (concat kwd ":"))
  10932. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  10933. (or end "")))
  10934. (defun org-fast-tag-show-exit (flag)
  10935. (save-excursion
  10936. (org-goto-line 3)
  10937. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  10938. (replace-match ""))
  10939. (when flag
  10940. (end-of-line 1)
  10941. (org-move-to-column (- (window-width) 19) t)
  10942. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  10943. (defun org-set-current-tags-overlay (current prefix)
  10944. "Add an overlay to CURRENT tag with PREFIX."
  10945. (let ((s (org-make-tag-string current)))
  10946. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  10947. (org-overlay-display org-tags-overlay (concat prefix s))))
  10948. (defvar org-last-tag-selection-key nil)
  10949. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  10950. "Fast tag selection with single keys.
  10951. CURRENT is the current list of tags in the headline, INHERITED is the
  10952. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  10953. possibly with grouping information. TODO-TABLE is a similar table with
  10954. TODO keywords, should these have keys assigned to them.
  10955. If the keys are nil, a-z are automatically assigned.
  10956. Returns the new tags string, or nil to not change the current settings."
  10957. (let* ((fulltable (append table todo-table))
  10958. (maxlen (if (null fulltable) 0
  10959. (apply #'max
  10960. (mapcar (lambda (x)
  10961. (if (stringp (car x)) (string-width (car x))
  10962. 0))
  10963. fulltable))))
  10964. (buf (current-buffer))
  10965. (expert (eq org-fast-tag-selection-single-key 'expert))
  10966. (buffer-tags nil)
  10967. (fwidth (+ maxlen 3 1 3))
  10968. (ncol (/ (- (window-width) 4) fwidth))
  10969. (i-face 'org-done)
  10970. (c-face 'org-todo)
  10971. tg cnt e c char c1 c2 ntable tbl rtn
  10972. ov-start ov-end ov-prefix
  10973. (exit-after-next org-fast-tag-selection-single-key)
  10974. (done-keywords org-done-keywords)
  10975. groups ingroup intaggroup)
  10976. (save-excursion
  10977. (beginning-of-line)
  10978. (if (looking-at org-tag-line-re)
  10979. (setq ov-start (match-beginning 1)
  10980. ov-end (match-end 1)
  10981. ov-prefix "")
  10982. (setq ov-start (1- (point-at-eol))
  10983. ov-end (1+ ov-start))
  10984. (skip-chars-forward "^\n\r")
  10985. (setq ov-prefix
  10986. (concat
  10987. (buffer-substring (1- (point)) (point))
  10988. (if (> (current-column) org-tags-column)
  10989. " "
  10990. (make-string (- org-tags-column (current-column)) ?\ ))))))
  10991. (move-overlay org-tags-overlay ov-start ov-end)
  10992. (save-excursion
  10993. (save-window-excursion
  10994. (if expert
  10995. (set-buffer (get-buffer-create " *Org tags*"))
  10996. (delete-other-windows)
  10997. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  10998. (org-switch-to-buffer-other-window " *Org tags*"))
  10999. (erase-buffer)
  11000. (setq-local org-done-keywords done-keywords)
  11001. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  11002. (org-fast-tag-insert "Current" current c-face "\n\n")
  11003. (org-fast-tag-show-exit exit-after-next)
  11004. (org-set-current-tags-overlay current ov-prefix)
  11005. (setq tbl fulltable char ?a cnt 0)
  11006. (while (setq e (pop tbl))
  11007. (cond
  11008. ((eq (car e) :startgroup)
  11009. (push '() groups) (setq ingroup t)
  11010. (unless (zerop cnt)
  11011. (setq cnt 0)
  11012. (insert "\n"))
  11013. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11014. ((eq (car e) :endgroup)
  11015. (setq ingroup nil cnt 0)
  11016. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11017. ((eq (car e) :startgrouptag)
  11018. (setq intaggroup t)
  11019. (unless (zerop cnt)
  11020. (setq cnt 0)
  11021. (insert "\n"))
  11022. (insert "[ "))
  11023. ((eq (car e) :endgrouptag)
  11024. (setq intaggroup nil cnt 0)
  11025. (insert "]\n"))
  11026. ((equal e '(:newline))
  11027. (unless (zerop cnt)
  11028. (setq cnt 0)
  11029. (insert "\n")
  11030. (setq e (car tbl))
  11031. (while (equal (car tbl) '(:newline))
  11032. (insert "\n")
  11033. (setq tbl (cdr tbl)))))
  11034. ((equal e '(:grouptags)) (insert " : "))
  11035. (t
  11036. (setq tg (copy-sequence (car e)) c2 nil)
  11037. (if (cdr e)
  11038. (setq c (cdr e))
  11039. ;; automatically assign a character.
  11040. (setq c1 (string-to-char
  11041. (downcase (substring
  11042. tg (if (= (string-to-char tg) ?@) 1 0)))))
  11043. (if (or (rassoc c1 ntable) (rassoc c1 table))
  11044. (while (or (rassoc char ntable) (rassoc char table))
  11045. (setq char (1+ char)))
  11046. (setq c2 c1))
  11047. (setq c (or c2 char)))
  11048. (when ingroup (push tg (car groups)))
  11049. (setq tg (org-add-props tg nil 'face
  11050. (cond
  11051. ((not (assoc tg table))
  11052. (org-get-todo-face tg))
  11053. ((member tg current) c-face)
  11054. ((member tg inherited) i-face))))
  11055. (when (equal (caar tbl) :grouptags)
  11056. (org-add-props tg nil 'face 'org-tag-group))
  11057. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  11058. (insert "[" c "] " tg (make-string
  11059. (- fwidth 4 (length tg)) ?\ ))
  11060. (push (cons tg c) ntable)
  11061. (when (= (cl-incf cnt) ncol)
  11062. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11063. (insert "\n")
  11064. (when (or ingroup intaggroup) (insert " ")))
  11065. (setq cnt 0)))))
  11066. (setq ntable (nreverse ntable))
  11067. (insert "\n")
  11068. (goto-char (point-min))
  11069. (unless expert (org-fit-window-to-buffer))
  11070. (setq rtn
  11071. (catch 'exit
  11072. (while t
  11073. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11074. (if (not groups) "no " "")
  11075. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11076. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11077. (setq org-last-tag-selection-key c)
  11078. (cond
  11079. ((= c ?\r) (throw 'exit t))
  11080. ((= c ?!)
  11081. (setq groups (not groups))
  11082. (goto-char (point-min))
  11083. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11084. ((= c ?\C-c)
  11085. (if (not expert)
  11086. (org-fast-tag-show-exit
  11087. (setq exit-after-next (not exit-after-next)))
  11088. (setq expert nil)
  11089. (delete-other-windows)
  11090. (set-window-buffer (split-window-vertically) " *Org tags*")
  11091. (org-switch-to-buffer-other-window " *Org tags*")
  11092. (org-fit-window-to-buffer)))
  11093. ((or (= c ?\C-g)
  11094. (and (= c ?q) (not (rassoc c ntable))))
  11095. (delete-overlay org-tags-overlay)
  11096. (setq quit-flag t))
  11097. ((= c ?\ )
  11098. (setq current nil)
  11099. (when exit-after-next (setq exit-after-next 'now)))
  11100. ((= c ?\t)
  11101. (condition-case nil
  11102. (setq tg (completing-read
  11103. "Tag: "
  11104. (or buffer-tags
  11105. (with-current-buffer buf
  11106. (setq buffer-tags
  11107. (org-get-buffer-tags))))))
  11108. (quit (setq tg "")))
  11109. (when (string-match "\\S-" tg)
  11110. (cl-pushnew (list tg) buffer-tags :test #'equal)
  11111. (if (member tg current)
  11112. (setq current (delete tg current))
  11113. (push tg current)))
  11114. (when exit-after-next (setq exit-after-next 'now)))
  11115. ((setq e (rassoc c todo-table) tg (car e))
  11116. (with-current-buffer buf
  11117. (save-excursion (org-todo tg)))
  11118. (when exit-after-next (setq exit-after-next 'now)))
  11119. ((setq e (rassoc c ntable) tg (car e))
  11120. (if (member tg current)
  11121. (setq current (delete tg current))
  11122. (cl-loop for g in groups do
  11123. (when (member tg g)
  11124. (dolist (x g) (setq current (delete x current)))))
  11125. (push tg current))
  11126. (when exit-after-next (setq exit-after-next 'now))))
  11127. ;; Create a sorted list
  11128. (setq current
  11129. (sort current
  11130. (lambda (a b)
  11131. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11132. (when (eq exit-after-next 'now) (throw 'exit t))
  11133. (goto-char (point-min))
  11134. (beginning-of-line 2)
  11135. (delete-region (point) (point-at-eol))
  11136. (org-fast-tag-insert "Current" current c-face)
  11137. (org-set-current-tags-overlay current ov-prefix)
  11138. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11139. (while (re-search-forward tag-re nil t)
  11140. (let ((tag (match-string 1)))
  11141. (add-text-properties
  11142. (match-beginning 1) (match-end 1)
  11143. (list 'face
  11144. (cond
  11145. ((member tag current) c-face)
  11146. ((member tag inherited) i-face)
  11147. (t (get-text-property (match-beginning 1) '
  11148. face))))))))
  11149. (goto-char (point-min)))))
  11150. (delete-overlay org-tags-overlay)
  11151. (if rtn
  11152. (mapconcat 'identity current ":")
  11153. nil)))))
  11154. (defun org-make-tag-string (tags)
  11155. "Return string associated to TAGS.
  11156. TAGS is a list of strings."
  11157. (if (null tags) ""
  11158. (format ":%s:" (mapconcat #'identity tags ":"))))
  11159. (defun org--get-local-tags ()
  11160. "Return list of tags for the current headline.
  11161. Assume point is at the beginning of the headline."
  11162. (and (looking-at org-tag-line-re)
  11163. (split-string (match-string-no-properties 2) ":" t)))
  11164. (defun org-get-tags (&optional pos local)
  11165. "Get the list of tags specified in the current headline.
  11166. When argument POS is non-nil, retrieve tags for headline at POS.
  11167. According to `org-use-tag-inheritance', tags may be inherited
  11168. from parent headlines, and from the whole document, through
  11169. `org-file-tags'. In this case, the returned list of tags
  11170. contains tags in this order: file tags, tags inherited from
  11171. parent headlines, local tags. If a tag appears multiple times,
  11172. only the most local tag is returned.
  11173. However, when optional argument LOCAL is non-nil, only return
  11174. tags specified at the headline.
  11175. Inherited tags have the `inherited' text property."
  11176. (if (and org-trust-scanner-tags
  11177. (or (not pos) (eq pos (point)))
  11178. (not local))
  11179. org-scanner-tags
  11180. (org-with-point-at (or pos (point))
  11181. (unless (org-before-first-heading-p)
  11182. (org-back-to-heading t)
  11183. (let ((ltags (org--get-local-tags)) itags)
  11184. (if (or local (not org-use-tag-inheritance)) ltags
  11185. (while (org-up-heading-safe)
  11186. (setq itags (nconc (mapcar #'org-add-prop-inherited
  11187. (org--get-local-tags))
  11188. itags)))
  11189. (setq itags (append org-file-tags itags))
  11190. (nreverse
  11191. (delete-dups
  11192. (nreverse (nconc (org-remove-uninherited-tags itags) ltags))))))))))
  11193. (defun org-get-buffer-tags ()
  11194. "Get a table of all tags used in the buffer, for completion."
  11195. (org-with-point-at 1
  11196. (let (tags)
  11197. (while (re-search-forward org-tag-line-re nil t)
  11198. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11199. tags)))
  11200. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11201. ;;;; The mapping API
  11202. (defvar org-agenda-skip-comment-trees)
  11203. (defvar org-agenda-skip-function)
  11204. (defun org-map-entries (func &optional match scope &rest skip)
  11205. "Call FUNC at each headline selected by MATCH in SCOPE.
  11206. FUNC is a function or a lisp form. The function will be called without
  11207. arguments, with the cursor positioned at the beginning of the headline.
  11208. The return values of all calls to the function will be collected and
  11209. returned as a list.
  11210. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  11211. does not need to preserve point. After evaluation, the cursor will be
  11212. moved to the end of the line (presumably of the headline of the
  11213. processed entry) and search continues from there. Under some
  11214. circumstances, this may not produce the wanted results. For example,
  11215. if you have removed (e.g. archived) the current (sub)tree it could
  11216. mean that the next entry will be skipped entirely. In such cases, you
  11217. can specify the position from where search should continue by making
  11218. FUNC set the variable `org-map-continue-from' to the desired buffer
  11219. position.
  11220. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11221. Only headlines that are matched by this query will be considered during
  11222. the iteration. When MATCH is nil or t, all headlines will be
  11223. visited by the iteration.
  11224. SCOPE determines the scope of this command. It can be any of:
  11225. nil The current buffer, respecting the restriction if any
  11226. tree The subtree started with the entry at point
  11227. region The entries within the active region, if any
  11228. region-start-level
  11229. The entries within the active region, but only those at
  11230. the same level than the first one.
  11231. file The current buffer, without restriction
  11232. file-with-archives
  11233. The current buffer, and any archives associated with it
  11234. agenda All agenda files
  11235. agenda-with-archives
  11236. All agenda files with any archive files associated with them
  11237. \(file1 file2 ...)
  11238. If this is a list, all files in the list will be scanned
  11239. The remaining args are treated as settings for the skipping facilities of
  11240. the scanner. The following items can be given here:
  11241. archive skip trees with the archive tag
  11242. comment skip trees with the COMMENT keyword
  11243. function or Emacs Lisp form:
  11244. will be used as value for `org-agenda-skip-function', so
  11245. whenever the function returns a position, FUNC will not be
  11246. called for that entry and search will continue from the
  11247. position returned
  11248. If your function needs to retrieve the tags including inherited tags
  11249. at the *current* entry, you can use the value of the variable
  11250. `org-scanner-tags' which will be much faster than getting the value
  11251. with `org-get-tags'. If your function gets properties with
  11252. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11253. to t around the call to `org-entry-properties' to get the same speedup.
  11254. Note that if your function moves around to retrieve tags and properties at
  11255. a *different* entry, you cannot use these techniques."
  11256. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11257. (not (org-region-active-p)))
  11258. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11259. (org-agenda-skip-archived-trees (memq 'archive skip))
  11260. (org-agenda-skip-comment-trees (memq 'comment skip))
  11261. (org-agenda-skip-function
  11262. (car (org-delete-all '(comment archive) skip)))
  11263. (org-tags-match-list-sublevels t)
  11264. (start-level (eq scope 'region-start-level))
  11265. matcher res
  11266. org-todo-keywords-for-agenda
  11267. org-done-keywords-for-agenda
  11268. org-todo-keyword-alist-for-agenda
  11269. org-tag-alist-for-agenda
  11270. org--matcher-tags-todo-only)
  11271. (cond
  11272. ((eq match t) (setq matcher t))
  11273. ((eq match nil) (setq matcher t))
  11274. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11275. (save-excursion
  11276. (save-restriction
  11277. (cond ((eq scope 'tree)
  11278. (org-back-to-heading t)
  11279. (org-narrow-to-subtree)
  11280. (setq scope nil))
  11281. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11282. (org-region-active-p))
  11283. ;; If needed, set start-level to a string like "2"
  11284. (when start-level
  11285. (save-excursion
  11286. (goto-char (region-beginning))
  11287. (unless (org-at-heading-p) (outline-next-heading))
  11288. (setq start-level (org-current-level))))
  11289. (narrow-to-region (region-beginning)
  11290. (save-excursion
  11291. (goto-char (region-end))
  11292. (unless (and (bolp) (org-at-heading-p))
  11293. (outline-next-heading))
  11294. (point)))
  11295. (setq scope nil)))
  11296. (if (not scope)
  11297. (progn
  11298. (org-agenda-prepare-buffers
  11299. (and buffer-file-name (list buffer-file-name)))
  11300. (setq res
  11301. (org-scan-tags
  11302. func matcher org--matcher-tags-todo-only start-level)))
  11303. ;; Get the right scope
  11304. (cond
  11305. ((and scope (listp scope) (symbolp (car scope)))
  11306. (setq scope (eval scope)))
  11307. ((eq scope 'agenda)
  11308. (setq scope (org-agenda-files t)))
  11309. ((eq scope 'agenda-with-archives)
  11310. (setq scope (org-agenda-files t))
  11311. (setq scope (org-add-archive-files scope)))
  11312. ((eq scope 'file)
  11313. (setq scope (and buffer-file-name (list buffer-file-name))))
  11314. ((eq scope 'file-with-archives)
  11315. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11316. (org-agenda-prepare-buffers scope)
  11317. (dolist (file scope)
  11318. (with-current-buffer (org-find-base-buffer-visiting file)
  11319. (org-with-wide-buffer
  11320. (goto-char (point-min))
  11321. (setq res
  11322. (append
  11323. res
  11324. (org-scan-tags
  11325. func matcher org--matcher-tags-todo-only)))))))))
  11326. res)))
  11327. ;;; Properties API
  11328. (defconst org-special-properties
  11329. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11330. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11331. "The special properties valid in Org mode.
  11332. These are properties that are not defined in the property drawer,
  11333. but in some other way.")
  11334. (defconst org-default-properties
  11335. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11336. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11337. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11338. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11339. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11340. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11341. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11342. "Some properties that are used by Org mode for various purposes.
  11343. Being in this list makes sure that they are offered for completion.")
  11344. (defun org--valid-property-p (property)
  11345. "Non-nil when string PROPERTY is a valid property name."
  11346. (not
  11347. (or (equal property "")
  11348. (string-match-p "\\s-" property))))
  11349. (defun org--update-property-plist (key val props)
  11350. "Associate KEY to VAL in alist PROPS.
  11351. Modifications are made by side-effect. Return new alist."
  11352. (let* ((appending (string= (substring key -1) "+"))
  11353. (key (if appending (substring key 0 -1) key))
  11354. (old (assoc-string key props t)))
  11355. (if (not old) (cons (cons key val) props)
  11356. (setcdr old (if appending (concat (cdr old) " " val) val))
  11357. props)))
  11358. (defun org-get-property-block (&optional beg force)
  11359. "Return the (beg . end) range of the body of the property drawer.
  11360. BEG is the beginning of the current subtree or the beginning of
  11361. the document if before the first headline. If it is not given,
  11362. it will be found. If the drawer does not exist, create it if
  11363. FORCE is non-nil, or return nil."
  11364. (org-with-wide-buffer
  11365. (let ((beg (cond (beg (goto-char beg))
  11366. ((or (not (featurep 'org-inlinetask))
  11367. (org-inlinetask-in-task-p))
  11368. (org-back-to-heading-or-point-min t) (point))
  11369. (t (org-with-limited-levels
  11370. (org-back-to-heading-or-point-min t))
  11371. (point)))))
  11372. ;; Move point to its position according to its positional rules.
  11373. (cond ((org-before-first-heading-p)
  11374. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11375. (t (forward-line)
  11376. (when (looking-at-p org-planning-line-re) (forward-line))))
  11377. (cond ((looking-at org-property-drawer-re)
  11378. (forward-line)
  11379. (cons (point) (progn (goto-char (match-end 0))
  11380. (line-beginning-position))))
  11381. (force
  11382. (goto-char beg)
  11383. (org-insert-property-drawer)
  11384. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11385. (line-beginning-position))))
  11386. (cons pos pos)))))))
  11387. (defun org-at-property-drawer-p ()
  11388. "Non-nil when point is at the first line of a property drawer."
  11389. (org-with-wide-buffer
  11390. (beginning-of-line)
  11391. (and (looking-at org-property-drawer-re)
  11392. (or (bobp)
  11393. (progn
  11394. (forward-line -1)
  11395. (cond ((org-at-heading-p))
  11396. ((looking-at org-planning-line-re)
  11397. (forward-line -1)
  11398. (org-at-heading-p))
  11399. ((looking-at org-comment-regexp)
  11400. (forward-line -1)
  11401. (while (and (not (bobp)) (looking-at org-comment-regexp))
  11402. (forward-line -1))
  11403. (looking-at org-comment-regexp))
  11404. (t nil)))))))
  11405. (defun org-at-property-p ()
  11406. "Non-nil when point is inside a property drawer.
  11407. See `org-property-re' for match data, if applicable."
  11408. (save-excursion
  11409. (beginning-of-line)
  11410. (and (looking-at org-property-re)
  11411. (let ((property-drawer (save-match-data (org-get-property-block))))
  11412. (and property-drawer
  11413. (>= (point) (car property-drawer))
  11414. (< (point) (cdr property-drawer)))))))
  11415. (defun org-property-action ()
  11416. "Do an action on properties."
  11417. (interactive)
  11418. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11419. (let ((c (read-char-exclusive)))
  11420. (cl-case c
  11421. (?s (call-interactively #'org-set-property))
  11422. (?d (call-interactively #'org-delete-property))
  11423. (?D (call-interactively #'org-delete-property-globally))
  11424. (?c (call-interactively #'org-compute-property-at-point))
  11425. (otherwise (user-error "No such property action %c" c)))))
  11426. (defun org-inc-effort ()
  11427. "Increment the value of the effort property in the current entry."
  11428. (interactive)
  11429. (org-set-effort t))
  11430. (defvar org-clock-effort) ; Defined in org-clock.el.
  11431. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11432. (defun org-set-effort (&optional increment value)
  11433. "Set the effort property of the current entry.
  11434. If INCREMENT is non-nil, set the property to the next allowed
  11435. value. Otherwise, if optional argument VALUE is provided, use
  11436. it. Eventually, prompt for the new value if none of the previous
  11437. variables is set."
  11438. (interactive "P")
  11439. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11440. (current (org-entry-get nil org-effort-property))
  11441. (value
  11442. (cond
  11443. (increment
  11444. (unless allowed (user-error "Allowed effort values are not set"))
  11445. (or (cl-caadr (member (list current) allowed))
  11446. (user-error "Unknown value %S among allowed values" current)))
  11447. (value
  11448. (if (stringp value) value
  11449. (error "Invalid effort value: %S" value)))
  11450. (t
  11451. (let ((must-match
  11452. (and allowed
  11453. (not (get-text-property 0 'org-unrestricted
  11454. (caar allowed))))))
  11455. (completing-read "Effort: " allowed nil must-match))))))
  11456. ;; Test whether the value can be interpreted as a duration before
  11457. ;; inserting it in the buffer:
  11458. (org-duration-to-minutes value)
  11459. ;; Maybe update the effort value:
  11460. (unless (equal current value)
  11461. (org-entry-put nil org-effort-property value))
  11462. (org-refresh-property '((effort . identity)
  11463. (effort-minutes . org-duration-to-minutes))
  11464. value)
  11465. (when (equal (org-get-heading t t t t)
  11466. (bound-and-true-p org-clock-current-task))
  11467. (setq org-clock-effort value)
  11468. (org-clock-update-mode-line))
  11469. (message "%s is now %s" org-effort-property value)))
  11470. (defun org-entry-properties (&optional pom which)
  11471. "Get all properties of the current entry.
  11472. When POM is a buffer position, get all properties from the entry
  11473. there instead.
  11474. This includes the TODO keyword, the tags, time strings for
  11475. deadline, scheduled, and clocking, and any additional properties
  11476. defined in the entry.
  11477. If WHICH is nil or `all', get all properties. If WHICH is
  11478. `special' or `standard', only get that subclass. If WHICH is
  11479. a string, only get that property.
  11480. Return value is an alist. Keys are properties, as upcased
  11481. strings."
  11482. (org-with-point-at pom
  11483. (when (and (derived-mode-p 'org-mode)
  11484. (org-back-to-heading-or-point-min t))
  11485. (catch 'exit
  11486. (let* ((beg (point))
  11487. (specific (and (stringp which) (upcase which)))
  11488. (which (cond ((not specific) which)
  11489. ((member specific org-special-properties) 'special)
  11490. (t 'standard)))
  11491. props)
  11492. ;; Get the special properties, like TODO and TAGS.
  11493. (when (memq which '(nil all special))
  11494. (when (or (not specific) (string= specific "CLOCKSUM"))
  11495. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11496. (when clocksum
  11497. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11498. props)))
  11499. (when specific (throw 'exit props)))
  11500. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11501. (let ((clocksumt (get-text-property (point)
  11502. :org-clock-minutes-today)))
  11503. (when clocksumt
  11504. (push (cons "CLOCKSUM_T"
  11505. (org-duration-from-minutes clocksumt))
  11506. props)))
  11507. (when specific (throw 'exit props)))
  11508. (when (or (not specific) (string= specific "ITEM"))
  11509. (let ((case-fold-search nil))
  11510. (when (looking-at org-complex-heading-regexp)
  11511. (push (cons "ITEM"
  11512. (let ((title (match-string-no-properties 4)))
  11513. (if (org-string-nw-p title)
  11514. (org-remove-tabs title)
  11515. "")))
  11516. props)))
  11517. (when specific (throw 'exit props)))
  11518. (when (or (not specific) (string= specific "TODO"))
  11519. (let ((case-fold-search nil))
  11520. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11521. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11522. (when specific (throw 'exit props)))
  11523. (when (or (not specific) (string= specific "PRIORITY"))
  11524. (push (cons "PRIORITY"
  11525. (if (looking-at org-priority-regexp)
  11526. (match-string-no-properties 2)
  11527. (char-to-string org-priority-default)))
  11528. props)
  11529. (when specific (throw 'exit props)))
  11530. (when (or (not specific) (string= specific "FILE"))
  11531. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11532. props)
  11533. (when specific (throw 'exit props)))
  11534. (when (or (not specific) (string= specific "TAGS"))
  11535. (let ((tags (org-get-tags nil t)))
  11536. (when tags
  11537. (push (cons "TAGS" (org-make-tag-string tags))
  11538. props)))
  11539. (when specific (throw 'exit props)))
  11540. (when (or (not specific) (string= specific "ALLTAGS"))
  11541. (let ((tags (org-get-tags)))
  11542. (when tags
  11543. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11544. props)))
  11545. (when specific (throw 'exit props)))
  11546. (when (or (not specific) (string= specific "BLOCKED"))
  11547. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11548. (when specific (throw 'exit props)))
  11549. (when (or (not specific)
  11550. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11551. (forward-line)
  11552. (when (looking-at-p org-planning-line-re)
  11553. (end-of-line)
  11554. (let ((bol (line-beginning-position))
  11555. ;; Backward compatibility: time keywords used to
  11556. ;; be configurable (before 8.3). Make sure we
  11557. ;; get the correct keyword.
  11558. (key-assoc `(("CLOSED" . ,org-closed-string)
  11559. ("DEADLINE" . ,org-deadline-string)
  11560. ("SCHEDULED" . ,org-scheduled-string))))
  11561. (dolist (pair (if specific (list (assoc specific key-assoc))
  11562. key-assoc))
  11563. (save-excursion
  11564. (when (search-backward (cdr pair) bol t)
  11565. (goto-char (match-end 0))
  11566. (skip-chars-forward " \t")
  11567. (and (looking-at org-ts-regexp-both)
  11568. (push (cons (car pair)
  11569. (match-string-no-properties 0))
  11570. props)))))))
  11571. (when specific (throw 'exit props)))
  11572. (when (or (not specific)
  11573. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11574. (let ((find-ts
  11575. (lambda (end ts)
  11576. ;; Fix next time-stamp before END. TS is the
  11577. ;; list of time-stamps found so far.
  11578. (let ((ts ts)
  11579. (regexp (cond
  11580. ((string= specific "TIMESTAMP")
  11581. org-ts-regexp)
  11582. ((string= specific "TIMESTAMP_IA")
  11583. org-ts-regexp-inactive)
  11584. ((assoc "TIMESTAMP_IA" ts)
  11585. org-ts-regexp)
  11586. ((assoc "TIMESTAMP" ts)
  11587. org-ts-regexp-inactive)
  11588. (t org-ts-regexp-both))))
  11589. (catch 'next
  11590. (while (re-search-forward regexp end t)
  11591. (backward-char)
  11592. (let ((object (org-element-context)))
  11593. ;; Accept to match timestamps in node
  11594. ;; properties, too.
  11595. (when (memq (org-element-type object)
  11596. '(node-property timestamp))
  11597. (let ((type
  11598. (org-element-property :type object)))
  11599. (cond
  11600. ((and (memq type '(active active-range))
  11601. (not (equal specific "TIMESTAMP_IA")))
  11602. (unless (assoc "TIMESTAMP" ts)
  11603. (push (cons "TIMESTAMP"
  11604. (org-element-property
  11605. :raw-value object))
  11606. ts)
  11607. (when specific (throw 'exit ts))))
  11608. ((and (memq type '(inactive inactive-range))
  11609. (not (string= specific "TIMESTAMP")))
  11610. (unless (assoc "TIMESTAMP_IA" ts)
  11611. (push (cons "TIMESTAMP_IA"
  11612. (org-element-property
  11613. :raw-value object))
  11614. ts)
  11615. (when specific (throw 'exit ts))))))
  11616. ;; Both timestamp types are found,
  11617. ;; move to next part.
  11618. (when (= (length ts) 2) (throw 'next ts)))))
  11619. ts)))))
  11620. (goto-char beg)
  11621. ;; First look for timestamps within headline.
  11622. (let ((ts (funcall find-ts (line-end-position) nil)))
  11623. (if (= (length ts) 2) (setq props (nconc ts props))
  11624. ;; Then find timestamps in the section, skipping
  11625. ;; planning line.
  11626. (let ((end (save-excursion (outline-next-heading))))
  11627. (forward-line)
  11628. (when (looking-at-p org-planning-line-re) (forward-line))
  11629. (setq props (nconc (funcall find-ts end ts) props))))))))
  11630. ;; Get the standard properties, like :PROP:.
  11631. (when (memq which '(nil all standard))
  11632. ;; If we are looking after a specific property, delegate
  11633. ;; to `org-entry-get', which is faster. However, make an
  11634. ;; exception for "CATEGORY", since it can be also set
  11635. ;; through keywords (i.e. #+CATEGORY).
  11636. (if (and specific (not (equal specific "CATEGORY")))
  11637. (let ((value (org-entry-get beg specific nil t)))
  11638. (throw 'exit (and value (list (cons specific value)))))
  11639. (let ((range (org-get-property-block beg)))
  11640. (when range
  11641. (let ((end (cdr range)) seen-base)
  11642. (goto-char (car range))
  11643. ;; Unlike to `org--update-property-plist', we
  11644. ;; handle the case where base values is found
  11645. ;; after its extension. We also forbid standard
  11646. ;; properties to be named as special properties.
  11647. (while (re-search-forward org-property-re end t)
  11648. (let* ((key (upcase (match-string-no-properties 2)))
  11649. (extendp (string-match-p "\\+\\'" key))
  11650. (key-base (if extendp (substring key 0 -1) key))
  11651. (value (match-string-no-properties 3)))
  11652. (cond
  11653. ((member-ignore-case key-base org-special-properties))
  11654. (extendp
  11655. (setq props
  11656. (org--update-property-plist key value props)))
  11657. ((member key seen-base))
  11658. (t (push key seen-base)
  11659. (let ((p (assoc-string key props t)))
  11660. (if p (setcdr p (concat value " " (cdr p)))
  11661. (push (cons key value) props))))))))))))
  11662. (unless (assoc "CATEGORY" props)
  11663. (push (cons "CATEGORY" (org-get-category beg)) props)
  11664. (when (string= specific "CATEGORY") (throw 'exit props)))
  11665. ;; Return value.
  11666. props)))))
  11667. (defun org--property-local-values (property literal-nil)
  11668. "Return value for PROPERTY in current entry.
  11669. Value is a list whose car is the base value for PROPERTY and cdr
  11670. a list of accumulated values. Return nil if neither is found in
  11671. the entry. Also return nil when PROPERTY is set to \"nil\",
  11672. unless LITERAL-NIL is non-nil."
  11673. (let ((range (org-get-property-block)))
  11674. (when range
  11675. (goto-char (car range))
  11676. (let* ((case-fold-search t)
  11677. (end (cdr range))
  11678. (value
  11679. ;; Base value.
  11680. (save-excursion
  11681. (let ((v (and (re-search-forward
  11682. (org-re-property property nil t) end t)
  11683. (match-string-no-properties 3))))
  11684. (list (if literal-nil v (org-not-nil v)))))))
  11685. ;; Find additional values.
  11686. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11687. (while (re-search-forward property+ end t)
  11688. (push (match-string-no-properties 3) value)))
  11689. ;; Return final values.
  11690. (and (not (equal value '(nil))) (nreverse value))))))
  11691. (defun org--property-global-or-keyword-value (property literal-nil)
  11692. "Return value for PROPERTY as defined by global properties or by keyword.
  11693. Return value is a string. Return nil if property is not set
  11694. globally or by keyword. Also return nil when PROPERTY is set to
  11695. \"nil\", unless LITERAL-NIL is non-nil."
  11696. (let ((global
  11697. (cdr (or (assoc-string property org-keyword-properties t)
  11698. (assoc-string property org-global-properties t)
  11699. (assoc-string property org-global-properties-fixed t)))))
  11700. (if literal-nil global (org-not-nil global))))
  11701. (defun org-entry-get (pom property &optional inherit literal-nil)
  11702. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11703. If INHERIT is non-nil and the entry does not have the property,
  11704. then also check higher levels of the hierarchy. If INHERIT is
  11705. the symbol `selective', use inheritance only if the setting in
  11706. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11707. If the property is present but empty, the return value is the
  11708. empty string. If the property is not present at all, nil is
  11709. returned. In any other case, return the value as a string.
  11710. Search is case-insensitive.
  11711. If LITERAL-NIL is set, return the string value \"nil\" as
  11712. a string, do not interpret it as the list atom nil. This is used
  11713. for inheritance when a \"nil\" value can supersede a non-nil
  11714. value higher up the hierarchy."
  11715. (org-with-point-at pom
  11716. (cond
  11717. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11718. ;; We need a special property. Use `org-entry-properties' to
  11719. ;; retrieve it, but specify the wanted property.
  11720. (cdr (assoc-string property (org-entry-properties nil property))))
  11721. ((and inherit
  11722. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11723. (org-entry-get-with-inheritance property literal-nil))
  11724. (t
  11725. (let* ((local (org--property-local-values property literal-nil))
  11726. (value (and local (mapconcat #'identity (delq nil local) " "))))
  11727. (if literal-nil value (org-not-nil value)))))))
  11728. (defun org-property-or-variable-value (var &optional inherit)
  11729. "Check if there is a property fixing the value of VAR.
  11730. If yes, return this value. If not, return the current value of the variable."
  11731. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11732. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11733. (read prop)
  11734. (symbol-value var))))
  11735. (defun org-entry-delete (pom property)
  11736. "Delete PROPERTY from entry at point-or-marker POM.
  11737. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11738. non-nil when a property was removed."
  11739. (org-with-point-at pom
  11740. (pcase (org-get-property-block)
  11741. (`(,begin . ,origin)
  11742. (let* ((end (copy-marker origin))
  11743. (re (org-re-property
  11744. (concat (regexp-quote property) "\\+?") t t)))
  11745. (goto-char begin)
  11746. (while (re-search-forward re end t)
  11747. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11748. ;; If drawer is empty, remove it altogether.
  11749. (when (= begin end)
  11750. (delete-region (line-beginning-position 0)
  11751. (line-beginning-position 2)))
  11752. ;; Return non-nil if some property was removed.
  11753. (prog1 (/= end origin) (set-marker end nil))))
  11754. (_ nil))))
  11755. ;; Multi-values properties are properties that contain multiple values
  11756. ;; These values are assumed to be single words, separated by whitespace.
  11757. (defun org-entry-add-to-multivalued-property (pom property value)
  11758. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11759. (let* ((old (org-entry-get pom property))
  11760. (values (and old (split-string old))))
  11761. (setq value (org-entry-protect-space value))
  11762. (unless (member value values)
  11763. (setq values (append values (list value)))
  11764. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11765. (defun org-entry-remove-from-multivalued-property (pom property value)
  11766. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11767. (let* ((old (org-entry-get pom property))
  11768. (values (and old (split-string old))))
  11769. (setq value (org-entry-protect-space value))
  11770. (when (member value values)
  11771. (setq values (delete value values))
  11772. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11773. (defun org-entry-member-in-multivalued-property (pom property value)
  11774. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11775. (let* ((old (org-entry-get pom property))
  11776. (values (and old (split-string old))))
  11777. (setq value (org-entry-protect-space value))
  11778. (member value values)))
  11779. (defun org-entry-get-multivalued-property (pom property)
  11780. "Return a list of values in a multivalued property."
  11781. (let* ((value (org-entry-get pom property))
  11782. (values (and value (split-string value))))
  11783. (mapcar #'org-entry-restore-space values)))
  11784. (defun org-entry-put-multivalued-property (pom property &rest values)
  11785. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11786. VALUES should be a list of strings. Spaces will be protected."
  11787. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11788. (let* ((value (org-entry-get pom property))
  11789. (values (and value (split-string value))))
  11790. (mapcar #'org-entry-restore-space values)))
  11791. (defun org-entry-protect-space (s)
  11792. "Protect spaces and newline in string S."
  11793. (while (string-match " " s)
  11794. (setq s (replace-match "%20" t t s)))
  11795. (while (string-match "\n" s)
  11796. (setq s (replace-match "%0A" t t s)))
  11797. s)
  11798. (defun org-entry-restore-space (s)
  11799. "Restore spaces and newline in string S."
  11800. (while (string-match "%20" s)
  11801. (setq s (replace-match " " t t s)))
  11802. (while (string-match "%0A" s)
  11803. (setq s (replace-match "\n" t t s)))
  11804. s)
  11805. (defvar org-entry-property-inherited-from (make-marker)
  11806. "Marker pointing to the entry from where a property was inherited.
  11807. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11808. location of the entry where the inheritance search matched. If there was
  11809. no match, the marker will point nowhere.
  11810. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11811. is set.")
  11812. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  11813. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11814. The search will stop at the first ancestor which has the property defined.
  11815. If the value found is \"nil\", return nil to show that the property
  11816. should be considered as undefined (this is the meaning of nil here).
  11817. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11818. (move-marker org-entry-property-inherited-from nil)
  11819. (org-with-wide-buffer
  11820. (let (value)
  11821. (catch 'exit
  11822. (while t
  11823. (let ((v (org--property-local-values property literal-nil)))
  11824. (when v
  11825. (setq value
  11826. (concat (mapconcat #'identity (delq nil v) " ")
  11827. (and value " ")
  11828. value)))
  11829. (cond
  11830. ((car v)
  11831. (org-back-to-heading-or-point-min t)
  11832. (move-marker org-entry-property-inherited-from (point))
  11833. (throw 'exit nil))
  11834. ((org-up-heading-or-point-min))
  11835. (t
  11836. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11837. (cond ((not global))
  11838. (value (setq value (concat global " " value)))
  11839. (t (setq value global))))
  11840. (throw 'exit nil))))))
  11841. (if literal-nil value (org-not-nil value)))))
  11842. (defvar org-property-changed-functions nil
  11843. "Hook called when the value of a property has changed.
  11844. Each hook function should accept two arguments, the name of the property
  11845. and the new value.")
  11846. (defun org-entry-put (pom property value)
  11847. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11848. If the value is nil, it is converted to the empty string. If it
  11849. is not a string, an error is raised. Also raise an error on
  11850. invalid property names.
  11851. PROPERTY can be any regular property (see
  11852. `org-special-properties'). It can also be \"TODO\",
  11853. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11854. For the last two properties, VALUE may have any of the special
  11855. values \"earlier\" and \"later\". The function then increases or
  11856. decreases scheduled or deadline date by one day."
  11857. (cond ((null value) (setq value ""))
  11858. ((not (stringp value)) (error "Properties values should be strings"))
  11859. ((not (org--valid-property-p property))
  11860. (user-error "Invalid property name: \"%s\"" property)))
  11861. (org-with-point-at pom
  11862. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11863. (org-back-to-heading-or-point-min t)
  11864. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11865. (let ((beg (point)))
  11866. (cond
  11867. ((equal property "TODO")
  11868. (cond ((not (org-string-nw-p value)) (setq value 'none))
  11869. ((not (member value org-todo-keywords-1))
  11870. (user-error "\"%s\" is not a valid TODO state" value)))
  11871. (org-todo value)
  11872. (org-align-tags))
  11873. ((equal property "PRIORITY")
  11874. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  11875. (org-align-tags))
  11876. ((equal property "SCHEDULED")
  11877. (forward-line)
  11878. (if (and (looking-at-p org-planning-line-re)
  11879. (re-search-forward
  11880. org-scheduled-time-regexp (line-end-position) t))
  11881. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11882. ((string= value "later") (org-timestamp-change 1 'day))
  11883. ((string= value "") (org-schedule '(4)))
  11884. (t (org-schedule nil value)))
  11885. (if (member value '("earlier" "later" ""))
  11886. (call-interactively #'org-schedule)
  11887. (org-schedule nil value))))
  11888. ((equal property "DEADLINE")
  11889. (forward-line)
  11890. (if (and (looking-at-p org-planning-line-re)
  11891. (re-search-forward
  11892. org-deadline-time-regexp (line-end-position) t))
  11893. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11894. ((string= value "later") (org-timestamp-change 1 'day))
  11895. ((string= value "") (org-deadline '(4)))
  11896. (t (org-deadline nil value)))
  11897. (if (member value '("earlier" "later" ""))
  11898. (call-interactively #'org-deadline)
  11899. (org-deadline nil value))))
  11900. ((member property org-special-properties)
  11901. (error "The %s property cannot be set with `org-entry-put'" property))
  11902. (t
  11903. (let* ((range (org-get-property-block beg 'force))
  11904. (end (cdr range))
  11905. (case-fold-search t))
  11906. (goto-char (car range))
  11907. (if (re-search-forward (org-re-property property nil t) end t)
  11908. (progn (delete-region (match-beginning 0) (match-end 0))
  11909. (goto-char (match-beginning 0)))
  11910. (goto-char end)
  11911. (insert "\n")
  11912. (backward-char))
  11913. (insert ":" property ":")
  11914. (when value (insert " " value))
  11915. (org-indent-line)))))
  11916. (run-hook-with-args 'org-property-changed-functions property value)))
  11917. (defun org-buffer-property-keys (&optional specials defaults columns)
  11918. "Get all property keys in the current buffer.
  11919. When SPECIALS is non-nil, also list the special properties that
  11920. reflect things like tags and TODO state.
  11921. When DEFAULTS is non-nil, also include properties that has
  11922. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  11923. DESCRIPTION, LOCATION, and LOGGING and others.
  11924. When COLUMNS in non-nil, also include property names given in
  11925. COLUMN formats in the current buffer."
  11926. (let ((case-fold-search t)
  11927. (props (append
  11928. (and specials org-special-properties)
  11929. (and defaults (cons org-effort-property org-default-properties))
  11930. ;; Get property names from #+PROPERTY keywords as well
  11931. (mapcar (lambda (s)
  11932. (nth 0 (split-string s)))
  11933. (cdar (org-collect-keywords '("PROPERTY")))))))
  11934. (org-with-wide-buffer
  11935. (goto-char (point-min))
  11936. (while (re-search-forward org-property-start-re nil t)
  11937. (catch :skip
  11938. (let ((range (org-get-property-block)))
  11939. (unless range (throw :skip nil))
  11940. (goto-char (car range))
  11941. (let ((begin (car range))
  11942. (end (cdr range)))
  11943. ;; Make sure that found property block is not located
  11944. ;; before current point, as it would generate an infloop.
  11945. ;; It can happen, for example, in the following
  11946. ;; situation:
  11947. ;;
  11948. ;; * Headline
  11949. ;; :PROPERTIES:
  11950. ;; ...
  11951. ;; :END:
  11952. ;; *************** Inlinetask
  11953. ;; #+BEGIN_EXAMPLE
  11954. ;; :PROPERTIES:
  11955. ;; #+END_EXAMPLE
  11956. ;;
  11957. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  11958. (while (< (point) end)
  11959. (let ((p (progn (looking-at org-property-re)
  11960. (match-string-no-properties 2))))
  11961. ;; Only add true property name, not extension symbol.
  11962. (push (if (not (string-match-p "\\+\\'" p)) p
  11963. (substring p 0 -1))
  11964. props))
  11965. (forward-line))))
  11966. (outline-next-heading)))
  11967. (when columns
  11968. (goto-char (point-min))
  11969. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  11970. (let ((element (org-element-at-point)))
  11971. (when (memq (org-element-type element) '(keyword node-property))
  11972. (let ((value (org-element-property :value element))
  11973. (start 0))
  11974. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  11975. \\(?:{[^}]+}\\)?"
  11976. value start)
  11977. (setq start (match-end 0))
  11978. (let ((p (match-string-no-properties 1 value)))
  11979. (unless (member-ignore-case p org-special-properties)
  11980. (push p props))))))))))
  11981. (sort (delete-dups
  11982. (append props
  11983. ;; for each xxx_ALL property, make sure the bare
  11984. ;; xxx property is also included
  11985. (delq nil (mapcar (lambda (p)
  11986. (and (string-match-p "._ALL\\'" p)
  11987. (substring p 0 -4)))
  11988. props))))
  11989. (lambda (a b) (string< (upcase a) (upcase b))))))
  11990. (defun org-property-values (key)
  11991. "List all non-nil values of property KEY in current buffer."
  11992. (org-with-wide-buffer
  11993. (goto-char (point-min))
  11994. (let ((case-fold-search t)
  11995. (re (org-re-property key))
  11996. values)
  11997. (while (re-search-forward re nil t)
  11998. (push (org-entry-get (point) key) values))
  11999. (delete-dups values))))
  12000. (defun org-insert-property-drawer ()
  12001. "Insert a property drawer into the current entry.
  12002. Do nothing if the drawer already exists. The newly created
  12003. drawer is immediately hidden."
  12004. (org-with-wide-buffer
  12005. ;; Set point to the position where the drawer should be inserted.
  12006. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12007. (org-back-to-heading-or-point-min t)
  12008. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12009. (if (org-before-first-heading-p)
  12010. (while (and (org-at-comment-p) (bolp)) (forward-line))
  12011. (progn
  12012. (forward-line)
  12013. (when (looking-at-p org-planning-line-re) (forward-line))))
  12014. (unless (looking-at-p org-property-drawer-re)
  12015. ;; Make sure we start editing a line from current entry, not from
  12016. ;; next one. It prevents extending text properties or overlays
  12017. ;; belonging to the latter.
  12018. (when (and (bolp) (> (point) (point-min))) (backward-char))
  12019. (let ((begin (if (bobp) (point) (1+ (point))))
  12020. (inhibit-read-only t))
  12021. (unless (bobp) (insert "\n"))
  12022. (insert ":PROPERTIES:\n:END:")
  12023. (org-flag-region (line-end-position 0) (point) t 'outline)
  12024. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  12025. (org-indent-region begin (point))))))
  12026. (defun org-insert-drawer (&optional arg drawer)
  12027. "Insert a drawer at point.
  12028. When optional argument ARG is non-nil, insert a property drawer.
  12029. Optional argument DRAWER, when non-nil, is a string representing
  12030. drawer's name. Otherwise, the user is prompted for a name.
  12031. If a region is active, insert the drawer around that region
  12032. instead.
  12033. Point is left between drawer's boundaries."
  12034. (interactive "P")
  12035. (let* ((drawer (if arg "PROPERTIES"
  12036. (or drawer (read-from-minibuffer "Drawer: ")))))
  12037. (cond
  12038. ;; With C-u, fall back on `org-insert-property-drawer'
  12039. (arg (org-insert-property-drawer))
  12040. ;; Check validity of suggested drawer's name.
  12041. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  12042. (user-error "Invalid drawer name"))
  12043. ;; With an active region, insert a drawer at point.
  12044. ((not (org-region-active-p))
  12045. (progn
  12046. (unless (bolp) (insert "\n"))
  12047. (insert (format ":%s:\n\n:END:\n" drawer))
  12048. (forward-line -2)))
  12049. ;; Otherwise, insert the drawer at point
  12050. (t
  12051. (let ((rbeg (region-beginning))
  12052. (rend (copy-marker (region-end))))
  12053. (unwind-protect
  12054. (progn
  12055. (goto-char rbeg)
  12056. (beginning-of-line)
  12057. (when (save-excursion
  12058. (re-search-forward org-outline-regexp-bol rend t))
  12059. (user-error "Drawers cannot contain headlines"))
  12060. ;; Position point at the beginning of the first
  12061. ;; non-blank line in region. Insert drawer's opening
  12062. ;; there, then indent it.
  12063. (org-skip-whitespace)
  12064. (beginning-of-line)
  12065. (insert ":" drawer ":\n")
  12066. (forward-line -1)
  12067. (indent-for-tab-command)
  12068. ;; Move point to the beginning of the first blank line
  12069. ;; after the last non-blank line in region. Insert
  12070. ;; drawer's closing, then indent it.
  12071. (goto-char rend)
  12072. (skip-chars-backward " \r\t\n")
  12073. (insert "\n:END:")
  12074. (deactivate-mark t)
  12075. (indent-for-tab-command)
  12076. (unless (eolp) (insert "\n")))
  12077. ;; Clear marker, whatever the outcome of insertion is.
  12078. (set-marker rend nil)))))))
  12079. (defvar org-property-set-functions-alist nil
  12080. "Property set function alist.
  12081. Each entry should have the following format:
  12082. (PROPERTY . READ-FUNCTION)
  12083. The read function will be called with the same argument as
  12084. `org-completing-read'.")
  12085. (defun org-set-property-function (property)
  12086. "Get the function that should be used to set PROPERTY.
  12087. This is computed according to `org-property-set-functions-alist'."
  12088. (or (cdr (assoc property org-property-set-functions-alist))
  12089. 'org-completing-read))
  12090. (defun org-read-property-value (property &optional pom)
  12091. "Read value for PROPERTY, as a string.
  12092. When optional argument POM is non-nil, completion uses additional
  12093. information, i.e., allowed or existing values at point or marker
  12094. POM."
  12095. (let* ((completion-ignore-case t)
  12096. (allowed
  12097. (or (org-property-get-allowed-values nil property 'table)
  12098. (and pom (org-property-get-allowed-values pom property 'table))))
  12099. (current (org-entry-get nil property))
  12100. (prompt (format "%s value%s: "
  12101. property
  12102. (if (org-string-nw-p current)
  12103. (format " [%s]" current)
  12104. "")))
  12105. (set-function (org-set-property-function property)))
  12106. (org-trim
  12107. (if allowed
  12108. (funcall set-function
  12109. prompt allowed nil
  12110. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  12111. (let ((all (mapcar #'list
  12112. (append (org-property-values property)
  12113. (and pom
  12114. (org-with-point-at pom
  12115. (org-property-values property)))))))
  12116. (funcall set-function prompt all nil nil "" nil current))))))
  12117. (defvar org-last-set-property nil)
  12118. (defvar org-last-set-property-value nil)
  12119. (defun org-read-property-name ()
  12120. "Read a property name."
  12121. (let ((completion-ignore-case t)
  12122. (default-prop (or (and (org-at-property-p)
  12123. (match-string-no-properties 2))
  12124. org-last-set-property)))
  12125. (org-completing-read
  12126. (concat "Property"
  12127. (if default-prop (concat " [" default-prop "]") "")
  12128. ": ")
  12129. (mapcar #'list (org-buffer-property-keys nil t t))
  12130. nil nil nil nil default-prop)))
  12131. (defun org-set-property-and-value (use-last)
  12132. "Allow to set [PROPERTY]: [value] direction from prompt.
  12133. When use-default, don't even ask, just use the last
  12134. \"[PROPERTY]: [value]\" string from the history."
  12135. (interactive "P")
  12136. (let* ((completion-ignore-case t)
  12137. (pv (or (and use-last org-last-set-property-value)
  12138. (org-completing-read
  12139. "Enter a \"[Property]: [value]\" pair: "
  12140. nil nil nil nil nil
  12141. org-last-set-property-value)))
  12142. prop val)
  12143. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12144. (setq prop (match-string 1 pv)
  12145. val (match-string 2 pv))
  12146. (org-set-property prop val))))
  12147. (defun org-set-property (property value)
  12148. "In the current entry, set PROPERTY to VALUE.
  12149. When called interactively, this will prompt for a property name, offering
  12150. completion on existing and default properties. And then it will prompt
  12151. for a value, offering completion either on allowed values (via an inherited
  12152. xxx_ALL property) or on existing values in other instances of this property
  12153. in the current file.
  12154. Throw an error when trying to set a property with an invalid name."
  12155. (interactive (list nil nil))
  12156. (let ((property (or property (org-read-property-name))))
  12157. ;; `org-entry-put' also makes the following check, but this one
  12158. ;; avoids polluting `org-last-set-property' and
  12159. ;; `org-last-set-property-value' needlessly.
  12160. (unless (org--valid-property-p property)
  12161. (user-error "Invalid property name: \"%s\"" property))
  12162. (let ((value (or value (org-read-property-value property)))
  12163. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12164. (setq org-last-set-property property)
  12165. (setq org-last-set-property-value (concat property ": " value))
  12166. ;; Possibly postprocess the inserted value:
  12167. (when fn (setq value (funcall fn value)))
  12168. (unless (equal (org-entry-get nil property) value)
  12169. (org-entry-put nil property value)))))
  12170. (defun org-find-property (property &optional value)
  12171. "Find first entry in buffer that sets PROPERTY.
  12172. When optional argument VALUE is non-nil, only consider an entry
  12173. if it contains PROPERTY set to this value. If PROPERTY should be
  12174. explicitly set to nil, use string \"nil\" for VALUE.
  12175. Return position where the entry begins, or nil if there is no
  12176. such entry. If narrowing is in effect, only search the visible
  12177. part of the buffer."
  12178. (save-excursion
  12179. (goto-char (point-min))
  12180. (let ((case-fold-search t)
  12181. (re (org-re-property property nil (not value) value)))
  12182. (catch 'exit
  12183. (while (re-search-forward re nil t)
  12184. (when (if value (org-at-property-p)
  12185. (org-entry-get (point) property nil t))
  12186. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  12187. (point)))))))))
  12188. (defun org-delete-property (property)
  12189. "In the current entry, delete PROPERTY."
  12190. (interactive
  12191. (let* ((completion-ignore-case t)
  12192. (cat (org-entry-get (point) "CATEGORY"))
  12193. (props0 (org-entry-properties nil 'standard))
  12194. (props (if cat props0
  12195. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12196. (prop (if (< 1 (length props))
  12197. (completing-read "Property: " props nil t)
  12198. (caar props))))
  12199. (list prop)))
  12200. (if (not property)
  12201. (message "No property to delete in this entry")
  12202. (org-entry-delete nil property)
  12203. (message "Property \"%s\" deleted" property)))
  12204. (defun org-delete-property-globally (property)
  12205. "Remove PROPERTY globally, from all entries.
  12206. This function ignores narrowing, if any."
  12207. (interactive
  12208. (let* ((completion-ignore-case t)
  12209. (prop (completing-read
  12210. "Globally remove property: "
  12211. (mapcar #'list (org-buffer-property-keys)))))
  12212. (list prop)))
  12213. (org-with-wide-buffer
  12214. (goto-char (point-min))
  12215. (let ((count 0)
  12216. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12217. (while (re-search-forward re nil t)
  12218. (when (org-entry-delete (point) property) (cl-incf count)))
  12219. (message "Property \"%s\" removed from %d entries" property count))))
  12220. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12221. (defun org-compute-property-at-point ()
  12222. "Compute the property at point.
  12223. This looks for an enclosing column format, extracts the operator and
  12224. then applies it to the property in the column format's scope."
  12225. (interactive)
  12226. (unless (org-at-property-p)
  12227. (user-error "Not at a property"))
  12228. (let ((prop (match-string-no-properties 2)))
  12229. (org-columns-get-format-and-top-level)
  12230. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12231. (user-error "No operator defined for property %s" prop))
  12232. (org-columns-compute prop)))
  12233. (defvar org-property-allowed-value-functions nil
  12234. "Hook for functions supplying allowed values for a specific property.
  12235. The functions must take a single argument, the name of the property, and
  12236. return a flat list of allowed values. If \":ETC\" is one of
  12237. the values, this means that these values are intended as defaults for
  12238. completion, but that other values should be allowed too.
  12239. The functions must return nil if they are not responsible for this
  12240. property.")
  12241. (defun org-property-get-allowed-values (pom property &optional table)
  12242. "Get allowed values for the property PROPERTY.
  12243. When TABLE is non-nil, return an alist that can directly be used for
  12244. completion."
  12245. (let (vals)
  12246. (cond
  12247. ((equal property "TODO")
  12248. (setq vals (org-with-point-at pom
  12249. (append org-todo-keywords-1 '("")))))
  12250. ((equal property "PRIORITY")
  12251. (let ((n org-priority-lowest))
  12252. (while (>= n org-priority-highest)
  12253. (push (char-to-string n) vals)
  12254. (setq n (1- n)))))
  12255. ((equal property "CATEGORY"))
  12256. ((member property org-special-properties))
  12257. ((setq vals (run-hook-with-args-until-success
  12258. 'org-property-allowed-value-functions property)))
  12259. (t
  12260. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12261. (when (and vals (string-match "\\S-" vals))
  12262. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12263. (setq vals (mapcar (lambda (x)
  12264. (cond ((stringp x) x)
  12265. ((numberp x) (number-to-string x))
  12266. ((symbolp x) (symbol-name x))
  12267. (t "???")))
  12268. vals)))))
  12269. (when (member ":ETC" vals)
  12270. (setq vals (remove ":ETC" vals))
  12271. (org-add-props (car vals) '(org-unrestricted t)))
  12272. (if table (mapcar 'list vals) vals)))
  12273. (defun org-property-previous-allowed-value (&optional _previous)
  12274. "Switch to the next allowed value for this property."
  12275. (interactive)
  12276. (org-property-next-allowed-value t))
  12277. (defun org-property-next-allowed-value (&optional previous)
  12278. "Switch to the next allowed value for this property."
  12279. (interactive)
  12280. (unless (org-at-property-p)
  12281. (user-error "Not at a property"))
  12282. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12283. (key (match-string 2))
  12284. (value (match-string 3))
  12285. (allowed (or (org-property-get-allowed-values (point) key)
  12286. (and (member value '("[ ]" "[-]" "[X]"))
  12287. '("[ ]" "[X]"))))
  12288. (heading (save-match-data (nth 4 (org-heading-components))))
  12289. nval)
  12290. (unless allowed
  12291. (user-error "Allowed values for this property have not been defined"))
  12292. (when previous (setq allowed (reverse allowed)))
  12293. (when (member value allowed)
  12294. (setq nval (car (cdr (member value allowed)))))
  12295. (setq nval (or nval (car allowed)))
  12296. (when (equal nval value)
  12297. (user-error "Only one allowed value for this property"))
  12298. (org-at-property-p)
  12299. (replace-match (concat " :" key ": " nval) t t)
  12300. (org-indent-line)
  12301. (beginning-of-line 1)
  12302. (skip-chars-forward " \t")
  12303. (when (equal prop org-effort-property)
  12304. (org-refresh-property
  12305. '((effort . identity)
  12306. (effort-minutes . org-duration-to-minutes))
  12307. nval)
  12308. (when (string= org-clock-current-task heading)
  12309. (setq org-clock-effort nval)
  12310. (org-clock-update-mode-line)))
  12311. (run-hook-with-args 'org-property-changed-functions key nval)))
  12312. (defun org-find-olp (path &optional this-buffer)
  12313. "Return a marker pointing to the entry at outline path OLP.
  12314. If anything goes wrong, throw an error, and if you need to do
  12315. something based on this error, you can catch it with
  12316. `condition-case'.
  12317. If THIS-BUFFER is set, the outline path does not contain a file,
  12318. only headings."
  12319. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12320. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12321. (level 1)
  12322. (lmin 1)
  12323. (lmax 1)
  12324. end found flevel)
  12325. (unless buffer (error "File not found :%s" file))
  12326. (with-current-buffer buffer
  12327. (unless (derived-mode-p 'org-mode)
  12328. (error "Buffer %s needs to be in Org mode" buffer))
  12329. (org-with-wide-buffer
  12330. (goto-char (point-min))
  12331. (dolist (heading path)
  12332. (let ((re (format org-complex-heading-regexp-format
  12333. (regexp-quote heading)))
  12334. (cnt 0))
  12335. (while (re-search-forward re end t)
  12336. (setq level (- (match-end 1) (match-beginning 1)))
  12337. (when (and (>= level lmin) (<= level lmax))
  12338. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12339. (when (= cnt 0)
  12340. (error "Heading not found on level %d: %s" lmax heading))
  12341. (when (> cnt 1)
  12342. (error "Heading not unique on level %d: %s" lmax heading))
  12343. (goto-char found)
  12344. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12345. (setq end (save-excursion (org-end-of-subtree t t)))))
  12346. (when (org-at-heading-p)
  12347. (point-marker))))))
  12348. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12349. "Find node HEADING in BUFFER.
  12350. Return a marker to the heading if it was found, or nil if not.
  12351. If POS-ONLY is set, return just the position instead of a marker.
  12352. The heading text must match exact, but it may have a TODO keyword,
  12353. a priority cookie and tags in the standard locations."
  12354. (with-current-buffer (or buffer (current-buffer))
  12355. (org-with-wide-buffer
  12356. (goto-char (point-min))
  12357. (let (case-fold-search)
  12358. (when (re-search-forward
  12359. (format org-complex-heading-regexp-format
  12360. (regexp-quote heading)) nil t)
  12361. (if pos-only
  12362. (match-beginning 0)
  12363. (move-marker (make-marker) (match-beginning 0))))))))
  12364. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12365. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12366. When the target headline is found, return a marker to this location."
  12367. (let ((files (directory-files (or dir default-directory)
  12368. t "\\`[^.#].*\\.org\\'"))
  12369. visiting m buffer)
  12370. (catch 'found
  12371. (dolist (file files)
  12372. (message "trying %s" file)
  12373. (setq visiting (org-find-base-buffer-visiting file))
  12374. (setq buffer (or visiting (find-file-noselect file)))
  12375. (setq m (org-find-exact-headline-in-buffer
  12376. heading buffer))
  12377. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12378. (and m (throw 'found m))))))
  12379. (defun org-find-entry-with-id (ident)
  12380. "Locate the entry that contains the ID property with exact value IDENT.
  12381. IDENT can be a string, a symbol or a number, this function will search for
  12382. the string representation of it.
  12383. Return the position where this entry starts, or nil if there is no such entry."
  12384. (interactive "sID: ")
  12385. (let ((id (cond
  12386. ((stringp ident) ident)
  12387. ((symbolp ident) (symbol-name ident))
  12388. ((numberp ident) (number-to-string ident))
  12389. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12390. (org-with-wide-buffer (org-find-property "ID" id))))
  12391. ;;;; Timestamps
  12392. (defvar org-last-changed-timestamp nil)
  12393. (defvar org-last-inserted-timestamp nil
  12394. "The last time stamp inserted with `org-insert-time-stamp'.")
  12395. (defun org-time-stamp (arg &optional inactive)
  12396. "Prompt for a date/time and insert a time stamp.
  12397. If the user specifies a time like HH:MM or if this command is
  12398. called with at least one prefix argument, the time stamp contains
  12399. the date and the time. Otherwise, only the date is included.
  12400. All parts of a date not specified by the user are filled in from
  12401. the timestamp at point, if any, or the current date/time
  12402. otherwise.
  12403. If there is already a timestamp at the cursor, it is replaced.
  12404. With two universal prefix arguments, insert an active timestamp
  12405. with the current time without prompting the user.
  12406. When called from lisp, the timestamp is inactive if INACTIVE is
  12407. non-nil."
  12408. (interactive "P")
  12409. (let* ((ts (cond
  12410. ((org-at-date-range-p t)
  12411. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12412. ((org-at-timestamp-p 'lax) (match-string 0))))
  12413. ;; Default time is either the timestamp at point or today.
  12414. ;; When entering a range, only the range start is considered.
  12415. (default-time (and ts (org-time-string-to-time ts)))
  12416. (default-input (and ts (org-get-compact-tod ts)))
  12417. (repeater (and ts
  12418. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12419. (match-string 0 ts)))
  12420. org-time-was-given
  12421. org-end-time-was-given
  12422. (time
  12423. (if (equal arg '(16)) (current-time)
  12424. ;; Preserve `this-command' and `last-command'.
  12425. (let ((this-command this-command)
  12426. (last-command last-command))
  12427. (org-read-date
  12428. arg 'totime nil nil default-time default-input
  12429. inactive)))))
  12430. (cond
  12431. ((and ts
  12432. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12433. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12434. (insert "--")
  12435. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12436. (ts
  12437. ;; Make sure we're on a timestamp. When in the middle of a date
  12438. ;; range, move arbitrarily to range end.
  12439. (unless (org-at-timestamp-p 'lax)
  12440. (skip-chars-forward "-")
  12441. (org-at-timestamp-p 'lax))
  12442. (replace-match "")
  12443. (setq org-last-changed-timestamp
  12444. (org-insert-time-stamp
  12445. time (or org-time-was-given arg)
  12446. inactive nil nil (list org-end-time-was-given)))
  12447. (when repeater
  12448. (backward-char)
  12449. (insert " " repeater)
  12450. (setq org-last-changed-timestamp
  12451. (concat (substring org-last-inserted-timestamp 0 -1)
  12452. " " repeater ">")))
  12453. (message "Timestamp updated"))
  12454. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12455. (t (org-insert-time-stamp
  12456. time (or org-time-was-given arg) inactive nil nil
  12457. (list org-end-time-was-given))))))
  12458. ;; FIXME: can we use this for something else, like computing time differences?
  12459. (defun org-get-compact-tod (s)
  12460. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12461. (let* ((t1 (match-string 1 s))
  12462. (h1 (string-to-number (match-string 2 s)))
  12463. (m1 (string-to-number (match-string 3 s)))
  12464. (t2 (and (match-end 4) (match-string 5 s)))
  12465. (h2 (and t2 (string-to-number (match-string 6 s))))
  12466. (m2 (and t2 (string-to-number (match-string 7 s))))
  12467. dh dm)
  12468. (if (not t2)
  12469. t1
  12470. (setq dh (- h2 h1) dm (- m2 m1))
  12471. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12472. (concat t1 "+" (number-to-string dh)
  12473. (and (/= 0 dm) (format ":%02d" dm)))))))
  12474. (defun org-time-stamp-inactive (&optional arg)
  12475. "Insert an inactive time stamp.
  12476. An inactive time stamp is enclosed in square brackets instead of
  12477. angle brackets. It is inactive in the sense that it does not
  12478. trigger agenda entries. So these are more for recording a
  12479. certain time/date.
  12480. If the user specifies a time like HH:MM or if this command is called with
  12481. at least one prefix argument, the time stamp contains the date and the time.
  12482. Otherwise, only the date is included.
  12483. When called with two universal prefix arguments, insert an inactive time stamp
  12484. with the current time without prompting the user."
  12485. (interactive "P")
  12486. (org-time-stamp arg 'inactive))
  12487. (defvar org-date-ovl (make-overlay 1 1))
  12488. (overlay-put org-date-ovl 'face 'org-date-selected)
  12489. (delete-overlay org-date-ovl)
  12490. (defvar org-ans1) ; dynamically scoped parameter
  12491. (defvar org-ans2) ; dynamically scoped parameter
  12492. (defvar org-plain-time-of-day-regexp) ; defined below
  12493. (defvar org-overriding-default-time nil) ; dynamically scoped
  12494. (defvar org-read-date-overlay nil)
  12495. (defvar org-read-date-history nil)
  12496. (defvar org-read-date-final-answer nil)
  12497. (defvar org-read-date-analyze-futurep nil)
  12498. (defvar org-read-date-analyze-forced-year nil)
  12499. (defvar org-read-date-inactive)
  12500. (defvar org-def)
  12501. (defvar org-defdecode)
  12502. (defvar org-with-time)
  12503. (defvar calendar-setup) ; Dynamically scoped.
  12504. (defun org-read-date (&optional with-time to-time from-string prompt
  12505. default-time default-input inactive)
  12506. "Read a date, possibly a time, and make things smooth for the user.
  12507. The prompt will suggest to enter an ISO date, but you can also enter anything
  12508. which will at least partially be understood by `parse-time-string'.
  12509. Unrecognized parts of the date will default to the current day, month, year,
  12510. hour and minute. If this command is called to replace a timestamp at point,
  12511. or to enter the second timestamp of a range, the default time is taken
  12512. from the existing stamp. Furthermore, the command prefers the future,
  12513. so if you are giving a date where the year is not given, and the day-month
  12514. combination is already past in the current year, it will assume you
  12515. mean next year. For details, see the manual. A few examples:
  12516. 3-2-5 --> 2003-02-05
  12517. feb 15 --> currentyear-02-15
  12518. 2/15 --> currentyear-02-15
  12519. sep 12 9 --> 2009-09-12
  12520. 12:45 --> today 12:45
  12521. 22 sept 0:34 --> currentyear-09-22 0:34
  12522. 12 --> currentyear-currentmonth-12
  12523. Fri --> nearest Friday after today
  12524. -Tue --> last Tuesday
  12525. etc.
  12526. Furthermore you can specify a relative date by giving, as the *first* thing
  12527. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12528. change in days weeks, months, years.
  12529. With a single plus or minus, the date is relative to today. With a double
  12530. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12531. +4d --> four days from today
  12532. +4 --> same as above
  12533. +2w --> two weeks from today
  12534. ++5 --> five days from default date
  12535. The function understands only English month and weekday abbreviations.
  12536. While prompting, a calendar is popped up - you can also select the
  12537. date with the mouse (button 1). The calendar shows a period of three
  12538. months. To scroll it to other months, use the keys `>' and `<'.
  12539. If you don't like the calendar, turn it off with
  12540. (setq org-read-date-popup-calendar nil)
  12541. With optional argument TO-TIME, the date will immediately be converted
  12542. to an internal time.
  12543. With an optional argument WITH-TIME, the prompt will suggest to
  12544. also insert a time. Note that when WITH-TIME is not set, you can
  12545. still enter a time, and this function will inform the calling routine
  12546. about this change. The calling routine may then choose to change the
  12547. format used to insert the time stamp into the buffer to include the time.
  12548. With optional argument FROM-STRING, read from this string instead from
  12549. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12550. the time/date that is used for everything that is not specified by the
  12551. user."
  12552. (require 'parse-time)
  12553. (let* ((org-with-time with-time)
  12554. (org-time-stamp-rounding-minutes
  12555. (if (equal org-with-time '(16))
  12556. '(0 0)
  12557. org-time-stamp-rounding-minutes))
  12558. (ct (org-current-time))
  12559. (org-def (or org-overriding-default-time default-time ct))
  12560. (org-defdecode (decode-time org-def))
  12561. (cur-frame (selected-frame))
  12562. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12563. (calendar-setup
  12564. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12565. (calendar-move-hook nil)
  12566. (calendar-view-diary-initially-flag nil)
  12567. (calendar-view-holidays-initially-flag nil)
  12568. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12569. ;; Rationalize `org-def' and `org-defdecode', if required.
  12570. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12571. (setf (nth 2 org-defdecode) -1)
  12572. (setf (nth 1 org-defdecode) 59)
  12573. (setq org-def (apply #'encode-time org-defdecode))
  12574. (setq org-defdecode (decode-time org-def)))
  12575. (let* ((timestr (format-time-string
  12576. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12577. org-def))
  12578. (prompt (concat (if prompt (concat prompt " ") "")
  12579. (format "Date+time [%s]: " timestr))))
  12580. (cond
  12581. (from-string (setq ans from-string))
  12582. (org-read-date-popup-calendar
  12583. (save-excursion
  12584. (save-window-excursion
  12585. (calendar)
  12586. (when (eq calendar-setup 'calendar-only)
  12587. (setq cal-frame
  12588. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12589. (select-frame cal-frame))
  12590. (org-eval-in-calendar '(setq cursor-type nil) t)
  12591. (unwind-protect
  12592. (progn
  12593. (calendar-forward-day (- (time-to-days org-def)
  12594. (calendar-absolute-from-gregorian
  12595. (calendar-current-date))))
  12596. (org-eval-in-calendar nil t)
  12597. (let* ((old-map (current-local-map))
  12598. (map (copy-keymap calendar-mode-map))
  12599. (minibuffer-local-map
  12600. (copy-keymap org-read-date-minibuffer-local-map)))
  12601. (org-defkey map (kbd "RET") 'org-calendar-select)
  12602. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12603. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12604. (unwind-protect
  12605. (progn
  12606. (use-local-map map)
  12607. (setq org-read-date-inactive inactive)
  12608. (add-hook 'post-command-hook 'org-read-date-display)
  12609. (setq org-ans0
  12610. (read-string prompt
  12611. default-input
  12612. 'org-read-date-history
  12613. nil))
  12614. ;; org-ans0: from prompt
  12615. ;; org-ans1: from mouse click
  12616. ;; org-ans2: from calendar motion
  12617. (setq ans
  12618. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12619. (remove-hook 'post-command-hook 'org-read-date-display)
  12620. (use-local-map old-map)
  12621. (when org-read-date-overlay
  12622. (delete-overlay org-read-date-overlay)
  12623. (setq org-read-date-overlay nil)))))
  12624. (bury-buffer "*Calendar*")
  12625. (when cal-frame
  12626. (delete-frame cal-frame)
  12627. (select-frame-set-input-focus cur-frame))))))
  12628. (t ; Naked prompt only
  12629. (unwind-protect
  12630. (setq ans (read-string prompt default-input
  12631. 'org-read-date-history timestr))
  12632. (when org-read-date-overlay
  12633. (delete-overlay org-read-date-overlay)
  12634. (setq org-read-date-overlay nil))))))
  12635. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12636. (when org-read-date-analyze-forced-year
  12637. (message "Year was forced into %s"
  12638. (if org-read-date-force-compatible-dates
  12639. "compatible range (1970-2037)"
  12640. "range representable on this machine"))
  12641. (ding))
  12642. (setq final (apply #'encode-time final))
  12643. (setq org-read-date-final-answer ans)
  12644. (if to-time
  12645. final
  12646. ;; This round-trip gets rid of 34th of August and stuff like that....
  12647. (setq final (decode-time final))
  12648. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12649. (format "%04d-%02d-%02d %02d:%02d"
  12650. (nth 5 final) (nth 4 final) (nth 3 final)
  12651. (nth 2 final) (nth 1 final))
  12652. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12653. (defun org-read-date-display ()
  12654. "Display the current date prompt interpretation in the minibuffer."
  12655. (when org-read-date-display-live
  12656. (when org-read-date-overlay
  12657. (delete-overlay org-read-date-overlay))
  12658. (when (minibufferp (current-buffer))
  12659. (save-excursion
  12660. (end-of-line 1)
  12661. (while (not (equal (buffer-substring
  12662. (max (point-min) (- (point) 4)) (point))
  12663. " "))
  12664. (insert " ")))
  12665. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12666. " " (or org-ans1 org-ans2)))
  12667. (org-end-time-was-given nil)
  12668. (f (org-read-date-analyze ans org-def org-defdecode))
  12669. (fmts (if org-display-custom-times
  12670. org-time-stamp-custom-formats
  12671. org-time-stamp-formats))
  12672. (fmt (if (or org-with-time
  12673. (and (boundp 'org-time-was-given) org-time-was-given))
  12674. (cdr fmts)
  12675. (car fmts)))
  12676. (txt (format-time-string fmt (apply #'encode-time f)))
  12677. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12678. (txt (concat "=> " txt)))
  12679. (when (and org-end-time-was-given
  12680. (string-match org-plain-time-of-day-regexp txt))
  12681. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12682. org-end-time-was-given
  12683. (substring txt (match-end 0)))))
  12684. (when org-read-date-analyze-futurep
  12685. (setq txt (concat txt " (=>F)")))
  12686. (setq org-read-date-overlay
  12687. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  12688. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12689. (defun org-read-date-analyze (ans def defdecode)
  12690. "Analyze the combined answer of the date prompt."
  12691. ;; FIXME: cleanup and comment
  12692. (let ((org-def def)
  12693. (org-defdecode defdecode)
  12694. (nowdecode (decode-time))
  12695. delta deltan deltaw deltadef year month day
  12696. hour minute second wday pm h2 m2 tl wday1
  12697. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12698. (setq org-read-date-analyze-futurep nil
  12699. org-read-date-analyze-forced-year nil)
  12700. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12701. (setq ans "+0"))
  12702. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12703. (setq ans (replace-match "" t t ans)
  12704. deltan (car delta)
  12705. deltaw (nth 1 delta)
  12706. deltadef (nth 2 delta)))
  12707. ;; Check if there is an iso week date in there. If yes, store the
  12708. ;; info and postpone interpreting it until the rest of the parsing
  12709. ;; is done.
  12710. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12711. (setq iso-year (when (match-end 1)
  12712. (org-small-year-to-year
  12713. (string-to-number (match-string 1 ans))))
  12714. iso-weekday (when (match-end 3)
  12715. (string-to-number (match-string 3 ans)))
  12716. iso-week (string-to-number (match-string 2 ans)))
  12717. (setq ans (replace-match "" t t ans)))
  12718. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12719. (when (string-match
  12720. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12721. (setq year (if (match-end 2)
  12722. (string-to-number (match-string 2 ans))
  12723. (progn (setq kill-year t)
  12724. (string-to-number (format-time-string "%Y"))))
  12725. month (string-to-number (match-string 3 ans))
  12726. day (string-to-number (match-string 4 ans)))
  12727. (setq year (org-small-year-to-year year))
  12728. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12729. t nil ans)))
  12730. ;; Help matching dotted european dates
  12731. (when (string-match
  12732. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12733. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12734. (setq kill-year t)
  12735. (string-to-number (format-time-string "%Y")))
  12736. day (string-to-number (match-string 1 ans))
  12737. month (string-to-number (match-string 2 ans))
  12738. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12739. t nil ans)))
  12740. ;; Help matching american dates, like 5/30 or 5/30/7
  12741. (when (string-match
  12742. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12743. (setq year (if (match-end 4)
  12744. (string-to-number (match-string 4 ans))
  12745. (progn (setq kill-year t)
  12746. (string-to-number (format-time-string "%Y"))))
  12747. month (string-to-number (match-string 1 ans))
  12748. day (string-to-number (match-string 2 ans)))
  12749. (setq year (org-small-year-to-year year))
  12750. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12751. t nil ans)))
  12752. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12753. ;; If there is a time with am/pm, and *no* time without it, we convert
  12754. ;; so that matching will be successful.
  12755. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12756. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12757. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12758. (setq hour (string-to-number (match-string 1 ans))
  12759. minute (if (match-end 3)
  12760. (string-to-number (match-string 3 ans))
  12761. 0)
  12762. pm (equal ?p
  12763. (string-to-char (downcase (match-string 4 ans)))))
  12764. (if (and (= hour 12) (not pm))
  12765. (setq hour 0)
  12766. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12767. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12768. t t ans))))
  12769. ;; Check if a time range is given as a duration
  12770. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12771. (setq hour (string-to-number (match-string 1 ans))
  12772. h2 (+ hour (string-to-number (match-string 3 ans)))
  12773. minute (string-to-number (match-string 2 ans))
  12774. m2 (+ minute (if (match-end 5) (string-to-number
  12775. (match-string 5 ans))0)))
  12776. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12777. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12778. t t ans)))
  12779. ;; Check if there is a time range
  12780. (when (boundp 'org-end-time-was-given)
  12781. (setq org-time-was-given nil)
  12782. (when (and (string-match org-plain-time-of-day-regexp ans)
  12783. (match-end 8))
  12784. (setq org-end-time-was-given (match-string 8 ans))
  12785. (setq ans (concat (substring ans 0 (match-beginning 7))
  12786. (substring ans (match-end 7))))))
  12787. (setq tl (parse-time-string ans)
  12788. day (or (nth 3 tl) (nth 3 org-defdecode))
  12789. month
  12790. (cond ((nth 4 tl))
  12791. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12792. ;; Day was specified. Make sure DAY+MONTH
  12793. ;; combination happens in the future.
  12794. ((nth 3 tl)
  12795. (setq futurep t)
  12796. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12797. (nth 4 nowdecode)))
  12798. (t (nth 4 org-defdecode)))
  12799. year
  12800. (cond ((and (not kill-year) (nth 5 tl)))
  12801. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12802. ;; Month was guessed in the future and is at least
  12803. ;; equal to NOWDECODE's. Fix year accordingly.
  12804. (futurep
  12805. (if (or (> month (nth 4 nowdecode))
  12806. (>= day (nth 3 nowdecode)))
  12807. (nth 5 nowdecode)
  12808. (1+ (nth 5 nowdecode))))
  12809. ;; Month was specified. Make sure MONTH+YEAR
  12810. ;; combination happens in the future.
  12811. ((nth 4 tl)
  12812. (setq futurep t)
  12813. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12814. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12815. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12816. (t (nth 5 nowdecode))))
  12817. (t (nth 5 org-defdecode)))
  12818. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12819. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12820. second (or (nth 0 tl) 0)
  12821. wday (nth 6 tl))
  12822. (when (and (eq org-read-date-prefer-future 'time)
  12823. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12824. (equal day (nth 3 nowdecode))
  12825. (equal month (nth 4 nowdecode))
  12826. (equal year (nth 5 nowdecode))
  12827. (nth 2 tl)
  12828. (or (< (nth 2 tl) (nth 2 nowdecode))
  12829. (and (= (nth 2 tl) (nth 2 nowdecode))
  12830. (nth 1 tl)
  12831. (< (nth 1 tl) (nth 1 nowdecode)))))
  12832. (setq day (1+ day)
  12833. futurep t))
  12834. ;; Special date definitions below
  12835. (cond
  12836. (iso-week
  12837. ;; There was an iso week
  12838. (require 'cal-iso)
  12839. (setq futurep nil)
  12840. (setq year (or iso-year year)
  12841. day (or iso-weekday wday 1)
  12842. wday nil ; to make sure that the trigger below does not match
  12843. iso-date (calendar-gregorian-from-absolute
  12844. (calendar-iso-to-absolute
  12845. (list iso-week day year))))
  12846. ; FIXME: Should we also push ISO weeks into the future?
  12847. ; (when (and org-read-date-prefer-future
  12848. ; (not iso-year)
  12849. ; (< (calendar-absolute-from-gregorian iso-date)
  12850. ; (time-to-days nil)))
  12851. ; (setq year (1+ year)
  12852. ; iso-date (calendar-gregorian-from-absolute
  12853. ; (calendar-iso-to-absolute
  12854. ; (list iso-week day year)))))
  12855. (setq month (car iso-date)
  12856. year (nth 2 iso-date)
  12857. day (nth 1 iso-date)))
  12858. (deltan
  12859. (setq futurep nil)
  12860. (unless deltadef
  12861. (let ((now (decode-time)))
  12862. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  12863. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  12864. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  12865. ((equal deltaw "m") (setq month (+ month deltan)))
  12866. ((equal deltaw "y") (setq year (+ year deltan)))))
  12867. ((and wday (not (nth 3 tl)))
  12868. ;; Weekday was given, but no day, so pick that day in the week
  12869. ;; on or after the derived date.
  12870. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  12871. (unless (equal wday wday1)
  12872. (setq day (+ day (% (- wday wday1 -7) 7))))))
  12873. (when (and (boundp 'org-time-was-given)
  12874. (nth 2 tl))
  12875. (setq org-time-was-given t))
  12876. (when (< year 100) (setq year (+ 2000 year)))
  12877. ;; Check of the date is representable
  12878. (if org-read-date-force-compatible-dates
  12879. (progn
  12880. (when (< year 1970)
  12881. (setq year 1970 org-read-date-analyze-forced-year t))
  12882. (when (> year 2037)
  12883. (setq year 2037 org-read-date-analyze-forced-year t)))
  12884. (condition-case nil
  12885. (ignore (encode-time second minute hour day month year))
  12886. (error
  12887. (setq year (nth 5 org-defdecode))
  12888. (setq org-read-date-analyze-forced-year t))))
  12889. (setq org-read-date-analyze-futurep futurep)
  12890. (list second minute hour day month year)))
  12891. (defvar parse-time-weekdays)
  12892. (defun org-read-date-get-relative (s today default)
  12893. "Check string S for special relative date string.
  12894. TODAY and DEFAULT are internal times, for today and for a default.
  12895. Return shift list (N what def-flag)
  12896. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  12897. N is the number of WHATs to shift.
  12898. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  12899. the DEFAULT date rather than TODAY."
  12900. (require 'parse-time)
  12901. (when (and
  12902. (string-match
  12903. (concat
  12904. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  12905. "\\([0-9]+\\)?"
  12906. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  12907. "\\([ \t]\\|$\\)") s)
  12908. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  12909. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  12910. (string-to-char (substring (match-string 1 s) -1))
  12911. ?+))
  12912. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  12913. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  12914. (what (if (match-end 3) (match-string 3 s) "d"))
  12915. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  12916. (date (if rel default today))
  12917. (wday (nth 6 (decode-time date)))
  12918. delta)
  12919. (if wday1
  12920. (progn
  12921. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  12922. (when (= delta 0) (setq delta 7))
  12923. (when (= dir ?-)
  12924. (setq delta (- delta 7))
  12925. (when (= delta 0) (setq delta -7)))
  12926. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  12927. (list delta "d" rel))
  12928. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  12929. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  12930. "Turn a user-specified date into the internal representation.
  12931. The internal representation needed by the calendar is (month day year).
  12932. This is a wrapper to handle the brain-dead convention in calendar that
  12933. user function argument order change dependent on argument order."
  12934. (pcase calendar-date-style
  12935. (`american (list arg1 arg2 arg3))
  12936. (`european (list arg2 arg1 arg3))
  12937. (`iso (list arg2 arg3 arg1))))
  12938. (defun org-eval-in-calendar (form &optional keepdate)
  12939. "Eval FORM in the calendar window and return to current window.
  12940. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  12941. (let ((sf (selected-frame))
  12942. (sw (selected-window)))
  12943. (select-window (get-buffer-window "*Calendar*" t))
  12944. (eval form)
  12945. (when (and (not keepdate) (calendar-cursor-to-date))
  12946. (let* ((date (calendar-cursor-to-date))
  12947. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12948. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  12949. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  12950. (select-window sw)
  12951. (select-frame-set-input-focus sf)))
  12952. (defun org-calendar-select ()
  12953. "Return to `org-read-date' with the date currently selected.
  12954. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12955. (interactive)
  12956. (when (calendar-cursor-to-date)
  12957. (let* ((date (calendar-cursor-to-date))
  12958. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12959. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12960. (when (active-minibuffer-window) (exit-minibuffer))))
  12961. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  12962. "Insert a date stamp for the date given by the internal TIME.
  12963. See `format-time-string' for the format of TIME.
  12964. WITH-HM means use the stamp format that includes the time of the day.
  12965. INACTIVE means use square brackets instead of angular ones, so that the
  12966. stamp will not contribute to the agenda.
  12967. PRE and POST are optional strings to be inserted before and after the
  12968. stamp.
  12969. The command returns the inserted time stamp."
  12970. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  12971. stamp)
  12972. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  12973. (insert-before-markers (or pre ""))
  12974. (when (listp extra)
  12975. (setq extra (car extra))
  12976. (if (and (stringp extra)
  12977. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  12978. (setq extra (format "-%02d:%02d"
  12979. (string-to-number (match-string 1 extra))
  12980. (string-to-number (match-string 2 extra))))
  12981. (setq extra nil)))
  12982. (when extra
  12983. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  12984. (insert-before-markers (setq stamp (format-time-string fmt time)))
  12985. (insert-before-markers (or post ""))
  12986. (setq org-last-inserted-timestamp stamp)))
  12987. (defun org-toggle-time-stamp-overlays ()
  12988. "Toggle the use of custom time stamp formats."
  12989. (interactive)
  12990. (setq org-display-custom-times (not org-display-custom-times))
  12991. (unless org-display-custom-times
  12992. (let ((p (point-min)) (bmp (buffer-modified-p)))
  12993. (while (setq p (next-single-property-change p 'display))
  12994. (when (and (get-text-property p 'display)
  12995. (eq (get-text-property p 'face) 'org-date))
  12996. (remove-text-properties
  12997. p (setq p (next-single-property-change p 'display))
  12998. '(display t))))
  12999. (set-buffer-modified-p bmp)))
  13000. (org-restart-font-lock)
  13001. (setq org-table-may-need-update t)
  13002. (if org-display-custom-times
  13003. (message "Time stamps are overlaid with custom format")
  13004. (message "Time stamp overlays removed")))
  13005. (defun org-display-custom-time (beg end)
  13006. "Overlay modified time stamp format over timestamp between BEG and END."
  13007. (let* ((ts (buffer-substring beg end))
  13008. t1 with-hm tf time str (off 0))
  13009. (save-match-data
  13010. (setq t1 (org-parse-time-string ts t))
  13011. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  13012. (setq off (- (match-end 0) (match-beginning 0)))))
  13013. (setq end (- end off))
  13014. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  13015. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  13016. time (org-fix-decoded-time t1)
  13017. str (org-add-props
  13018. (format-time-string
  13019. (substring tf 1 -1) (apply 'encode-time time))
  13020. nil 'mouse-face 'highlight))
  13021. (put-text-property beg end 'display str)))
  13022. (defun org-fix-decoded-time (time)
  13023. "Set 0 instead of nil for the first 6 elements of time.
  13024. Don't touch the rest."
  13025. (let ((n 0))
  13026. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  13027. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  13028. "Difference between TIMESTAMP-STRING and now in days.
  13029. If SECONDS is non-nil, return the difference in seconds."
  13030. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  13031. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  13032. (funcall fdiff nil))))
  13033. (defun org-deadline-close-p (timestamp-string &optional ndays)
  13034. "Is the time in TIMESTAMP-STRING close to the current date?"
  13035. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  13036. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  13037. (not (org-entry-is-done-p))))
  13038. (defun org-get-wdays (ts &optional delay zero-delay)
  13039. "Get the deadline lead time appropriate for timestring TS.
  13040. When DELAY is non-nil, get the delay time for scheduled items
  13041. instead of the deadline lead time. When ZERO-DELAY is non-nil
  13042. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  13043. don't try to find the delay cookie in the scheduled timestamp."
  13044. (let ((tv (if delay org-scheduled-delay-days
  13045. org-deadline-warning-days)))
  13046. (cond
  13047. ((or (and delay (< tv 0))
  13048. (and delay zero-delay (<= tv 0))
  13049. (and (not delay) (<= tv 0)))
  13050. ;; Enforce this value no matter what
  13051. (- tv))
  13052. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  13053. ;; lead time is specified.
  13054. (floor (* (string-to-number (match-string 1 ts))
  13055. (cdr (assoc (match-string 2 ts)
  13056. '(("d" . 1) ("w" . 7)
  13057. ("m" . 30.4) ("y" . 365.25)
  13058. ("h" . 0.041667)))))))
  13059. ;; go for the default.
  13060. (t tv))))
  13061. (defun org-calendar-select-mouse (ev)
  13062. "Return to `org-read-date' with the date currently selected.
  13063. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13064. (interactive "e")
  13065. (mouse-set-point ev)
  13066. (when (calendar-cursor-to-date)
  13067. (let* ((date (calendar-cursor-to-date))
  13068. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13069. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13070. (when (active-minibuffer-window) (exit-minibuffer))))
  13071. (defun org-check-deadlines (ndays)
  13072. "Check if there are any deadlines due or past due.
  13073. A deadline is considered due if it happens within `org-deadline-warning-days'
  13074. days from today's date. If the deadline appears in an entry marked DONE,
  13075. it is not shown. A numeric prefix argument NDAYS can be used to test that
  13076. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  13077. are shown."
  13078. (interactive "P")
  13079. (let* ((org-warn-days
  13080. (cond
  13081. ((equal ndays '(4)) 100000)
  13082. (ndays (prefix-numeric-value ndays))
  13083. (t (abs org-deadline-warning-days))))
  13084. (case-fold-search nil)
  13085. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  13086. (callback
  13087. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  13088. (message "%d deadlines past-due or due within %d days"
  13089. (org-occur regexp nil callback)
  13090. org-warn-days)))
  13091. (defsubst org-re-timestamp (type)
  13092. "Return a regexp for timestamp TYPE.
  13093. Allowed values for TYPE are:
  13094. all: all timestamps
  13095. active: only active timestamps (<...>)
  13096. inactive: only inactive timestamps ([...])
  13097. scheduled: only scheduled timestamps
  13098. deadline: only deadline timestamps
  13099. closed: only closed time-stamps
  13100. When TYPE is nil, fall back on returning a regexp that matches
  13101. both scheduled and deadline timestamps."
  13102. (cl-case type
  13103. (all org-ts-regexp-both)
  13104. (active org-ts-regexp)
  13105. (inactive org-ts-regexp-inactive)
  13106. (scheduled org-scheduled-time-regexp)
  13107. (deadline org-deadline-time-regexp)
  13108. (closed org-closed-time-regexp)
  13109. (otherwise
  13110. (concat "\\<"
  13111. (regexp-opt (list org-deadline-string org-scheduled-string))
  13112. " *<\\([^>]+\\)>"))))
  13113. (defun org-check-before-date (d)
  13114. "Check if there are deadlines or scheduled entries before date D."
  13115. (interactive (list (org-read-date)))
  13116. (let* ((case-fold-search nil)
  13117. (regexp (org-re-timestamp org-ts-type))
  13118. (ts-type org-ts-type)
  13119. (callback
  13120. (lambda ()
  13121. (let ((match (match-string 1)))
  13122. (and (if (memq ts-type '(active inactive all))
  13123. (eq (org-element-type (save-excursion
  13124. (backward-char)
  13125. (org-element-context)))
  13126. 'timestamp)
  13127. (org-at-planning-p))
  13128. (time-less-p
  13129. (org-time-string-to-time match)
  13130. (org-time-string-to-time d)))))))
  13131. (message "%d entries before %s"
  13132. (org-occur regexp nil callback)
  13133. d)))
  13134. (defun org-check-after-date (d)
  13135. "Check if there are deadlines or scheduled entries after date D."
  13136. (interactive (list (org-read-date)))
  13137. (let* ((case-fold-search nil)
  13138. (regexp (org-re-timestamp org-ts-type))
  13139. (ts-type org-ts-type)
  13140. (callback
  13141. (lambda ()
  13142. (let ((match (match-string 1)))
  13143. (and (if (memq ts-type '(active inactive all))
  13144. (eq (org-element-type (save-excursion
  13145. (backward-char)
  13146. (org-element-context)))
  13147. 'timestamp)
  13148. (org-at-planning-p))
  13149. (not (time-less-p
  13150. (org-time-string-to-time match)
  13151. (org-time-string-to-time d))))))))
  13152. (message "%d entries after %s"
  13153. (org-occur regexp nil callback)
  13154. d)))
  13155. (defun org-check-dates-range (start-date end-date)
  13156. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13157. (interactive (list (org-read-date nil nil nil "Range starts")
  13158. (org-read-date nil nil nil "Range end")))
  13159. (let ((case-fold-search nil)
  13160. (regexp (org-re-timestamp org-ts-type))
  13161. (callback
  13162. (let ((type org-ts-type))
  13163. (lambda ()
  13164. (let ((match (match-string 1)))
  13165. (and
  13166. (if (memq type '(active inactive all))
  13167. (eq (org-element-type (save-excursion
  13168. (backward-char)
  13169. (org-element-context)))
  13170. 'timestamp)
  13171. (org-at-planning-p))
  13172. (not (time-less-p
  13173. (org-time-string-to-time match)
  13174. (org-time-string-to-time start-date)))
  13175. (time-less-p
  13176. (org-time-string-to-time match)
  13177. (org-time-string-to-time end-date))))))))
  13178. (message "%d entries between %s and %s"
  13179. (org-occur regexp nil callback) start-date end-date)))
  13180. (defun org-evaluate-time-range (&optional to-buffer)
  13181. "Evaluate a time range by computing the difference between start and end.
  13182. Normally the result is just printed in the echo area, but with prefix arg
  13183. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13184. If the time range is actually in a table, the result is inserted into the
  13185. next column.
  13186. For time difference computation, a year is assumed to be exactly 365
  13187. days in order to avoid rounding problems."
  13188. (interactive "P")
  13189. (or
  13190. (org-clock-update-time-maybe)
  13191. (save-excursion
  13192. (unless (org-at-date-range-p t)
  13193. (goto-char (point-at-bol))
  13194. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13195. (unless (org-at-date-range-p t)
  13196. (user-error "Not at a time-stamp range, and none found in current line")))
  13197. (let* ((ts1 (match-string 1))
  13198. (ts2 (match-string 2))
  13199. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13200. (match-end (match-end 0))
  13201. (time1 (org-time-string-to-time ts1))
  13202. (time2 (org-time-string-to-time ts2))
  13203. (diff (abs (float-time (time-subtract time2 time1))))
  13204. (negative (time-less-p time2 time1))
  13205. ;; (ys (floor (* 365 24 60 60)))
  13206. (ds (* 24 60 60))
  13207. (hs (* 60 60))
  13208. (fy "%dy %dd %02d:%02d")
  13209. (fy1 "%dy %dd")
  13210. (fd "%dd %02d:%02d")
  13211. (fd1 "%dd")
  13212. (fh "%02d:%02d")
  13213. y d h m align)
  13214. (if havetime
  13215. (setq ; y (floor diff ys) diff (mod diff ys)
  13216. y 0
  13217. d (floor diff ds) diff (mod diff ds)
  13218. h (floor diff hs) diff (mod diff hs)
  13219. m (floor diff 60))
  13220. (setq ; y (floor diff ys) diff (mod diff ys)
  13221. y 0
  13222. d (round diff ds)
  13223. h 0 m 0))
  13224. (if (not to-buffer)
  13225. (message "%s" (org-make-tdiff-string y d h m))
  13226. (if (org-at-table-p)
  13227. (progn
  13228. (goto-char match-end)
  13229. (setq align t)
  13230. (and (looking-at " *|") (goto-char (match-end 0))))
  13231. (goto-char match-end))
  13232. (when (looking-at
  13233. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13234. (replace-match ""))
  13235. (when negative (insert " -"))
  13236. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13237. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13238. (insert " " (format fh h m))))
  13239. (when align (org-table-align))
  13240. (message "Time difference inserted")))))
  13241. (defun org-make-tdiff-string (y d h m)
  13242. (let ((fmt "")
  13243. (l nil))
  13244. (when (> y 0)
  13245. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13246. (push y l))
  13247. (when (> d 0)
  13248. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13249. (push d l))
  13250. (when (> h 0)
  13251. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13252. (push h l))
  13253. (when (> m 0)
  13254. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13255. (push m l))
  13256. (apply 'format fmt (nreverse l))))
  13257. (defun org-time-string-to-time (s)
  13258. "Convert timestamp string S into internal time."
  13259. (apply #'encode-time (org-parse-time-string s)))
  13260. (defun org-time-string-to-seconds (s)
  13261. "Convert a timestamp string S into a number of seconds."
  13262. (float-time (org-time-string-to-time s)))
  13263. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13264. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13265. "Convert time stamp S to an absolute day number.
  13266. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13267. stamp, get the closest date to DAYNR. If PREFER is
  13268. `past' (respectively `future') return a date past (respectively
  13269. after) or equal to DAYNR.
  13270. POS is the location of time stamp S, as a buffer position in
  13271. BUFFER.
  13272. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13273. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13274. signaled."
  13275. (cond
  13276. ((string-match "\\`%%\\((.*)\\)" s)
  13277. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13278. ;; only able to match individual dates. If it fails, raise an
  13279. ;; error.
  13280. (if (and daynr
  13281. (org-diary-sexp-entry
  13282. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13283. daynr
  13284. (signal 'org-diary-sexp-no-match (list s))))
  13285. (daynr (org-closest-date s daynr prefer))
  13286. (t (time-to-days
  13287. (condition-case errdata
  13288. (org-time-string-to-time s)
  13289. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13290. s
  13291. (if (not (and buffer pos)) ""
  13292. (format-message " at %d in buffer `%s'" pos buffer))
  13293. (cdr errdata))))))))
  13294. (defun org-days-to-iso-week (days)
  13295. "Return the ISO week number."
  13296. (require 'cal-iso)
  13297. (car (calendar-iso-from-absolute days)))
  13298. (defun org-small-year-to-year (year)
  13299. "Convert 2-digit years into 4-digit years.
  13300. YEAR is expanded into one of the 30 next years, if possible, or
  13301. into a past one. Any year larger than 99 is returned unchanged."
  13302. (if (>= year 100) year
  13303. (let* ((current (string-to-number (format-time-string "%Y")))
  13304. (century (/ current 100))
  13305. (offset (- year (% current 100))))
  13306. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13307. ((> offset -70) (+ (* century 100) year))
  13308. (t (+ (* (1+ century) 100) year))))))
  13309. (defun org-time-from-absolute (d)
  13310. "Return the time corresponding to date D.
  13311. D may be an absolute day number, or a calendar-type list (month day year)."
  13312. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13313. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13314. (defvar org-agenda-current-date)
  13315. (defun org-calendar-holiday ()
  13316. "List of holidays, for Diary display in Org mode."
  13317. (require 'holidays)
  13318. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13319. (and hl (mapconcat #'identity hl "; "))))
  13320. (defun org-diary-sexp-entry (sexp entry d)
  13321. "Process a SEXP diary ENTRY for date D."
  13322. (require 'diary-lib)
  13323. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13324. ;; dynamically.
  13325. (let* ((sexp `(let ((entry ,entry)
  13326. (date ',d))
  13327. ,(car (read-from-string sexp))))
  13328. (result (if calendar-debug-sexp (eval sexp)
  13329. (condition-case nil
  13330. (eval sexp)
  13331. (error
  13332. (beep)
  13333. (message "Bad sexp at line %d in %s: %s"
  13334. (org-current-line)
  13335. (buffer-file-name) sexp)
  13336. (sleep-for 2))))))
  13337. (cond ((stringp result) (split-string result "; "))
  13338. ((and (consp result)
  13339. (not (consp (cdr result)))
  13340. (stringp (cdr result))) (cdr result))
  13341. ((and (consp result)
  13342. (stringp (car result))) result)
  13343. (result entry))))
  13344. (defun org-diary-to-ical-string (frombuf)
  13345. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13346. This uses the icalendar.el library."
  13347. (let* ((tmpdir temporary-file-directory)
  13348. (tmpfile (make-temp-name
  13349. (expand-file-name "orgics" tmpdir)))
  13350. buf rtn b e)
  13351. (with-current-buffer frombuf
  13352. (icalendar-export-region (point-min) (point-max) tmpfile)
  13353. (setq buf (find-buffer-visiting tmpfile))
  13354. (set-buffer buf)
  13355. (goto-char (point-min))
  13356. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13357. (setq b (match-beginning 0)))
  13358. (goto-char (point-max))
  13359. (when (re-search-backward "^END:VEVENT" nil t)
  13360. (setq e (match-end 0)))
  13361. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13362. (kill-buffer buf)
  13363. (delete-file tmpfile)
  13364. rtn))
  13365. (defun org-closest-date (start current prefer)
  13366. "Return closest date to CURRENT starting from START.
  13367. CURRENT and START are both time stamps.
  13368. When PREFER is `past', return a date that is either CURRENT or
  13369. past. When PREFER is `future', return a date that is either
  13370. CURRENT or future.
  13371. Only time stamps with a repeater are modified. Any other time
  13372. stamp stay unchanged. In any case, return value is an absolute
  13373. day number."
  13374. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13375. ;; No repeater. Do not shift time stamp.
  13376. (time-to-days (org-time-string-to-time start))
  13377. (let ((value (string-to-number (match-string 1 start)))
  13378. (type (match-string 2 start)))
  13379. (if (= 0 value)
  13380. ;; Repeater with a 0-value is considered as void.
  13381. (time-to-days (org-time-string-to-time start))
  13382. (let* ((base (org-date-to-gregorian start))
  13383. (target (org-date-to-gregorian current))
  13384. (sday (calendar-absolute-from-gregorian base))
  13385. (cday (calendar-absolute-from-gregorian target))
  13386. n1 n2)
  13387. ;; If START is already past CURRENT, just return START.
  13388. (if (<= cday sday) sday
  13389. ;; Compute closest date before (N1) and closest date past
  13390. ;; (N2) CURRENT.
  13391. (pcase type
  13392. ("h"
  13393. (let ((missing-hours
  13394. (mod (+ (- (* 24 (- cday sday))
  13395. (nth 2 (org-parse-time-string start)))
  13396. org-extend-today-until)
  13397. value)))
  13398. (setf n1 (if (= missing-hours 0) cday
  13399. (- cday (1+ (/ missing-hours 24)))))
  13400. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13401. ((or "d" "w")
  13402. (let ((value (if (equal type "w") (* 7 value) value)))
  13403. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13404. (setf n2 (+ n1 value))))
  13405. ("m"
  13406. (let* ((add-months
  13407. (lambda (d n)
  13408. ;; Add N months to gregorian date D, i.e.,
  13409. ;; a list (MONTH DAY YEAR). Return a valid
  13410. ;; gregorian date.
  13411. (let ((m (+ (nth 0 d) n)))
  13412. (list (mod m 12)
  13413. (nth 1 d)
  13414. (+ (/ m 12) (nth 2 d))))))
  13415. (months ; Complete months to TARGET.
  13416. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13417. (- (nth 0 target) (nth 0 base))
  13418. ;; If START's day is greater than
  13419. ;; TARGET's, remove incomplete month.
  13420. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13421. value)
  13422. value))
  13423. (before (funcall add-months base months)))
  13424. (setf n1 (calendar-absolute-from-gregorian before))
  13425. (setf n2
  13426. (calendar-absolute-from-gregorian
  13427. (funcall add-months before value)))))
  13428. (_
  13429. (let* ((d (nth 1 base))
  13430. (m (nth 0 base))
  13431. (y (nth 2 base))
  13432. (years ; Complete years to TARGET.
  13433. (* (/ (- (nth 2 target)
  13434. y
  13435. ;; If START's month and day are
  13436. ;; greater than TARGET's, remove
  13437. ;; incomplete year.
  13438. (if (or (> (nth 0 target) m)
  13439. (and (= (nth 0 target) m)
  13440. (> (nth 1 target) d)))
  13441. 0
  13442. 1))
  13443. value)
  13444. value))
  13445. (before (list m d (+ y years))))
  13446. (setf n1 (calendar-absolute-from-gregorian before))
  13447. (setf n2 (calendar-absolute-from-gregorian
  13448. (list m d (+ (nth 2 before) value)))))))
  13449. ;; Handle PREFER parameter, if any.
  13450. (cond
  13451. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13452. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13453. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13454. (defun org-date-to-gregorian (d)
  13455. "Turn any specification of date D into a Gregorian date for the calendar."
  13456. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13457. ((and (listp d) (= (length d) 3)) d)
  13458. ((stringp d)
  13459. (let ((d (org-parse-time-string d)))
  13460. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13461. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13462. (defun org-timestamp-up (&optional arg)
  13463. "Increase the date item at the cursor by one.
  13464. If the cursor is on the year, change the year. If it is on the month,
  13465. the day or the time, change that. If the cursor is on the enclosing
  13466. bracket, change the timestamp type.
  13467. With prefix ARG, change by that many units."
  13468. (interactive "p")
  13469. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13470. (defun org-timestamp-down (&optional arg)
  13471. "Decrease the date item at the cursor by one.
  13472. If the cursor is on the year, change the year. If it is on the month,
  13473. the day or the time, change that. If the cursor is on the enclosing
  13474. bracket, change the timestamp type.
  13475. With prefix ARG, change by that many units."
  13476. (interactive "p")
  13477. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13478. (defun org-timestamp-up-day (&optional arg)
  13479. "Increase the date in the time stamp by one day.
  13480. With prefix ARG, change that many days."
  13481. (interactive "p")
  13482. (if (and (not (org-at-timestamp-p 'lax))
  13483. (org-at-heading-p))
  13484. (org-todo 'up)
  13485. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13486. (defun org-timestamp-down-day (&optional arg)
  13487. "Decrease the date in the time stamp by one day.
  13488. With prefix ARG, change that many days."
  13489. (interactive "p")
  13490. (if (and (not (org-at-timestamp-p 'lax))
  13491. (org-at-heading-p))
  13492. (org-todo 'down)
  13493. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13494. (defun org-at-timestamp-p (&optional extended)
  13495. "Non-nil if point is inside a timestamp.
  13496. By default, the function only consider syntactically valid active
  13497. timestamps. However, the caller may have a broader definition
  13498. for timestamps. As a consequence, optional argument EXTENDED can
  13499. be set to the following values
  13500. `inactive'
  13501. Include also syntactically valid inactive timestamps.
  13502. `agenda'
  13503. Include timestamps allowed in Agenda, i.e., those in
  13504. properties drawers, planning lines and clock lines.
  13505. `lax'
  13506. Ignore context. The function matches any part of the
  13507. document looking like a timestamp. This includes comments,
  13508. example blocks...
  13509. For backward-compatibility with Org 9.0, every other non-nil
  13510. value is equivalent to `inactive'.
  13511. When at a timestamp, return the position of the point as a symbol
  13512. among `bracket', `after', `year', `month', `hour', `minute',
  13513. `day' or a number of character from the last know part of the
  13514. time stamp.
  13515. When matching, the match groups are the following:
  13516. group 1: year
  13517. group 2: month
  13518. group 3: day number
  13519. group 4: day name
  13520. group 5: hours, if any
  13521. group 6: minutes, if any"
  13522. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13523. (pos (point))
  13524. (match?
  13525. (let ((boundaries (org-in-regexp regexp)))
  13526. (save-match-data
  13527. (cond ((null boundaries) nil)
  13528. ((eq extended 'lax) t)
  13529. (t
  13530. (or (and (eq extended 'agenda)
  13531. (or (org-at-planning-p)
  13532. (org-at-property-p)
  13533. (and (bound-and-true-p
  13534. org-agenda-include-inactive-timestamps)
  13535. (org-at-clock-log-p))))
  13536. (eq 'timestamp
  13537. (save-excursion
  13538. (when (= pos (cdr boundaries)) (forward-char -1))
  13539. (org-element-type (org-element-context)))))))))))
  13540. (cond
  13541. ((not match?) nil)
  13542. ((= pos (match-beginning 0)) 'bracket)
  13543. ;; Distinguish location right before the closing bracket from
  13544. ;; right after it.
  13545. ((= pos (1- (match-end 0))) 'bracket)
  13546. ((= pos (match-end 0)) 'after)
  13547. ((org-pos-in-match-range pos 2) 'year)
  13548. ((org-pos-in-match-range pos 3) 'month)
  13549. ((org-pos-in-match-range pos 7) 'hour)
  13550. ((org-pos-in-match-range pos 8) 'minute)
  13551. ((or (org-pos-in-match-range pos 4)
  13552. (org-pos-in-match-range pos 5)) 'day)
  13553. ((and (> pos (or (match-end 8) (match-end 5)))
  13554. (< pos (match-end 0)))
  13555. (- pos (or (match-end 8) (match-end 5))))
  13556. (t 'day))))
  13557. (defun org-toggle-timestamp-type ()
  13558. "Toggle the type (<active> or [inactive]) of a time stamp."
  13559. (interactive)
  13560. (when (org-at-timestamp-p 'lax)
  13561. (let ((beg (match-beginning 0)) (end (match-end 0))
  13562. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13563. (save-excursion
  13564. (goto-char beg)
  13565. (while (re-search-forward "[][<>]" end t)
  13566. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13567. t t)))
  13568. (message "Timestamp is now %sactive"
  13569. (if (equal (char-after beg) ?<) "" "in")))))
  13570. (defun org-at-clock-log-p ()
  13571. "Non-nil if point is on a clock log line."
  13572. (and (org-match-line org-clock-line-re)
  13573. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13574. (defvar org-clock-history) ; defined in org-clock.el
  13575. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13576. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13577. "Change the date in the time stamp at point.
  13578. The date is changed by N times WHAT. WHAT can be `day', `month',
  13579. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13580. position in the timestamp determines what is changed.
  13581. When optional argument UPDOWN is non-nil, minutes are rounded
  13582. according to `org-time-stamp-rounding-minutes'.
  13583. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13584. \"--2d\"."
  13585. (let ((origin (point))
  13586. (timestamp? (org-at-timestamp-p 'lax))
  13587. origin-cat
  13588. with-hm inactive
  13589. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13590. extra rem
  13591. ts time time0 fixnext clrgx)
  13592. (unless timestamp? (user-error "Not at a timestamp"))
  13593. (if (and (not what) (eq timestamp? 'bracket))
  13594. (org-toggle-timestamp-type)
  13595. ;; Point isn't on brackets. Remember the part of the time-stamp
  13596. ;; the point was in. Indeed, size of time-stamps may change,
  13597. ;; but point must be kept in the same category nonetheless.
  13598. (setq origin-cat timestamp?)
  13599. (when (and (not what) (not (eq timestamp? 'day))
  13600. org-display-custom-times
  13601. (get-text-property (point) 'display)
  13602. (not (get-text-property (1- (point)) 'display)))
  13603. (setq timestamp? 'day))
  13604. (setq timestamp? (or what timestamp?)
  13605. inactive (= (char-after (match-beginning 0)) ?\[)
  13606. ts (match-string 0))
  13607. (replace-match "")
  13608. (when (string-match
  13609. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13610. ts)
  13611. (setq extra (match-string 1 ts))
  13612. (when suppress-tmp-delay
  13613. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13614. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13615. (setq with-hm t))
  13616. (setq time0 (org-parse-time-string ts))
  13617. (when (and updown
  13618. (eq timestamp? 'minute)
  13619. (not current-prefix-arg))
  13620. ;; This looks like s-up and s-down. Change by one rounding step.
  13621. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13622. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13623. (setcar (cdr time0) (+ (nth 1 time0)
  13624. (if (> n 0) (- rem) (- dm rem))))))
  13625. (setq time
  13626. (apply #'encode-time
  13627. (or (car time0) 0)
  13628. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13629. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13630. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13631. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13632. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13633. (nthcdr 6 time0)))
  13634. (when (and (memq timestamp? '(hour minute))
  13635. extra
  13636. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13637. (setq extra (org-modify-ts-extra
  13638. extra
  13639. (if (eq timestamp? 'hour) 2 5)
  13640. n dm)))
  13641. (when (integerp timestamp?)
  13642. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13643. (when (eq what 'calendar)
  13644. (let ((cal-date (org-get-date-from-calendar)))
  13645. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13646. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13647. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13648. (setcar time0 (or (car time0) 0))
  13649. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13650. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13651. (setq time (apply 'encode-time time0))))
  13652. ;; Insert the new time-stamp, and ensure point stays in the same
  13653. ;; category as before (i.e. not after the last position in that
  13654. ;; category).
  13655. (let ((pos (point)))
  13656. ;; Stay before inserted string. `save-excursion' is of no use.
  13657. (setq org-last-changed-timestamp
  13658. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13659. (goto-char pos))
  13660. (save-match-data
  13661. (looking-at org-ts-regexp3)
  13662. (goto-char
  13663. (pcase origin-cat
  13664. ;; `day' category ends before `hour' if any, or at the end
  13665. ;; of the day name.
  13666. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13667. (`hour (min (match-end 7) origin))
  13668. (`minute (min (1- (match-end 8)) origin))
  13669. ((pred integerp) (min (1- (match-end 0)) origin))
  13670. ;; Point was right after the time-stamp. However, the
  13671. ;; time-stamp length might have changed, so refer to
  13672. ;; (match-end 0) instead.
  13673. (`after (match-end 0))
  13674. ;; `year' and `month' have both fixed size: point couldn't
  13675. ;; have moved into another part.
  13676. (_ origin))))
  13677. ;; Update clock if on a CLOCK line.
  13678. (org-clock-update-time-maybe)
  13679. ;; Maybe adjust the closest clock in `org-clock-history'
  13680. (when org-clock-adjust-closest
  13681. (if (not (and (org-at-clock-log-p)
  13682. (< 1 (length (delq nil (mapcar 'marker-position
  13683. org-clock-history))))))
  13684. (message "No clock to adjust")
  13685. (cond ((save-excursion ; fix previous clock?
  13686. (re-search-backward org-ts-regexp0 nil t)
  13687. (looking-back (concat org-clock-string " \\[")
  13688. (line-beginning-position)))
  13689. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13690. ((save-excursion ; fix next clock?
  13691. (re-search-backward org-ts-regexp0 nil t)
  13692. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13693. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13694. (save-window-excursion
  13695. ;; Find closest clock to point, adjust the previous/next one in history
  13696. (let* ((p (save-excursion (org-back-to-heading t)))
  13697. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13698. (clfixnth
  13699. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13700. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13701. (if (not clfixpos)
  13702. (message "No clock to adjust")
  13703. (save-excursion
  13704. (org-goto-marker-or-bmk clfixpos)
  13705. (org-show-subtree)
  13706. (when (re-search-forward clrgx nil t)
  13707. (goto-char (match-beginning 1))
  13708. (let (org-clock-adjust-closest)
  13709. (org-timestamp-change n timestamp? updown))
  13710. (message "Clock adjusted in %s for heading: %s"
  13711. (file-name-nondirectory (buffer-file-name))
  13712. (org-get-heading t t)))))))))
  13713. ;; Try to recenter the calendar window, if any.
  13714. (when (and org-calendar-follow-timestamp-change
  13715. (get-buffer-window "*Calendar*" t)
  13716. (memq timestamp? '(day month year)))
  13717. (org-recenter-calendar (time-to-days time))))))
  13718. (defun org-modify-ts-extra (s pos n dm)
  13719. "Change the different parts of the lead-time and repeat fields in timestamp."
  13720. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13721. ng h m new rem)
  13722. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13723. (cond
  13724. ((or (org-pos-in-match-range pos 2)
  13725. (org-pos-in-match-range pos 3))
  13726. (setq m (string-to-number (match-string 3 s))
  13727. h (string-to-number (match-string 2 s)))
  13728. (if (org-pos-in-match-range pos 2)
  13729. (setq h (+ h n))
  13730. (setq n (* dm (with-no-warnings (cl-signum n))))
  13731. (unless (= 0 (setq rem (% m dm)))
  13732. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13733. (setq m (+ m n)))
  13734. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13735. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13736. (setq h (mod h 24))
  13737. (setq ng 1 new (format "-%02d:%02d" h m)))
  13738. ((org-pos-in-match-range pos 6)
  13739. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13740. ((org-pos-in-match-range pos 5)
  13741. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13742. ((org-pos-in-match-range pos 9)
  13743. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13744. ((org-pos-in-match-range pos 8)
  13745. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13746. (when ng
  13747. (setq s (concat
  13748. (substring s 0 (match-beginning ng))
  13749. new
  13750. (substring s (match-end ng))))))
  13751. s))
  13752. (defun org-recenter-calendar (d)
  13753. "If the calendar is visible, recenter it to date D."
  13754. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13755. (when cwin
  13756. (let ((calendar-move-hook nil))
  13757. (with-selected-window cwin
  13758. (calendar-goto-date
  13759. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13760. (defun org-goto-calendar (&optional arg)
  13761. "Go to the Emacs calendar at the current date.
  13762. If there is a time stamp in the current line, go to that date.
  13763. A prefix ARG can be used to force the current date."
  13764. (interactive "P")
  13765. (let ((calendar-move-hook nil)
  13766. (calendar-view-holidays-initially-flag nil)
  13767. (calendar-view-diary-initially-flag nil)
  13768. diff)
  13769. (when (or (org-at-timestamp-p 'lax)
  13770. (org-match-line (concat ".*" org-ts-regexp)))
  13771. (let ((d1 (time-to-days nil))
  13772. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13773. (setq diff (- d2 d1))))
  13774. (calendar)
  13775. (calendar-goto-today)
  13776. (when (and diff (not arg)) (calendar-forward-day diff))))
  13777. (defun org-get-date-from-calendar ()
  13778. "Return a list (month day year) of date at point in calendar."
  13779. (with-current-buffer "*Calendar*"
  13780. (save-match-data
  13781. (calendar-cursor-to-date))))
  13782. (defun org-date-from-calendar ()
  13783. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13784. If there is already a time stamp at the cursor position, update it."
  13785. (interactive)
  13786. (if (org-at-timestamp-p 'lax)
  13787. (org-timestamp-change 0 'calendar)
  13788. (let ((cal-date (org-get-date-from-calendar)))
  13789. (org-insert-time-stamp
  13790. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13791. (defcustom org-image-actual-width t
  13792. "When non-nil, use the actual width of images when inlining them.
  13793. When set to a number, use imagemagick (when available) to set the
  13794. image's width to this value.
  13795. When set to a number in a list, try to get the width from any
  13796. #+ATTR.* keyword if it matches a width specification like
  13797. #+ATTR_HTML: :width 300px
  13798. and fall back on that number if none is found.
  13799. When set to nil, try to get the width from an #+ATTR.* keyword
  13800. and fall back on the original width if none is found.
  13801. When set to any other non-nil value, always use the image width.
  13802. This requires Emacs >= 24.1, built with imagemagick support."
  13803. :group 'org-appearance
  13804. :version "24.4"
  13805. :package-version '(Org . "8.0")
  13806. :type '(choice
  13807. (const :tag "Use the image width" t)
  13808. (integer :tag "Use a number of pixels")
  13809. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13810. (const :tag "Use #+ATTR* or don't resize" nil)))
  13811. (defcustom org-agenda-inhibit-startup nil
  13812. "Inhibit startup when preparing agenda buffers.
  13813. When this variable is t, the initialization of the Org agenda
  13814. buffers is inhibited: e.g. the visibility state is not set, the
  13815. tables are not re-aligned, etc."
  13816. :type 'boolean
  13817. :version "24.3"
  13818. :group 'org-agenda)
  13819. (defcustom org-agenda-ignore-properties nil
  13820. "Avoid updating text properties when building the agenda.
  13821. Properties are used to prepare buffers for effort estimates,
  13822. appointments, statistics and subtree-local categories.
  13823. If you don't use these in the agenda, you can add them to this
  13824. list and agenda building will be a bit faster.
  13825. The value is a list, with zero or more of the symbols `effort', `appt',
  13826. `stats' or `category'."
  13827. :type '(set :greedy t
  13828. (const effort)
  13829. (const appt)
  13830. (const stats)
  13831. (const category))
  13832. :version "26.1"
  13833. :package-version '(Org . "8.3")
  13834. :group 'org-agenda)
  13835. ;;;; Files
  13836. (defun org-save-all-org-buffers ()
  13837. "Save all Org buffers without user confirmation."
  13838. (interactive)
  13839. (message "Saving all Org buffers...")
  13840. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  13841. (when (featurep 'org-id) (org-id-locations-save))
  13842. (message "Saving all Org buffers... done"))
  13843. (defun org-revert-all-org-buffers ()
  13844. "Revert all Org buffers.
  13845. Prompt for confirmation when there are unsaved changes.
  13846. Be sure you know what you are doing before letting this function
  13847. overwrite your changes.
  13848. This function is useful in a setup where one tracks Org files
  13849. with a version control system, to revert on one machine after pulling
  13850. changes from another. I believe the procedure must be like this:
  13851. 1. M-x org-save-all-org-buffers
  13852. 2. Pull changes from the other machine, resolve conflicts
  13853. 3. M-x org-revert-all-org-buffers"
  13854. (interactive)
  13855. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  13856. (user-error "Abort"))
  13857. (save-excursion
  13858. (save-window-excursion
  13859. (dolist (b (buffer-list))
  13860. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  13861. (with-current-buffer b buffer-file-name))
  13862. (pop-to-buffer-same-window b)
  13863. (revert-buffer t 'no-confirm)))
  13864. (when (and (featurep 'org-id) org-id-track-globally)
  13865. (org-id-locations-load)))))
  13866. ;;;; Agenda files
  13867. ;;;###autoload
  13868. (defun org-switchb (&optional arg)
  13869. "Switch between Org buffers.
  13870. With `\\[universal-argument]' prefix, restrict available buffers to files.
  13871. With `\\[universal-argument] \\[universal-argument]' \
  13872. prefix, restrict available buffers to agenda files."
  13873. (interactive "P")
  13874. (let ((blist (org-buffer-list
  13875. (cond ((equal arg '(4)) 'files)
  13876. ((equal arg '(16)) 'agenda)))))
  13877. (pop-to-buffer-same-window
  13878. (completing-read "Org buffer: "
  13879. (mapcar #'list (mapcar #'buffer-name blist))
  13880. nil t))))
  13881. (defun org-buffer-list (&optional predicate exclude-tmp)
  13882. "Return a list of Org buffers.
  13883. PREDICATE can be `export', `files' or `agenda'.
  13884. export restrict the list to Export buffers.
  13885. files restrict the list to buffers visiting Org files.
  13886. agenda restrict the list to buffers visiting agenda files.
  13887. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  13888. (let* ((bfn nil)
  13889. (agenda-files (and (eq predicate 'agenda)
  13890. (mapcar 'file-truename (org-agenda-files t))))
  13891. (filter
  13892. (cond
  13893. ((eq predicate 'files)
  13894. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  13895. ((eq predicate 'export)
  13896. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  13897. ((eq predicate 'agenda)
  13898. (lambda (b)
  13899. (with-current-buffer b
  13900. (and (derived-mode-p 'org-mode)
  13901. (setq bfn (buffer-file-name b))
  13902. (member (file-truename bfn) agenda-files)))))
  13903. (t (lambda (b) (with-current-buffer b
  13904. (or (derived-mode-p 'org-mode)
  13905. (string-match "\\*Org .*Export"
  13906. (buffer-name b)))))))))
  13907. (delq nil
  13908. (mapcar
  13909. (lambda(b)
  13910. (if (and (funcall filter b)
  13911. (or (not exclude-tmp)
  13912. (not (string-match "tmp" (buffer-name b)))))
  13913. b
  13914. nil))
  13915. (buffer-list)))))
  13916. (defun org-agenda-files (&optional unrestricted archives)
  13917. "Get the list of agenda files.
  13918. Optional UNRESTRICTED means return the full list even if a restriction
  13919. is currently in place.
  13920. When ARCHIVES is t, include all archive files that are really being
  13921. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  13922. `org-agenda-archives-mode' is t."
  13923. (let ((files
  13924. (cond
  13925. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  13926. ((stringp org-agenda-files) (org-read-agenda-file-list))
  13927. ((listp org-agenda-files) org-agenda-files)
  13928. (t (error "Invalid value of `org-agenda-files'")))))
  13929. (setq files (apply 'append
  13930. (mapcar (lambda (f)
  13931. (if (file-directory-p f)
  13932. (directory-files
  13933. f t org-agenda-file-regexp)
  13934. (list f)))
  13935. files)))
  13936. (when org-agenda-skip-unavailable-files
  13937. (setq files (delq nil
  13938. (mapcar (function
  13939. (lambda (file)
  13940. (and (file-readable-p file) file)))
  13941. files))))
  13942. (when (or (eq archives t)
  13943. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  13944. (setq files (org-add-archive-files files)))
  13945. files))
  13946. (defun org-agenda-file-p (&optional file)
  13947. "Return non-nil, if FILE is an agenda file.
  13948. If FILE is omitted, use the file associated with the current
  13949. buffer."
  13950. (let ((fname (or file (buffer-file-name))))
  13951. (and fname
  13952. (member (file-truename fname)
  13953. (mapcar #'file-truename (org-agenda-files t))))))
  13954. (defun org-edit-agenda-file-list ()
  13955. "Edit the list of agenda files.
  13956. Depending on setup, this either uses customize to edit the variable
  13957. `org-agenda-files', or it visits the file that is holding the list. In the
  13958. latter case, the buffer is set up in a way that saving it automatically kills
  13959. the buffer and restores the previous window configuration."
  13960. (interactive)
  13961. (if (stringp org-agenda-files)
  13962. (let ((cw (current-window-configuration)))
  13963. (find-file org-agenda-files)
  13964. (setq-local org-window-configuration cw)
  13965. (add-hook 'after-save-hook
  13966. (lambda ()
  13967. (set-window-configuration
  13968. (prog1 org-window-configuration
  13969. (kill-buffer (current-buffer))))
  13970. (org-install-agenda-files-menu)
  13971. (message "New agenda file list installed"))
  13972. nil 'local)
  13973. (message "%s" (substitute-command-keys
  13974. "Edit list and finish with \\[save-buffer]")))
  13975. (customize-variable 'org-agenda-files)))
  13976. (defun org-store-new-agenda-file-list (list)
  13977. "Set new value for the agenda file list and save it correctly."
  13978. (if (stringp org-agenda-files)
  13979. (let ((fe (org-read-agenda-file-list t)) b u)
  13980. (while (setq b (find-buffer-visiting org-agenda-files))
  13981. (kill-buffer b))
  13982. (with-temp-file org-agenda-files
  13983. (insert
  13984. (mapconcat
  13985. (lambda (f) ;; Keep un-expanded entries.
  13986. (if (setq u (assoc f fe))
  13987. (cdr u)
  13988. f))
  13989. list "\n")
  13990. "\n")))
  13991. (let ((org-mode-hook nil) (org-inhibit-startup t)
  13992. (org-insert-mode-line-in-empty-file nil))
  13993. (setq org-agenda-files list)
  13994. (customize-save-variable 'org-agenda-files org-agenda-files))))
  13995. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  13996. "Read the list of agenda files from a file.
  13997. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  13998. filenames, used by `org-store-new-agenda-file-list' to write back
  13999. un-expanded file names."
  14000. (when (file-directory-p org-agenda-files)
  14001. (error "`org-agenda-files' cannot be a single directory"))
  14002. (when (stringp org-agenda-files)
  14003. (with-temp-buffer
  14004. (insert-file-contents org-agenda-files)
  14005. (mapcar
  14006. (lambda (f)
  14007. (let ((e (expand-file-name (substitute-in-file-name f)
  14008. org-directory)))
  14009. (if pair-with-expansion
  14010. (cons e f)
  14011. e)))
  14012. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  14013. ;;;###autoload
  14014. (defun org-cycle-agenda-files ()
  14015. "Cycle through the files in `org-agenda-files'.
  14016. If the current buffer visits an agenda file, find the next one in the list.
  14017. If the current buffer does not, find the first agenda file."
  14018. (interactive)
  14019. (let* ((fs (or (org-agenda-files t)
  14020. (user-error "No agenda files")))
  14021. (files (copy-sequence fs))
  14022. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  14023. file)
  14024. (when tcf
  14025. (while (and (setq file (pop files))
  14026. (not (equal (file-truename file) tcf)))))
  14027. (find-file (car (or files fs)))
  14028. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  14029. (defun org-agenda-file-to-front (&optional to-end)
  14030. "Move/add the current file to the top of the agenda file list.
  14031. If the file is not present in the list, it is added to the front. If it is
  14032. present, it is moved there. With optional argument TO-END, add/move to the
  14033. end of the list."
  14034. (interactive "P")
  14035. (let ((org-agenda-skip-unavailable-files nil)
  14036. (file-alist (mapcar (lambda (x)
  14037. (cons (file-truename x) x))
  14038. (org-agenda-files t)))
  14039. (ctf (file-truename
  14040. (or buffer-file-name
  14041. (user-error "Please save the current buffer to a file"))))
  14042. x had)
  14043. (setq x (assoc ctf file-alist) had x)
  14044. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  14045. (if to-end
  14046. (setq file-alist (append (delq x file-alist) (list x)))
  14047. (setq file-alist (cons x (delq x file-alist))))
  14048. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  14049. (org-install-agenda-files-menu)
  14050. (message "File %s to %s of agenda file list"
  14051. (if had "moved" "added") (if to-end "end" "front"))))
  14052. (defun org-remove-file (&optional file)
  14053. "Remove current file from the list of files in variable `org-agenda-files'.
  14054. These are the files which are being checked for agenda entries.
  14055. Optional argument FILE means use this file instead of the current."
  14056. (interactive)
  14057. (let* ((org-agenda-skip-unavailable-files nil)
  14058. (file (or file buffer-file-name
  14059. (user-error "Current buffer does not visit a file")))
  14060. (true-file (file-truename file))
  14061. (afile (abbreviate-file-name file))
  14062. (files (delq nil (mapcar
  14063. (lambda (x)
  14064. (unless (equal true-file
  14065. (file-truename x))
  14066. x))
  14067. (org-agenda-files t)))))
  14068. (if (not (= (length files) (length (org-agenda-files t))))
  14069. (progn
  14070. (org-store-new-agenda-file-list files)
  14071. (org-install-agenda-files-menu)
  14072. (message "Removed from Org Agenda list: %s" afile))
  14073. (message "File was not in list: %s (not removed)" afile))))
  14074. (defun org-file-menu-entry (file)
  14075. (vector file (list 'find-file file) t))
  14076. (defun org-check-agenda-file (file)
  14077. "Make sure FILE exists. If not, ask user what to do."
  14078. (unless (file-exists-p file)
  14079. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  14080. (abbreviate-file-name file))
  14081. (let ((r (downcase (read-char-exclusive))))
  14082. (cond
  14083. ((equal r ?r)
  14084. (org-remove-file file)
  14085. (throw 'nextfile t))
  14086. (t (user-error "Abort"))))))
  14087. (defun org-get-agenda-file-buffer (file)
  14088. "Get an agenda buffer visiting FILE.
  14089. If the buffer needs to be created, add it to the list of buffers
  14090. which might be released later."
  14091. (let ((buf (org-find-base-buffer-visiting file)))
  14092. (if buf
  14093. buf ; just return it
  14094. ;; Make a new buffer and remember it
  14095. (setq buf (find-file-noselect file))
  14096. (when buf (push buf org-agenda-new-buffers))
  14097. buf)))
  14098. (defun org-release-buffers (blist)
  14099. "Release all buffers in list, asking the user for confirmation when needed.
  14100. When a buffer is unmodified, it is just killed. When modified, it is saved
  14101. \(if the user agrees) and then killed."
  14102. (let (file)
  14103. (dolist (buf blist)
  14104. (setq file (buffer-file-name buf))
  14105. (when (and (buffer-modified-p buf)
  14106. file
  14107. (y-or-n-p (format "Save file %s? " file)))
  14108. (with-current-buffer buf (save-buffer)))
  14109. (kill-buffer buf))))
  14110. (defun org-agenda-prepare-buffers (files)
  14111. "Create buffers for all agenda files, protect archived trees and comments."
  14112. (interactive)
  14113. (let ((pa '(:org-archived t))
  14114. (pc '(:org-comment t))
  14115. (pall '(:org-archived t :org-comment t))
  14116. (inhibit-read-only t)
  14117. (org-inhibit-startup org-agenda-inhibit-startup)
  14118. (rea (org-make-tag-string (list org-archive-tag)))
  14119. re pos)
  14120. (setq org-tag-alist-for-agenda nil
  14121. org-tag-groups-alist-for-agenda nil)
  14122. (save-excursion
  14123. (save-restriction
  14124. (dolist (file files)
  14125. (catch 'nextfile
  14126. (if (bufferp file)
  14127. (set-buffer file)
  14128. (org-check-agenda-file file)
  14129. (set-buffer (org-get-agenda-file-buffer file)))
  14130. (widen)
  14131. (org-set-regexps-and-options 'tags-only)
  14132. (setq pos (point))
  14133. (or (memq 'category org-agenda-ignore-properties)
  14134. (org-refresh-category-properties))
  14135. (or (memq 'stats org-agenda-ignore-properties)
  14136. (org-refresh-stats-properties))
  14137. (or (memq 'effort org-agenda-ignore-properties)
  14138. (org-refresh-effort-properties))
  14139. (or (memq 'appt org-agenda-ignore-properties)
  14140. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14141. (setq org-todo-keywords-for-agenda
  14142. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14143. (setq org-done-keywords-for-agenda
  14144. (append org-done-keywords-for-agenda org-done-keywords))
  14145. (setq org-todo-keyword-alist-for-agenda
  14146. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14147. (setq org-tag-alist-for-agenda
  14148. (org--tag-add-to-alist
  14149. org-tag-alist-for-agenda
  14150. org-current-tag-alist))
  14151. ;; Merge current file's tag groups into global
  14152. ;; `org-tag-groups-alist-for-agenda'.
  14153. (when org-group-tags
  14154. (dolist (alist org-tag-groups-alist)
  14155. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14156. (if old
  14157. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14158. (push alist org-tag-groups-alist-for-agenda)))))
  14159. (with-silent-modifications
  14160. (save-excursion
  14161. (remove-text-properties (point-min) (point-max) pall)
  14162. (when org-agenda-skip-archived-trees
  14163. (goto-char (point-min))
  14164. (while (re-search-forward rea nil t)
  14165. (when (org-at-heading-p t)
  14166. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  14167. (goto-char (point-min))
  14168. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  14169. (while (re-search-forward re nil t)
  14170. (when (save-match-data (org-in-commented-heading-p t))
  14171. (add-text-properties
  14172. (match-beginning 0) (org-end-of-subtree t) pc)))))
  14173. (goto-char pos)))))
  14174. (setq org-todo-keywords-for-agenda
  14175. (org-uniquify org-todo-keywords-for-agenda))
  14176. (setq org-todo-keyword-alist-for-agenda
  14177. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14178. ;;;; CDLaTeX minor mode
  14179. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14180. "Keymap for the minor `org-cdlatex-mode'.")
  14181. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14182. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14183. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14184. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14185. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14186. (defvar org-cdlatex-texmathp-advice-is-done nil
  14187. "Flag remembering if we have applied the advice to texmathp already.")
  14188. (define-minor-mode org-cdlatex-mode
  14189. "Toggle the minor `org-cdlatex-mode'.
  14190. This mode supports entering LaTeX environment and math in LaTeX fragments
  14191. in Org mode.
  14192. \\{org-cdlatex-mode-map}"
  14193. nil " OCDL" nil
  14194. (when org-cdlatex-mode
  14195. (require 'cdlatex)
  14196. (run-hooks 'cdlatex-mode-hook)
  14197. (cdlatex-compute-tables))
  14198. (unless org-cdlatex-texmathp-advice-is-done
  14199. (setq org-cdlatex-texmathp-advice-is-done t)
  14200. (defadvice texmathp (around org-math-always-on activate)
  14201. "Always return t in Org buffers.
  14202. This is because we want to insert math symbols without dollars even outside
  14203. the LaTeX math segments. If Org mode thinks that point is actually inside
  14204. an embedded LaTeX fragment, let `texmathp' do its job.
  14205. `\\[org-cdlatex-mode-map]'"
  14206. (interactive)
  14207. (let (p)
  14208. (cond
  14209. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14210. ((eq this-command 'cdlatex-math-symbol)
  14211. (setq ad-return-value t
  14212. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14213. (t
  14214. (let ((p (org-inside-LaTeX-fragment-p)))
  14215. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14216. (setq ad-return-value t
  14217. texmathp-why '("Org mode embedded math" . 0))
  14218. (when p ad-do-it)))))))))
  14219. (defun turn-on-org-cdlatex ()
  14220. "Unconditionally turn on `org-cdlatex-mode'."
  14221. (org-cdlatex-mode 1))
  14222. (defun org-try-cdlatex-tab ()
  14223. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14224. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14225. - inside a LaTeX fragment, or
  14226. - after the first word in a line, where an abbreviation expansion could
  14227. insert a LaTeX environment."
  14228. (when org-cdlatex-mode
  14229. (cond
  14230. ;; Before any word on the line: No expansion possible.
  14231. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14232. ;; Just after first word on the line: Expand it. Make sure it
  14233. ;; cannot happen on headlines, though.
  14234. ((save-excursion
  14235. (skip-chars-backward "a-zA-Z0-9*")
  14236. (skip-chars-backward " \t")
  14237. (and (bolp) (not (org-at-heading-p))))
  14238. (cdlatex-tab) t)
  14239. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14240. (defun org-cdlatex-underscore-caret (&optional _arg)
  14241. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14242. Revert to the normal definition outside of these fragments."
  14243. (interactive "P")
  14244. (if (org-inside-LaTeX-fragment-p)
  14245. (call-interactively 'cdlatex-sub-superscript)
  14246. (let (org-cdlatex-mode)
  14247. (call-interactively (key-binding (vector last-input-event))))))
  14248. (defun org-cdlatex-math-modify (&optional _arg)
  14249. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14250. Revert to the normal definition outside of these fragments."
  14251. (interactive "P")
  14252. (if (org-inside-LaTeX-fragment-p)
  14253. (call-interactively 'cdlatex-math-modify)
  14254. (let (org-cdlatex-mode)
  14255. (call-interactively (key-binding (vector last-input-event))))))
  14256. (defun org-cdlatex-environment-indent (&optional environment item)
  14257. "Execute `cdlatex-environment' and indent the inserted environment.
  14258. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14259. The inserted environment is indented to current indentation
  14260. unless point is at the beginning of the line, in which the
  14261. environment remains unintended."
  14262. (interactive)
  14263. ;; cdlatex-environment always return nil. Therefore, capture output
  14264. ;; first and determine if an environment was selected.
  14265. (let* ((beg (point-marker))
  14266. (end (copy-marker (point) t))
  14267. (inserted (progn
  14268. (ignore-errors (cdlatex-environment environment item))
  14269. (< beg end)))
  14270. ;; Figure out how many lines to move forward after the
  14271. ;; environment has been inserted.
  14272. (lines (when inserted
  14273. (save-excursion
  14274. (- (cl-loop while (< beg (point))
  14275. with x = 0
  14276. do (forward-line -1)
  14277. (cl-incf x)
  14278. finally return x)
  14279. (if (progn (goto-char beg)
  14280. (and (progn (skip-chars-forward " \t") (eolp))
  14281. (progn (skip-chars-backward " \t") (bolp))))
  14282. 1 0)))))
  14283. (env (org-trim (delete-and-extract-region beg end))))
  14284. (when inserted
  14285. ;; Get indentation of next line unless at column 0.
  14286. (let ((ind (if (bolp) 0
  14287. (save-excursion
  14288. (org-return t)
  14289. (prog1 (current-indentation)
  14290. (when (progn (skip-chars-forward " \t") (eolp))
  14291. (delete-region beg (point)))))))
  14292. (bol (progn (skip-chars-backward " \t") (bolp))))
  14293. ;; Insert a newline before environment unless at column zero
  14294. ;; to "escape" the current line. Insert a newline if
  14295. ;; something is one the same line as \end{ENVIRONMENT}.
  14296. (insert
  14297. (concat (unless bol "\n") env
  14298. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14299. (unless (zerop ind)
  14300. (save-excursion
  14301. (goto-char beg)
  14302. (while (< (point) end)
  14303. (unless (eolp) (indent-line-to ind))
  14304. (forward-line))))
  14305. (goto-char beg)
  14306. (forward-line lines)
  14307. (indent-line-to ind)))
  14308. (set-marker beg nil)
  14309. (set-marker end nil)))
  14310. ;;;; LaTeX fragments
  14311. (defun org-inside-LaTeX-fragment-p ()
  14312. "Test if point is inside a LaTeX fragment.
  14313. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14314. sequence appearing also before point.
  14315. Even though the matchers for math are configurable, this function assumes
  14316. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14317. delimiters are skipped when they have been removed by customization.
  14318. The return value is nil, or a cons cell with the delimiter and the
  14319. position of this delimiter.
  14320. This function does a reasonably good job, but can locally be fooled by
  14321. for example currency specifications. For example it will assume being in
  14322. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14323. fragments that are properly closed, but during editing, we have to live
  14324. with the uncertainty caused by missing closing delimiters. This function
  14325. looks only before point, not after."
  14326. (catch 'exit
  14327. (let ((pos (point))
  14328. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14329. (lim (progn
  14330. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  14331. 'move)
  14332. (point)))
  14333. dd-on str (start 0) m re)
  14334. (goto-char pos)
  14335. (when dodollar
  14336. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14337. re (nth 1 (assoc "$" org-latex-regexps)))
  14338. (while (string-match re str start)
  14339. (cond
  14340. ((= (match-end 0) (length str))
  14341. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14342. ((= (match-end 0) (- (length str) 5))
  14343. (throw 'exit nil))
  14344. (t (setq start (match-end 0))))))
  14345. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14346. (goto-char pos)
  14347. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14348. (and (match-beginning 2) (throw 'exit nil))
  14349. ;; count $$
  14350. (while (re-search-backward "\\$\\$" lim t)
  14351. (setq dd-on (not dd-on)))
  14352. (goto-char pos)
  14353. (when dd-on (cons "$$" m))))))
  14354. (defun org-inside-latex-macro-p ()
  14355. "Is point inside a LaTeX macro or its arguments?"
  14356. (save-match-data
  14357. (org-in-regexp
  14358. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14359. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14360. "Build an overlay between BEG and END using IMAGE file.
  14361. Argument IMAGETYPE is the extension of the displayed image,
  14362. as a string. It defaults to \"png\"."
  14363. (let ((ov (make-overlay beg end))
  14364. (imagetype (or (intern imagetype) 'png)))
  14365. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14366. (overlay-put ov 'evaporate t)
  14367. (overlay-put ov
  14368. 'modification-hooks
  14369. (list (lambda (o _flag _beg _end &optional _l)
  14370. (delete-overlay o))))
  14371. (overlay-put ov
  14372. 'display
  14373. (list 'image :type imagetype :file image :ascent 'center))))
  14374. (defun org-clear-latex-preview (&optional beg end)
  14375. "Remove all overlays with LaTeX fragment images in current buffer.
  14376. When optional arguments BEG and END are non-nil, remove all
  14377. overlays between them instead. Return a non-nil value when some
  14378. overlays were removed, nil otherwise."
  14379. (let ((overlays
  14380. (cl-remove-if-not
  14381. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14382. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14383. (mapc #'delete-overlay overlays)
  14384. overlays))
  14385. (defun org--latex-preview-region (beg end)
  14386. "Preview LaTeX fragments between BEG and END.
  14387. BEG and END are buffer positions."
  14388. (let ((file (buffer-file-name (buffer-base-buffer))))
  14389. (save-excursion
  14390. (org-format-latex
  14391. (concat org-preview-latex-image-directory "org-ltximg")
  14392. beg end
  14393. ;; Emacs cannot overlay images from remote hosts. Create it in
  14394. ;; `temporary-file-directory' instead.
  14395. (if (or (not file) (file-remote-p file))
  14396. temporary-file-directory
  14397. default-directory)
  14398. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14399. (defun org-latex-preview (&optional arg)
  14400. "Toggle preview of the LaTeX fragment at point.
  14401. If the cursor is on a LaTeX fragment, create the image and
  14402. overlay it over the source code, if there is none. Remove it
  14403. otherwise. If there is no fragment at point, display images for
  14404. all fragments in the current section.
  14405. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14406. for all fragments
  14407. in the current section.
  14408. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14409. argument ARG, display image for all
  14410. fragments in the buffer.
  14411. With a `\\[universal-argument] \\[universal-argument] \
  14412. \\[universal-argument]' prefix argument ARG, clear image for all
  14413. fragments in the buffer."
  14414. (interactive "P")
  14415. (cond
  14416. ((not (display-graphic-p)) nil)
  14417. ;; Clear whole buffer.
  14418. ((equal arg '(64))
  14419. (org-clear-latex-preview (point-min) (point-max))
  14420. (message "LaTeX previews removed from buffer"))
  14421. ;; Preview whole buffer.
  14422. ((equal arg '(16))
  14423. (message "Creating LaTeX previews in buffer...")
  14424. (org--latex-preview-region (point-min) (point-max))
  14425. (message "Creating LaTeX previews in buffer... done."))
  14426. ;; Clear current section.
  14427. ((equal arg '(4))
  14428. (org-clear-latex-preview
  14429. (if (org-before-first-heading-p) (point-min)
  14430. (save-excursion
  14431. (org-with-limited-levels (org-back-to-heading t) (point))))
  14432. (org-with-limited-levels (org-entry-end-position))))
  14433. ;; Toggle preview on LaTeX code at point.
  14434. ((let ((datum (org-element-context)))
  14435. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14436. (let ((beg (org-element-property :begin datum))
  14437. (end (org-element-property :end datum)))
  14438. (if (org-clear-latex-preview beg end)
  14439. (message "LaTeX preview removed")
  14440. (message "Creating LaTeX preview...")
  14441. (org--latex-preview-region beg end)
  14442. (message "Creating LaTeX preview... done."))
  14443. t))))
  14444. ;; Preview current section.
  14445. (t
  14446. (let ((beg (if (org-before-first-heading-p) (point-min)
  14447. (save-excursion
  14448. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14449. (end (org-with-limited-levels (org-entry-end-position))))
  14450. (message "Creating LaTeX previews in section...")
  14451. (org--latex-preview-region beg end)
  14452. (message "Creating LaTeX previews in section... done.")))))
  14453. (defun org-format-latex
  14454. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14455. "Replace LaTeX fragments with links to an image.
  14456. The function takes care of creating the replacement image.
  14457. Only consider fragments between BEG and END when those are
  14458. provided.
  14459. When optional argument OVERLAYS is non-nil, display the image on
  14460. top of the fragment instead of replacing it.
  14461. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14462. Some of the options can be changed using the variable
  14463. `org-format-latex-options', which see."
  14464. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14465. (unless (eq processing-type 'verbatim)
  14466. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14467. (cnt 0)
  14468. checkdir-flag)
  14469. (goto-char (or beg (point-min)))
  14470. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14471. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14472. (overlay-recenter (or end (point-max))))
  14473. (while (re-search-forward math-regexp end t)
  14474. (unless (and overlays
  14475. (eq (get-char-property (point) 'org-overlay-type)
  14476. 'org-latex-overlay))
  14477. (let* ((context (org-element-context))
  14478. (type (org-element-type context)))
  14479. (when (memq type '(latex-environment latex-fragment))
  14480. (let ((block-type (eq type 'latex-environment))
  14481. (value (org-element-property :value context))
  14482. (beg (org-element-property :begin context))
  14483. (end (save-excursion
  14484. (goto-char (org-element-property :end context))
  14485. (skip-chars-backward " \r\t\n")
  14486. (point))))
  14487. (cond
  14488. ((eq processing-type 'mathjax)
  14489. ;; Prepare for MathJax processing.
  14490. (if (not (string-match "\\`\\$\\$?" value))
  14491. (goto-char end)
  14492. (delete-region beg end)
  14493. (if (string= (match-string 0 value) "$$")
  14494. (insert "\\[" (substring value 2 -2) "\\]")
  14495. (insert "\\(" (substring value 1 -1) "\\)"))))
  14496. ((eq processing-type 'html)
  14497. (goto-char beg)
  14498. (delete-region beg end)
  14499. (insert (org-format-latex-as-html value)))
  14500. ((assq processing-type org-preview-latex-process-alist)
  14501. ;; Process to an image.
  14502. (cl-incf cnt)
  14503. (goto-char beg)
  14504. (let* ((processing-info
  14505. (cdr (assq processing-type org-preview-latex-process-alist)))
  14506. (face (face-at-point))
  14507. ;; Get the colors from the face at point.
  14508. (fg
  14509. (let ((color (plist-get org-format-latex-options
  14510. :foreground)))
  14511. (if (and forbuffer (eq color 'auto))
  14512. (face-attribute face :foreground nil 'default)
  14513. color)))
  14514. (bg
  14515. (let ((color (plist-get org-format-latex-options
  14516. :background)))
  14517. (if (and forbuffer (eq color 'auto))
  14518. (face-attribute face :background nil 'default)
  14519. color)))
  14520. (hash (sha1 (prin1-to-string
  14521. (list org-format-latex-header
  14522. org-latex-default-packages-alist
  14523. org-latex-packages-alist
  14524. org-format-latex-options
  14525. forbuffer value fg bg))))
  14526. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14527. (absprefix (expand-file-name prefix dir))
  14528. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14529. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14530. (sep (and block-type "\n\n"))
  14531. (link (concat sep "[[file:" linkfile "]]" sep))
  14532. (options
  14533. (org-combine-plists
  14534. org-format-latex-options
  14535. `(:foreground ,fg :background ,bg))))
  14536. (when msg (message msg cnt))
  14537. (unless checkdir-flag ; Ensure the directory exists.
  14538. (setq checkdir-flag t)
  14539. (let ((todir (file-name-directory absprefix)))
  14540. (unless (file-directory-p todir)
  14541. (make-directory todir t))))
  14542. (unless (file-exists-p movefile)
  14543. (org-create-formula-image
  14544. value movefile options forbuffer processing-type))
  14545. (if overlays
  14546. (progn
  14547. (dolist (o (overlays-in beg end))
  14548. (when (eq (overlay-get o 'org-overlay-type)
  14549. 'org-latex-overlay)
  14550. (delete-overlay o)))
  14551. (org--make-preview-overlay beg end movefile imagetype)
  14552. (goto-char end))
  14553. (delete-region beg end)
  14554. (insert
  14555. (org-add-props link
  14556. (list 'org-latex-src
  14557. (replace-regexp-in-string "\"" "" value)
  14558. 'org-latex-src-embed-type
  14559. (if block-type 'paragraph 'character)))))))
  14560. ((eq processing-type 'mathml)
  14561. ;; Process to MathML.
  14562. (unless (org-format-latex-mathml-available-p)
  14563. (user-error "LaTeX to MathML converter not configured"))
  14564. (cl-incf cnt)
  14565. (when msg (message msg cnt))
  14566. (goto-char beg)
  14567. (delete-region beg end)
  14568. (insert (org-format-latex-as-mathml
  14569. value block-type prefix dir)))
  14570. (t
  14571. (error "Unknown conversion process %s for LaTeX fragments"
  14572. processing-type)))))))))))
  14573. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14574. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14575. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14576. successful, return the portion between \"<math...> </math>\"
  14577. elements otherwise return nil. When MATHML-FILE is specified,
  14578. write the results in to that file. When invoked as an
  14579. interactive command, prompt for LATEX-FRAG, with initial value
  14580. set to the current active region and echo the results for user
  14581. inspection."
  14582. (interactive (list (let ((frag (when (org-region-active-p)
  14583. (buffer-substring-no-properties
  14584. (region-beginning) (region-end)))))
  14585. (read-string "LaTeX Fragment: " frag nil frag))))
  14586. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14587. (let* ((tmp-in-file
  14588. (let ((file (file-relative-name
  14589. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14590. (write-region latex-frag nil file)
  14591. file))
  14592. (tmp-out-file (file-relative-name
  14593. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14594. (cmd (format-spec
  14595. org-latex-to-mathml-convert-command
  14596. `((?j . ,(and org-latex-to-mathml-jar-file
  14597. (shell-quote-argument
  14598. (expand-file-name
  14599. org-latex-to-mathml-jar-file))))
  14600. (?I . ,(shell-quote-argument tmp-in-file))
  14601. (?i . ,latex-frag)
  14602. (?o . ,(shell-quote-argument tmp-out-file)))))
  14603. mathml shell-command-output)
  14604. (when (called-interactively-p 'any)
  14605. (unless (org-format-latex-mathml-available-p)
  14606. (user-error "LaTeX to MathML converter not configured")))
  14607. (message "Running %s" cmd)
  14608. (setq shell-command-output (shell-command-to-string cmd))
  14609. (setq mathml
  14610. (when (file-readable-p tmp-out-file)
  14611. (with-current-buffer (find-file-noselect tmp-out-file t)
  14612. (goto-char (point-min))
  14613. (when (re-search-forward
  14614. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14615. (regexp-quote
  14616. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14617. nil t)
  14618. (prog1 (match-string 0) (kill-buffer))))))
  14619. (cond
  14620. (mathml
  14621. (setq mathml
  14622. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14623. (when mathml-file
  14624. (write-region mathml nil mathml-file))
  14625. (when (called-interactively-p 'any)
  14626. (message mathml)))
  14627. ((warn "LaTeX to MathML conversion failed")
  14628. (message shell-command-output)))
  14629. (delete-file tmp-in-file)
  14630. (when (file-exists-p tmp-out-file)
  14631. (delete-file tmp-out-file))
  14632. mathml))
  14633. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14634. prefix &optional dir)
  14635. "Use `org-create-math-formula' but check local cache first."
  14636. (let* ((absprefix (expand-file-name prefix dir))
  14637. (print-length nil) (print-level nil)
  14638. (formula-id (concat
  14639. "formula-"
  14640. (sha1
  14641. (prin1-to-string
  14642. (list latex-frag
  14643. org-latex-to-mathml-convert-command)))))
  14644. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14645. (formula-cache-dir (file-name-directory formula-cache)))
  14646. (unless (file-directory-p formula-cache-dir)
  14647. (make-directory formula-cache-dir t))
  14648. (unless (file-exists-p formula-cache)
  14649. (org-create-math-formula latex-frag formula-cache))
  14650. (if (file-exists-p formula-cache)
  14651. ;; Successful conversion. Return the link to MathML file.
  14652. (org-add-props
  14653. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14654. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14655. 'org-latex-src-embed-type (if latex-frag-type
  14656. 'paragraph 'character)))
  14657. ;; Failed conversion. Return the LaTeX fragment verbatim
  14658. latex-frag)))
  14659. (defun org-format-latex-as-html (latex-fragment)
  14660. "Convert LATEX-FRAGMENT to HTML.
  14661. This uses `org-latex-to-html-convert-command', which see."
  14662. (let ((cmd (format-spec org-latex-to-html-convert-command
  14663. `((?i . ,latex-fragment)))))
  14664. (message "Running %s" cmd)
  14665. (shell-command-to-string cmd)))
  14666. (defun org--get-display-dpi ()
  14667. "Get the DPI of the display.
  14668. The function assumes that the display has the same pixel width in
  14669. the horizontal and vertical directions."
  14670. (if (display-graphic-p)
  14671. (round (/ (display-pixel-height)
  14672. (/ (display-mm-height) 25.4)))
  14673. (error "Attempt to calculate the dpi of a non-graphic display")))
  14674. (defun org-create-formula-image
  14675. (string tofile options buffer &optional processing-type)
  14676. "Create an image from LaTeX source using external processes.
  14677. The LaTeX STRING is saved to a temporary LaTeX file, then
  14678. converted to an image file by process PROCESSING-TYPE defined in
  14679. `org-preview-latex-process-alist'. A nil value defaults to
  14680. `org-preview-latex-default-process'.
  14681. The generated image file is eventually moved to TOFILE.
  14682. The OPTIONS argument controls the size, foreground color and
  14683. background color of the generated image.
  14684. When BUFFER non-nil, this function is used for LaTeX previewing.
  14685. Otherwise, it is used to deal with LaTeX snippets showed in
  14686. a HTML file."
  14687. (let* ((processing-type (or processing-type
  14688. org-preview-latex-default-process))
  14689. (processing-info
  14690. (cdr (assq processing-type org-preview-latex-process-alist)))
  14691. (programs (plist-get processing-info :programs))
  14692. (error-message (or (plist-get processing-info :message) ""))
  14693. (image-input-type (plist-get processing-info :image-input-type))
  14694. (image-output-type (plist-get processing-info :image-output-type))
  14695. (post-clean (or (plist-get processing-info :post-clean)
  14696. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14697. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14698. (latex-header
  14699. (or (plist-get processing-info :latex-header)
  14700. (org-latex-make-preamble
  14701. (org-export-get-environment (org-export-get-backend 'latex))
  14702. org-format-latex-header
  14703. 'snippet)))
  14704. (latex-compiler (plist-get processing-info :latex-compiler))
  14705. (image-converter (plist-get processing-info :image-converter))
  14706. (tmpdir temporary-file-directory)
  14707. (texfilebase (make-temp-name
  14708. (expand-file-name "orgtex" tmpdir)))
  14709. (texfile (concat texfilebase ".tex"))
  14710. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14711. '(1.0 . 1.0)))
  14712. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14713. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14714. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14715. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14716. "Black"))
  14717. (bg (or (plist-get options (if buffer :background :html-background))
  14718. "Transparent"))
  14719. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14720. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14721. (dolist (program programs)
  14722. (org-check-external-command program error-message))
  14723. (if (eq fg 'default)
  14724. (setq fg (org-latex-color :foreground))
  14725. (setq fg (org-latex-color-format fg)))
  14726. (if (eq bg 'default)
  14727. (setq bg (org-latex-color :background))
  14728. (setq bg (org-latex-color-format
  14729. (if (string= bg "Transparent") "white" bg))))
  14730. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14731. (if (string-suffix-p string "\n")
  14732. (aset string (1- (length string)) ?%)
  14733. (setq string (concat string "%")))
  14734. (with-temp-file texfile
  14735. (insert latex-header)
  14736. (insert "\n\\begin{document}\n"
  14737. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14738. "\\definecolor{bg}{rgb}{" bg "}%\n"
  14739. "\n\\pagecolor{bg}%\n"
  14740. "\n{\\color{fg}\n"
  14741. string
  14742. "\n}\n"
  14743. "\n\\end{document}\n"))
  14744. (let* ((err-msg (format "Please adjust `%s' part of \
  14745. `org-preview-latex-process-alist'."
  14746. processing-type))
  14747. (image-input-file
  14748. (org-compile-file
  14749. texfile latex-compiler image-input-type err-msg log-buf))
  14750. (image-output-file
  14751. (org-compile-file
  14752. image-input-file image-converter image-output-type err-msg log-buf
  14753. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14754. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14755. (copy-file image-output-file tofile 'replace)
  14756. (dolist (e post-clean)
  14757. (when (file-exists-p (concat texfilebase e))
  14758. (delete-file (concat texfilebase e))))
  14759. image-output-file)))
  14760. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14761. "Fill a LaTeX header template TPL.
  14762. In the template, the following place holders will be recognized:
  14763. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14764. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14765. [PACKAGES] \\usepackage statements for PKG
  14766. [NO-PACKAGES] do not include PKG
  14767. [EXTRA] the string EXTRA
  14768. [NO-EXTRA] do not include EXTRA
  14769. For backward compatibility, if both the positive and the negative place
  14770. holder is missing, the positive one (without the \"NO-\") will be
  14771. assumed to be present at the end of the template.
  14772. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14773. EXTRA is a string.
  14774. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14775. (let (rpl (end ""))
  14776. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14777. (setq rpl (if (or (match-end 1) (not def-pkg))
  14778. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14779. tpl (replace-match rpl t t tpl))
  14780. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14781. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14782. (setq rpl (if (or (match-end 1) (not pkg))
  14783. "" (org-latex-packages-to-string pkg snippets-p t))
  14784. tpl (replace-match rpl t t tpl))
  14785. (when pkg (setq end
  14786. (concat end "\n"
  14787. (org-latex-packages-to-string pkg snippets-p)))))
  14788. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14789. (setq rpl (if (or (match-end 1) (not extra))
  14790. "" (concat extra "\n"))
  14791. tpl (replace-match rpl t t tpl))
  14792. (when (and extra (string-match "\\S-" extra))
  14793. (setq end (concat end "\n" extra))))
  14794. (if (string-match "\\S-" end)
  14795. (concat tpl "\n" end)
  14796. tpl)))
  14797. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14798. "Turn an alist of packages into a string with the \\usepackage macros."
  14799. (setq pkg (mapconcat (lambda(p)
  14800. (cond
  14801. ((stringp p) p)
  14802. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14803. (format "%% Package %s omitted" (cadr p)))
  14804. ((equal "" (car p))
  14805. (format "\\usepackage{%s}" (cadr p)))
  14806. (t
  14807. (format "\\usepackage[%s]{%s}"
  14808. (car p) (cadr p)))))
  14809. pkg
  14810. "\n"))
  14811. (if newline (concat pkg "\n") pkg))
  14812. (defun org-dvipng-color (attr)
  14813. "Return a RGB color specification for dvipng."
  14814. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14815. (defun org-dvipng-color-format (color-name)
  14816. "Convert COLOR-NAME to a RGB color value for dvipng."
  14817. (apply #'format "rgb %s %s %s"
  14818. (mapcar 'org-normalize-color
  14819. (color-values color-name))))
  14820. (defun org-latex-color (attr)
  14821. "Return a RGB color for the LaTeX color package."
  14822. (org-latex-color-format (face-attribute 'default attr nil)))
  14823. (defun org-latex-color-format (color-name)
  14824. "Convert COLOR-NAME to a RGB color value."
  14825. (apply #'format "%s,%s,%s"
  14826. (mapcar 'org-normalize-color
  14827. (color-values color-name))))
  14828. (defun org-normalize-color (value)
  14829. "Return string to be used as color value for an RGB component."
  14830. (format "%g" (/ value 65535.0)))
  14831. ;; Image display
  14832. (defvar-local org-inline-image-overlays nil)
  14833. (defun org-toggle-inline-images (&optional include-linked)
  14834. "Toggle the display of inline images.
  14835. INCLUDE-LINKED is passed to `org-display-inline-images'."
  14836. (interactive "P")
  14837. (if org-inline-image-overlays
  14838. (progn
  14839. (org-remove-inline-images)
  14840. (when (called-interactively-p 'interactive)
  14841. (message "Inline image display turned off")))
  14842. (org-display-inline-images include-linked)
  14843. (when (called-interactively-p 'interactive)
  14844. (message (if org-inline-image-overlays
  14845. (format "%d images displayed inline"
  14846. (length org-inline-image-overlays))
  14847. "No images to display inline")))))
  14848. (defun org-redisplay-inline-images ()
  14849. "Assure display of inline images and refresh them."
  14850. (interactive)
  14851. (org-toggle-inline-images)
  14852. (unless org-inline-image-overlays
  14853. (org-toggle-inline-images)))
  14854. ;; For without-x builds.
  14855. (declare-function image-refresh "image" (spec &optional frame))
  14856. (defcustom org-display-remote-inline-images 'skip
  14857. "How to display remote inline images.
  14858. Possible values of this option are:
  14859. skip Don't display remote images.
  14860. download Always download and display remote images.
  14861. cache Display remote images, and open them in separate buffers
  14862. for caching. Silently update the image buffer when a file
  14863. change is detected."
  14864. :group 'org-appearance
  14865. :package-version '(Org . "9.4")
  14866. :type '(choice
  14867. (const :tag "Ignore remote images" skip)
  14868. (const :tag "Always display remote images" download)
  14869. (const :tag "Display and silently update remote images" cache))
  14870. :safe #'symbolp)
  14871. (defun org--create-inline-image (file width)
  14872. "Create image located at FILE, or return nil.
  14873. WIDTH is the width of the image. The image may not be created
  14874. according to the value of `org-display-remote-inline-images'."
  14875. (let* ((remote? (file-remote-p file))
  14876. (file-or-data
  14877. (pcase org-display-remote-inline-images
  14878. ((guard (not remote?)) file)
  14879. (`download (with-temp-buffer
  14880. (set-buffer-multibyte nil)
  14881. (insert-file-contents-literally file)
  14882. (buffer-string)))
  14883. (`cache (let ((revert-without-query '(".")))
  14884. (with-current-buffer (find-file-noselect file)
  14885. (buffer-string))))
  14886. (`skip nil)
  14887. (other
  14888. (message "Invalid value of `org-display-remote-inline-images': %S"
  14889. other)
  14890. nil))))
  14891. (when file-or-data
  14892. (create-image file-or-data
  14893. (and (image-type-available-p 'imagemagick)
  14894. width
  14895. 'imagemagick)
  14896. remote?
  14897. :width width))))
  14898. (defun org-display-inline-images (&optional include-linked refresh beg end)
  14899. "Display inline images.
  14900. An inline image is a link which follows either of these
  14901. conventions:
  14902. 1. Its path is a file with an extension matching return value
  14903. from `image-file-name-regexp' and it has no contents.
  14904. 2. Its description consists in a single link of the previous
  14905. type. In this case, that link must be a well-formed plain
  14906. or angle link, i.e., it must have an explicit \"file\" type.
  14907. Equip each image with the key-map `image-map'.
  14908. When optional argument INCLUDE-LINKED is non-nil, also links with
  14909. a text description part will be inlined. This can be nice for
  14910. a quick look at those images, but it does not reflect what
  14911. exported files will look like.
  14912. When optional argument REFRESH is non-nil, refresh existing
  14913. images between BEG and END. This will create new image displays
  14914. only if necessary.
  14915. BEG and END define the considered part. They default to the
  14916. buffer boundaries with possible narrowing."
  14917. (interactive "P")
  14918. (when (display-graphic-p)
  14919. (unless refresh
  14920. (org-remove-inline-images)
  14921. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  14922. (let ((end (or end (point-max))))
  14923. (org-with-point-at (or beg (point-min))
  14924. (let* ((case-fold-search t)
  14925. (file-extension-re (image-file-name-regexp))
  14926. (link-abbrevs (mapcar #'car
  14927. (append org-link-abbrev-alist-local
  14928. org-link-abbrev-alist)))
  14929. ;; Check absolute, relative file names and explicit
  14930. ;; "file:" links. Also check link abbreviations since
  14931. ;; some might expand to "file" links.
  14932. (file-types-re
  14933. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  14934. (if (not link-abbrevs) ""
  14935. (concat "\\|" (regexp-opt link-abbrevs))))))
  14936. (while (re-search-forward file-types-re end t)
  14937. (let* ((link (org-element-lineage
  14938. (save-match-data (org-element-context))
  14939. '(link) t))
  14940. (linktype (org-element-property :type link))
  14941. (inner-start (match-beginning 1))
  14942. (path
  14943. (cond
  14944. ;; No link at point; no inline image.
  14945. ((not link) nil)
  14946. ;; File link without a description. Also handle
  14947. ;; INCLUDE-LINKED here since it should have
  14948. ;; precedence over the next case. I.e., if link
  14949. ;; contains filenames in both the path and the
  14950. ;; description, prioritize the path only when
  14951. ;; INCLUDE-LINKED is non-nil.
  14952. ((or (not (org-element-property :contents-begin link))
  14953. include-linked)
  14954. (and (or (equal "file" linktype)
  14955. (equal "attachment" linktype))
  14956. (org-element-property :path link)))
  14957. ;; Link with a description. Check if description
  14958. ;; is a filename. Even if Org doesn't have syntax
  14959. ;; for those -- clickable image -- constructs, fake
  14960. ;; them, as in `org-export-insert-image-links'.
  14961. ((not inner-start) nil)
  14962. (t
  14963. (org-with-point-at inner-start
  14964. (and (looking-at
  14965. (if (char-equal ?< (char-after inner-start))
  14966. org-link-angle-re
  14967. org-link-plain-re))
  14968. ;; File name must fill the whole
  14969. ;; description.
  14970. (= (org-element-property :contents-end link)
  14971. (match-end 0))
  14972. (match-string 2)))))))
  14973. (when (and path (string-match-p file-extension-re path))
  14974. (let ((file (if (equal "attachment" linktype)
  14975. (progn
  14976. (require 'org-attach)
  14977. (ignore-errors (org-attach-expand path)))
  14978. (expand-file-name path))))
  14979. (when (and file (file-exists-p file))
  14980. (let ((width
  14981. ;; Apply `org-image-actual-width' specifications.
  14982. (cond
  14983. ((eq org-image-actual-width t) nil)
  14984. ((listp org-image-actual-width)
  14985. (or
  14986. ;; First try to find a width among
  14987. ;; attributes associated to the paragraph
  14988. ;; containing link.
  14989. (pcase (org-element-lineage link '(paragraph))
  14990. (`nil nil)
  14991. (p
  14992. (let* ((case-fold-search t)
  14993. (end (org-element-property :post-affiliated p))
  14994. (re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"))
  14995. (when (org-with-point-at
  14996. (org-element-property :begin p)
  14997. (re-search-forward re end t))
  14998. (string-to-number (match-string 1))))))
  14999. ;; Otherwise, fall-back to provided number.
  15000. (car org-image-actual-width)))
  15001. ((numberp org-image-actual-width)
  15002. org-image-actual-width)
  15003. (t nil)))
  15004. (old (get-char-property-and-overlay
  15005. (org-element-property :begin link)
  15006. 'org-image-overlay)))
  15007. (if (and (car-safe old) refresh)
  15008. (image-refresh (overlay-get (cdr old) 'display))
  15009. (let ((image (org--create-inline-image file width)))
  15010. (when image
  15011. (let ((ov (make-overlay
  15012. (org-element-property :begin link)
  15013. (progn
  15014. (goto-char
  15015. (org-element-property :end link))
  15016. (skip-chars-backward " \t")
  15017. (point)))))
  15018. (overlay-put ov 'display image)
  15019. (overlay-put ov 'face 'default)
  15020. (overlay-put ov 'org-image-overlay t)
  15021. (overlay-put
  15022. ov 'modification-hooks
  15023. (list 'org-display-inline-remove-overlay))
  15024. (when (<= 26 emacs-major-version)
  15025. (cl-assert (boundp 'image-map))
  15026. (overlay-put ov 'keymap image-map))
  15027. (push ov org-inline-image-overlays))))))))))))))))
  15028. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  15029. "Remove inline-display overlay if a corresponding region is modified."
  15030. (let ((inhibit-modification-hooks t))
  15031. (when (and ov after)
  15032. (delete ov org-inline-image-overlays)
  15033. (delete-overlay ov))))
  15034. (defun org-remove-inline-images ()
  15035. "Remove inline display of images."
  15036. (interactive)
  15037. (mapc #'delete-overlay org-inline-image-overlays)
  15038. (setq org-inline-image-overlays nil))
  15039. (defvar org-self-insert-command-undo-counter 0)
  15040. (defvar org-speed-command nil)
  15041. (defun org-self-insert-command (N)
  15042. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  15043. If the cursor is in a table looking at whitespace, the whitespace is
  15044. overwritten, and the table is not marked as requiring realignment."
  15045. (interactive "p")
  15046. (org-check-before-invisible-edit 'insert)
  15047. (cond
  15048. ((and org-use-speed-commands
  15049. (let ((kv (this-command-keys-vector)))
  15050. (setq org-speed-command
  15051. (run-hook-with-args-until-success
  15052. 'org-speed-command-hook
  15053. (make-string 1 (aref kv (1- (length kv))))))))
  15054. (cond
  15055. ((commandp org-speed-command)
  15056. (setq this-command org-speed-command)
  15057. (call-interactively org-speed-command))
  15058. ((functionp org-speed-command)
  15059. (funcall org-speed-command))
  15060. ((and org-speed-command (listp org-speed-command))
  15061. (eval org-speed-command))
  15062. (t (let (org-use-speed-commands)
  15063. (call-interactively 'org-self-insert-command)))))
  15064. ((and
  15065. (= N 1)
  15066. (not (org-region-active-p))
  15067. (org-at-table-p)
  15068. (progn
  15069. ;; Check if we blank the field, and if that triggers align.
  15070. (and (featurep 'org-table)
  15071. org-table-auto-blank-field
  15072. (memq last-command
  15073. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  15074. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  15075. ;; Got extra space, this field does not determine
  15076. ;; column width.
  15077. (let (org-table-may-need-update) (org-table-blank-field))
  15078. ;; No extra space, this field may determine column
  15079. ;; width.
  15080. (org-table-blank-field)))
  15081. t)
  15082. (looking-at "[^|\n]* |"))
  15083. ;; There is room for insertion without re-aligning the table.
  15084. (self-insert-command N)
  15085. (org-table-with-shrunk-field
  15086. (save-excursion
  15087. (skip-chars-forward "^|")
  15088. ;; Do not delete last space, which is
  15089. ;; `org-table-separator-space', but the regular space before
  15090. ;; it.
  15091. (delete-region (- (point) 2) (1- (point))))))
  15092. (t
  15093. (setq org-table-may-need-update t)
  15094. (self-insert-command N)
  15095. (org-fix-tags-on-the-fly)
  15096. (when org-self-insert-cluster-for-undo
  15097. (if (not (eq last-command 'org-self-insert-command))
  15098. (setq org-self-insert-command-undo-counter 1)
  15099. (if (>= org-self-insert-command-undo-counter 20)
  15100. (setq org-self-insert-command-undo-counter 1)
  15101. (and (> org-self-insert-command-undo-counter 0)
  15102. buffer-undo-list (listp buffer-undo-list)
  15103. (not (cadr buffer-undo-list)) ; remove nil entry
  15104. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15105. (setq org-self-insert-command-undo-counter
  15106. (1+ org-self-insert-command-undo-counter))))))))
  15107. (defun org-check-before-invisible-edit (kind)
  15108. "Check if editing kind KIND would be dangerous with invisible text around.
  15109. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15110. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15111. (when (and org-catch-invisible-edits
  15112. (or (not (boundp 'visible-mode)) (not visible-mode))
  15113. (or (get-char-property (point) 'invisible)
  15114. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15115. ;; OK, we need to take a closer look. Do not consider
  15116. ;; invisibility obtained through text properties (e.g., link
  15117. ;; fontification), as it cannot be toggled.
  15118. (let* ((invisible-at-point
  15119. (pcase (get-char-property-and-overlay (point) 'invisible)
  15120. (`(,_ . ,(and (pred overlayp) o)) o)))
  15121. ;; Assume that point cannot land in the middle of an
  15122. ;; overlay, or between two overlays.
  15123. (invisible-before-point
  15124. (and (not invisible-at-point)
  15125. (not (bobp))
  15126. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15127. (`(,_ . ,(and (pred overlayp) o)) o))))
  15128. (border-and-ok-direction
  15129. (or
  15130. ;; Check if we are acting predictably before invisible
  15131. ;; text.
  15132. (and invisible-at-point
  15133. (memq kind '(insert delete-backward)))
  15134. ;; Check if we are acting predictably after invisible text
  15135. ;; This works not well, and I have turned it off. It seems
  15136. ;; better to always show and stop after invisible text.
  15137. ;; (and (not invisible-at-point) invisible-before-point
  15138. ;; (memq kind '(insert delete)))
  15139. )))
  15140. (when (or invisible-at-point invisible-before-point)
  15141. (when (eq org-catch-invisible-edits 'error)
  15142. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15143. (if (and org-custom-properties-overlays
  15144. (y-or-n-p "Display invisible properties in this buffer? "))
  15145. (org-toggle-custom-properties-visibility)
  15146. ;; Make the area visible
  15147. (save-excursion
  15148. (when invisible-before-point
  15149. (goto-char
  15150. (previous-single-char-property-change (point) 'invisible)))
  15151. ;; Remove whatever overlay is currently making yet-to-be
  15152. ;; edited text invisible. Also remove nested invisibility
  15153. ;; related overlays.
  15154. (delete-overlay (or invisible-at-point invisible-before-point))
  15155. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15156. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15157. (`(,_ . ,(and (pred overlayp) o))
  15158. (delete-overlay o)
  15159. t)))))
  15160. (cond
  15161. ((eq org-catch-invisible-edits 'show)
  15162. ;; That's it, we do the edit after showing
  15163. (message
  15164. "Unfolding invisible region around point before editing")
  15165. (sit-for 1))
  15166. ((and (eq org-catch-invisible-edits 'smart)
  15167. border-and-ok-direction)
  15168. (message "Unfolding invisible region around point before editing"))
  15169. (t
  15170. ;; Don't do the edit, make the user repeat it in full visibility
  15171. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15172. (defun org-fix-tags-on-the-fly ()
  15173. "Align tags in headline at point.
  15174. Unlike `org-align-tags', this function does nothing if point is
  15175. either not currently on a tagged headline or on a tag."
  15176. (when (and (org-match-line org-tag-line-re)
  15177. (< (point) (match-beginning 1)))
  15178. (org-align-tags)))
  15179. (defun org-delete-backward-char (N)
  15180. "Like `delete-backward-char', insert whitespace at field end in tables.
  15181. When deleting backwards, in tables this function will insert whitespace in
  15182. front of the next \"|\" separator, to keep the table aligned. The table will
  15183. still be marked for re-alignment if the field did fill the entire column,
  15184. because, in this case the deletion might narrow the column."
  15185. (interactive "p")
  15186. (save-match-data
  15187. (org-check-before-invisible-edit 'delete-backward)
  15188. (if (and (= N 1)
  15189. (not overwrite-mode)
  15190. (not (org-region-active-p))
  15191. (not (eq (char-before) ?|))
  15192. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15193. (looking-at-p ".*?|")
  15194. (org-at-table-p))
  15195. (progn (forward-char -1) (org-delete-char 1))
  15196. (backward-delete-char N)
  15197. (org-fix-tags-on-the-fly))))
  15198. (defun org-delete-char (N)
  15199. "Like `delete-char', but insert whitespace at field end in tables.
  15200. When deleting characters, in tables this function will insert whitespace in
  15201. front of the next \"|\" separator, to keep the table aligned. The table will
  15202. still be marked for re-alignment if the field did fill the entire column,
  15203. because, in this case the deletion might narrow the column."
  15204. (interactive "p")
  15205. (save-match-data
  15206. (org-check-before-invisible-edit 'delete)
  15207. (cond
  15208. ((or (/= N 1)
  15209. (eq (char-after) ?|)
  15210. (save-excursion (skip-chars-backward " \t") (bolp))
  15211. (not (org-at-table-p)))
  15212. (delete-char N)
  15213. (org-fix-tags-on-the-fly))
  15214. ((looking-at ".\\(.*?\\)|")
  15215. (let* ((update? org-table-may-need-update)
  15216. (noalign (looking-at-p ".*? |")))
  15217. (delete-char 1)
  15218. (org-table-with-shrunk-field
  15219. (save-excursion
  15220. ;; Last space is `org-table-separator-space', so insert
  15221. ;; a regular one before it instead.
  15222. (goto-char (- (match-end 0) 2))
  15223. (insert " ")))
  15224. ;; If there were two spaces at the end, this field does not
  15225. ;; determine the width of the column.
  15226. (when noalign (setq org-table-may-need-update update?))))
  15227. (t
  15228. (delete-char N)))))
  15229. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15230. (put 'org-self-insert-command 'delete-selection
  15231. (lambda ()
  15232. (not (run-hook-with-args-until-success
  15233. 'self-insert-uses-region-functions))))
  15234. (put 'orgtbl-self-insert-command 'delete-selection
  15235. (lambda ()
  15236. (not (run-hook-with-args-until-success
  15237. 'self-insert-uses-region-functions))))
  15238. (put 'org-delete-char 'delete-selection 'supersede)
  15239. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15240. (put 'org-yank 'delete-selection 'yank)
  15241. ;; Make `flyspell-mode' delay after some commands
  15242. (put 'org-self-insert-command 'flyspell-delayed t)
  15243. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15244. (put 'org-delete-char 'flyspell-delayed t)
  15245. (put 'org-delete-backward-char 'flyspell-delayed t)
  15246. ;; Make pabbrev-mode expand after Org mode commands
  15247. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15248. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15249. (defun org-transpose-words ()
  15250. "Transpose words for Org.
  15251. This uses the `org-mode-transpose-word-syntax-table' syntax
  15252. table, which interprets characters in `org-emphasis-alist' as
  15253. word constituents."
  15254. (interactive)
  15255. (with-syntax-table org-mode-transpose-word-syntax-table
  15256. (call-interactively 'transpose-words)))
  15257. (defvar org-ctrl-c-ctrl-c-hook nil
  15258. "Hook for functions attaching themselves to `C-c C-c'.
  15259. This can be used to add additional functionality to the `C-c C-c'
  15260. key which executes context-dependent commands. This hook is run
  15261. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15262. run after the last test.
  15263. Each function will be called with no arguments. The function
  15264. must check if the context is appropriate for it to act. If yes,
  15265. it should do its thing and then return a non-nil value. If the
  15266. context is wrong, just do nothing and return nil.")
  15267. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15268. "Hook for functions attaching themselves to `C-c C-c'.
  15269. This can be used to add additional functionality to the `C-c C-c'
  15270. key which executes context-dependent commands. This hook is run
  15271. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15272. before the first test.
  15273. Each function will be called with no arguments. The function
  15274. must check if the context is appropriate for it to act. If yes,
  15275. it should do its thing and then return a non-nil value. If the
  15276. context is wrong, just do nothing and return nil.")
  15277. (defvar org-tab-first-hook nil
  15278. "Hook for functions to attach themselves to TAB.
  15279. See `org-ctrl-c-ctrl-c-hook' for more information.
  15280. This hook runs as the first action when TAB is pressed, even before
  15281. `org-cycle' messes around with the `outline-regexp' to cater for
  15282. inline tasks and plain list item folding.
  15283. If any function in this hook returns t, any other actions that
  15284. would have been caused by TAB (such as table field motion or visibility
  15285. cycling) will not occur.")
  15286. (defvar org-tab-after-check-for-table-hook nil
  15287. "Hook for functions to attach themselves to TAB.
  15288. See `org-ctrl-c-ctrl-c-hook' for more information.
  15289. This hook runs after it has been established that the cursor is not in a
  15290. table, but before checking if the cursor is in a headline or if global cycling
  15291. should be done.
  15292. If any function in this hook returns t, not other actions like visibility
  15293. cycling will be done.")
  15294. (defvar org-tab-after-check-for-cycling-hook nil
  15295. "Hook for functions to attach themselves to TAB.
  15296. See `org-ctrl-c-ctrl-c-hook' for more information.
  15297. This hook runs after it has been established that not table field motion and
  15298. not visibility should be done because of current context. This is probably
  15299. the place where a package like yasnippets can hook in.")
  15300. (defvar org-tab-before-tab-emulation-hook nil
  15301. "Hook for functions to attach themselves to TAB.
  15302. See `org-ctrl-c-ctrl-c-hook' for more information.
  15303. This hook runs after every other options for TAB have been exhausted, but
  15304. before indentation and \t insertion takes place.")
  15305. (defvar org-metaleft-hook nil
  15306. "Hook for functions attaching themselves to `M-left'.
  15307. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15308. (defvar org-metaright-hook nil
  15309. "Hook for functions attaching themselves to `M-right'.
  15310. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15311. (defvar org-metaup-hook nil
  15312. "Hook for functions attaching themselves to `M-up'.
  15313. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15314. (defvar org-metadown-hook nil
  15315. "Hook for functions attaching themselves to `M-down'.
  15316. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15317. (defvar org-shiftmetaleft-hook nil
  15318. "Hook for functions attaching themselves to `M-S-left'.
  15319. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15320. (defvar org-shiftmetaright-hook nil
  15321. "Hook for functions attaching themselves to `M-S-right'.
  15322. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15323. (defvar org-shiftmetaup-hook nil
  15324. "Hook for functions attaching themselves to `M-S-up'.
  15325. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15326. (defvar org-shiftmetadown-hook nil
  15327. "Hook for functions attaching themselves to `M-S-down'.
  15328. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15329. (defvar org-metareturn-hook nil
  15330. "Hook for functions attaching themselves to `M-RET'.
  15331. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15332. (defvar org-shiftup-hook nil
  15333. "Hook for functions attaching themselves to `S-up'.
  15334. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15335. (defvar org-shiftup-final-hook nil
  15336. "Hook for functions attaching themselves to `S-up'.
  15337. This one runs after all other options except shift-select have been excluded.
  15338. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15339. (defvar org-shiftdown-hook nil
  15340. "Hook for functions attaching themselves to `S-down'.
  15341. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15342. (defvar org-shiftdown-final-hook nil
  15343. "Hook for functions attaching themselves to `S-down'.
  15344. This one runs after all other options except shift-select have been excluded.
  15345. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15346. (defvar org-shiftleft-hook nil
  15347. "Hook for functions attaching themselves to `S-left'.
  15348. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15349. (defvar org-shiftleft-final-hook nil
  15350. "Hook for functions attaching themselves to `S-left'.
  15351. This one runs after all other options except shift-select have been excluded.
  15352. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15353. (defvar org-shiftright-hook nil
  15354. "Hook for functions attaching themselves to `S-right'.
  15355. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15356. (defvar org-shiftright-final-hook nil
  15357. "Hook for functions attaching themselves to `S-right'.
  15358. This one runs after all other options except shift-select have been excluded.
  15359. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15360. (defun org-modifier-cursor-error ()
  15361. "Throw an error, a modified cursor command was applied in wrong context."
  15362. (user-error "This command is active in special context like tables, headlines or items"))
  15363. (defun org-shiftselect-error ()
  15364. "Throw an error because Shift-Cursor command was applied in wrong context."
  15365. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15366. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15367. (user-error "This command works only in special context like headlines or timestamps")))
  15368. (defun org-call-for-shift-select (cmd)
  15369. (let ((this-command-keys-shift-translated t))
  15370. (call-interactively cmd)))
  15371. (defun org-shifttab (&optional arg)
  15372. "Global visibility cycling or move to previous table field.
  15373. Call `org-table-previous-field' within a table.
  15374. When ARG is nil, cycle globally through visibility states.
  15375. When ARG is a numeric prefix, show contents of this level."
  15376. (interactive "P")
  15377. (cond
  15378. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15379. ((integerp arg)
  15380. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15381. (message "Content view to level: %d" arg)
  15382. (org-content (prefix-numeric-value arg2))
  15383. (org-cycle-show-empty-lines t)
  15384. (setq org-cycle-global-status 'overview)))
  15385. (t (call-interactively 'org-global-cycle))))
  15386. (defun org-shiftmetaleft ()
  15387. "Promote subtree or delete table column.
  15388. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15389. `org-table-delete-column', depending on context. See the
  15390. individual commands for more information."
  15391. (interactive)
  15392. (cond
  15393. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15394. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15395. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15396. ((if (not (org-region-active-p)) (org-at-item-p)
  15397. (save-excursion (goto-char (region-beginning))
  15398. (org-at-item-p)))
  15399. (call-interactively 'org-outdent-item-tree))
  15400. (t (org-modifier-cursor-error))))
  15401. (defun org-shiftmetaright ()
  15402. "Demote subtree or insert table column.
  15403. Calls `org-demote-subtree', `org-indent-item-tree', or
  15404. `org-table-insert-column', depending on context. See the
  15405. individual commands for more information."
  15406. (interactive)
  15407. (cond
  15408. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15409. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15410. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15411. ((if (not (org-region-active-p)) (org-at-item-p)
  15412. (save-excursion (goto-char (region-beginning))
  15413. (org-at-item-p)))
  15414. (call-interactively 'org-indent-item-tree))
  15415. (t (org-modifier-cursor-error))))
  15416. (defun org-shiftmetaup (&optional _arg)
  15417. "Drag the line at point up.
  15418. In a table, kill the current row.
  15419. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15420. but also adjust the previous clocked item in the clock history.
  15421. Everywhere else, drag the line at point up."
  15422. (interactive "P")
  15423. (cond
  15424. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15425. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15426. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15427. (call-interactively 'org-timestamp-up)))
  15428. (t (call-interactively 'org-drag-line-backward))))
  15429. (defun org-shiftmetadown (&optional _arg)
  15430. "Drag the line at point down.
  15431. In a table, insert an empty row at the current line.
  15432. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15433. but also adjust the previous clocked item in the clock history.
  15434. Everywhere else, drag the line at point down."
  15435. (interactive "P")
  15436. (cond
  15437. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15438. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15439. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15440. (call-interactively 'org-timestamp-down)))
  15441. (t (call-interactively 'org-drag-line-forward))))
  15442. (defsubst org-hidden-tree-error ()
  15443. (user-error
  15444. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15445. (defun org-metaleft (&optional _arg)
  15446. "Promote heading, list item at point or move table column left.
  15447. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15448. depending on context. With no specific context, calls the Emacs
  15449. default `backward-word'. See the individual commands for more
  15450. information.
  15451. This function runs the hook `org-metaleft-hook' as a first step,
  15452. and returns at first non-nil value."
  15453. (interactive "P")
  15454. (cond
  15455. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15456. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15457. ((org-with-limited-levels
  15458. (or (org-at-heading-p)
  15459. (and (org-region-active-p)
  15460. (save-excursion
  15461. (goto-char (region-beginning))
  15462. (org-at-heading-p)))))
  15463. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15464. (call-interactively 'org-do-promote))
  15465. ;; At an inline task.
  15466. ((org-at-heading-p)
  15467. (call-interactively 'org-inlinetask-promote))
  15468. ((or (org-at-item-p)
  15469. (and (org-region-active-p)
  15470. (save-excursion
  15471. (goto-char (region-beginning))
  15472. (org-at-item-p))))
  15473. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15474. (call-interactively 'org-outdent-item))
  15475. (t (call-interactively 'backward-word))))
  15476. (defun org-metaright (&optional _arg)
  15477. "Demote heading, list item at point or move table column right.
  15478. In front of a drawer or a block keyword, indent it correctly.
  15479. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15480. `org-indent-drawer' or `org-indent-block' depending on context.
  15481. With no specific context, calls the Emacs default `forward-word'.
  15482. See the individual commands for more information.
  15483. This function runs the hook `org-metaright-hook' as a first step,
  15484. and returns at first non-nil value."
  15485. (interactive "P")
  15486. (cond
  15487. ((run-hook-with-args-until-success 'org-metaright-hook))
  15488. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15489. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15490. ((org-at-block-p) (call-interactively 'org-indent-block))
  15491. ((org-with-limited-levels
  15492. (or (org-at-heading-p)
  15493. (and (org-region-active-p)
  15494. (save-excursion
  15495. (goto-char (region-beginning))
  15496. (org-at-heading-p)))))
  15497. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15498. (call-interactively 'org-do-demote))
  15499. ;; At an inline task.
  15500. ((org-at-heading-p)
  15501. (call-interactively 'org-inlinetask-demote))
  15502. ((or (org-at-item-p)
  15503. (and (org-region-active-p)
  15504. (save-excursion
  15505. (goto-char (region-beginning))
  15506. (org-at-item-p))))
  15507. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15508. (call-interactively 'org-indent-item))
  15509. (t (call-interactively 'forward-word))))
  15510. (defun org-check-for-hidden (what)
  15511. "Check if there are hidden headlines/items in the current visual line.
  15512. WHAT can be either `headlines' or `items'. If the current line is
  15513. an outline or item heading and it has a folded subtree below it,
  15514. this function returns t, nil otherwise."
  15515. (let ((re (cond
  15516. ((eq what 'headlines) org-outline-regexp-bol)
  15517. ((eq what 'items) (org-item-beginning-re))
  15518. (t (error "This should not happen"))))
  15519. beg end)
  15520. (save-excursion
  15521. (catch 'exit
  15522. (unless (org-region-active-p)
  15523. (setq beg (point-at-bol))
  15524. (beginning-of-line 2)
  15525. (while (and (not (eobp)) ;; this is like `next-line'
  15526. (get-char-property (1- (point)) 'invisible))
  15527. (beginning-of-line 2))
  15528. (setq end (point))
  15529. (goto-char beg)
  15530. (goto-char (point-at-eol))
  15531. (setq end (max end (point)))
  15532. (while (re-search-forward re end t)
  15533. (when (get-char-property (match-beginning 0) 'invisible)
  15534. (throw 'exit t))))
  15535. nil))))
  15536. (defun org-metaup (&optional _arg)
  15537. "Move subtree up or move table row up.
  15538. Calls `org-move-subtree-up' or `org-table-move-row' or
  15539. `org-move-item-up', depending on context. See the individual commands
  15540. for more information."
  15541. (interactive "P")
  15542. (cond
  15543. ((run-hook-with-args-until-success 'org-metaup-hook))
  15544. ((org-region-active-p)
  15545. (let* ((a (save-excursion
  15546. (goto-char (min (region-beginning) (region-end)))
  15547. (line-beginning-position)))
  15548. (b (save-excursion
  15549. (goto-char (max (region-beginning) (region-end)))
  15550. (if (bolp) (1- (point)) (line-end-position))))
  15551. (c (save-excursion
  15552. (goto-char a)
  15553. (move-beginning-of-line 0)
  15554. (point)))
  15555. (d (save-excursion
  15556. (goto-char a)
  15557. (move-end-of-line 0)
  15558. (point))))
  15559. (transpose-regions a b c d)
  15560. (goto-char c)))
  15561. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15562. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15563. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15564. (t (org-drag-element-backward))))
  15565. (defun org-metadown (&optional _arg)
  15566. "Move subtree down or move table row down.
  15567. Calls `org-move-subtree-down' or `org-table-move-row' or
  15568. `org-move-item-down', depending on context. See the individual
  15569. commands for more information."
  15570. (interactive "P")
  15571. (cond
  15572. ((run-hook-with-args-until-success 'org-metadown-hook))
  15573. ((org-region-active-p)
  15574. (let* ((a (save-excursion
  15575. (goto-char (min (region-beginning) (region-end)))
  15576. (line-beginning-position)))
  15577. (b (save-excursion
  15578. (goto-char (max (region-beginning) (region-end)))
  15579. (if (bolp) (1- (point)) (line-end-position))))
  15580. (c (save-excursion
  15581. (goto-char b)
  15582. (move-beginning-of-line (if (bolp) 1 2))
  15583. (point)))
  15584. (d (save-excursion
  15585. (goto-char b)
  15586. (move-end-of-line (if (bolp) 1 2))
  15587. (point))))
  15588. (transpose-regions a b c d)
  15589. (goto-char d)))
  15590. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15591. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15592. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15593. (t (org-drag-element-forward))))
  15594. (defun org-shiftup (&optional arg)
  15595. "Act on current element according to context.
  15596. Call `org-timestamp-up' or `org-priority-up', or
  15597. `org-previous-item', or `org-table-move-cell-up'. See the
  15598. individual commands for more information."
  15599. (interactive "P")
  15600. (cond
  15601. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15602. ((and org-support-shift-select (org-region-active-p))
  15603. (org-call-for-shift-select 'previous-line))
  15604. ((org-at-timestamp-p 'lax)
  15605. (call-interactively (if org-edit-timestamp-down-means-later
  15606. 'org-timestamp-down 'org-timestamp-up)))
  15607. ((and (not (eq org-support-shift-select 'always))
  15608. org-priority-enable-commands
  15609. (org-at-heading-p))
  15610. (call-interactively 'org-priority-up))
  15611. ((and (not org-support-shift-select) (org-at-item-p))
  15612. (call-interactively 'org-previous-item))
  15613. ((org-clocktable-try-shift 'up arg))
  15614. ((and (not (eq org-support-shift-select 'always))
  15615. (org-at-table-p))
  15616. (org-table-move-cell-up))
  15617. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15618. (org-support-shift-select
  15619. (org-call-for-shift-select 'previous-line))
  15620. (t (org-shiftselect-error))))
  15621. (defun org-shiftdown (&optional arg)
  15622. "Act on current element according to context.
  15623. Call `org-timestamp-down' or `org-priority-down', or
  15624. `org-next-item', or `org-table-move-cell-down'. See the
  15625. individual commands for more information."
  15626. (interactive "P")
  15627. (cond
  15628. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15629. ((and org-support-shift-select (org-region-active-p))
  15630. (org-call-for-shift-select 'next-line))
  15631. ((org-at-timestamp-p 'lax)
  15632. (call-interactively (if org-edit-timestamp-down-means-later
  15633. 'org-timestamp-up 'org-timestamp-down)))
  15634. ((and (not (eq org-support-shift-select 'always))
  15635. org-priority-enable-commands
  15636. (org-at-heading-p))
  15637. (call-interactively 'org-priority-down))
  15638. ((and (not org-support-shift-select) (org-at-item-p))
  15639. (call-interactively 'org-next-item))
  15640. ((org-clocktable-try-shift 'down arg))
  15641. ((and (not (eq org-support-shift-select 'always))
  15642. (org-at-table-p))
  15643. (org-table-move-cell-down))
  15644. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15645. (org-support-shift-select
  15646. (org-call-for-shift-select 'next-line))
  15647. (t (org-shiftselect-error))))
  15648. (defun org-shiftright (&optional arg)
  15649. "Act on the current element according to context.
  15650. This does one of the following:
  15651. - switch a timestamp at point one day into the future
  15652. - on a headline, switch to the next TODO keyword
  15653. - on an item, switch entire list to the next bullet type
  15654. - on a property line, switch to the next allowed value
  15655. - on a clocktable definition line, move time block into the future
  15656. - in a table, move a single cell right"
  15657. (interactive "P")
  15658. (cond
  15659. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15660. ((and org-support-shift-select (org-region-active-p))
  15661. (org-call-for-shift-select 'forward-char))
  15662. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15663. ((and (not (eq org-support-shift-select 'always))
  15664. (org-at-heading-p))
  15665. (let ((org-inhibit-logging
  15666. (not org-treat-S-cursor-todo-selection-as-state-change))
  15667. (org-inhibit-blocking
  15668. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15669. (org-call-with-arg 'org-todo 'right)))
  15670. ((or (and org-support-shift-select
  15671. (not (eq org-support-shift-select 'always))
  15672. (org-at-item-bullet-p))
  15673. (and (not org-support-shift-select) (org-at-item-p)))
  15674. (org-call-with-arg 'org-cycle-list-bullet nil))
  15675. ((and (not (eq org-support-shift-select 'always))
  15676. (org-at-property-p))
  15677. (call-interactively 'org-property-next-allowed-value))
  15678. ((org-clocktable-try-shift 'right arg))
  15679. ((and (not (eq org-support-shift-select 'always))
  15680. (org-at-table-p))
  15681. (org-table-move-cell-right))
  15682. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15683. (org-support-shift-select
  15684. (org-call-for-shift-select 'forward-char))
  15685. (t (org-shiftselect-error))))
  15686. (defun org-shiftleft (&optional arg)
  15687. "Act on current element according to context.
  15688. This does one of the following:
  15689. - switch a timestamp at point one day into the past
  15690. - on a headline, switch to the previous TODO keyword.
  15691. - on an item, switch entire list to the previous bullet type
  15692. - on a property line, switch to the previous allowed value
  15693. - on a clocktable definition line, move time block into the past
  15694. - in a table, move a single cell left"
  15695. (interactive "P")
  15696. (cond
  15697. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15698. ((and org-support-shift-select (org-region-active-p))
  15699. (org-call-for-shift-select 'backward-char))
  15700. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15701. ((and (not (eq org-support-shift-select 'always))
  15702. (org-at-heading-p))
  15703. (let ((org-inhibit-logging
  15704. (not org-treat-S-cursor-todo-selection-as-state-change))
  15705. (org-inhibit-blocking
  15706. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15707. (org-call-with-arg 'org-todo 'left)))
  15708. ((or (and org-support-shift-select
  15709. (not (eq org-support-shift-select 'always))
  15710. (org-at-item-bullet-p))
  15711. (and (not org-support-shift-select) (org-at-item-p)))
  15712. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15713. ((and (not (eq org-support-shift-select 'always))
  15714. (org-at-property-p))
  15715. (call-interactively 'org-property-previous-allowed-value))
  15716. ((org-clocktable-try-shift 'left arg))
  15717. ((and (not (eq org-support-shift-select 'always))
  15718. (org-at-table-p))
  15719. (org-table-move-cell-left))
  15720. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15721. (org-support-shift-select
  15722. (org-call-for-shift-select 'backward-char))
  15723. (t (org-shiftselect-error))))
  15724. (defun org-shiftcontrolright ()
  15725. "Switch to next TODO set."
  15726. (interactive)
  15727. (cond
  15728. ((and org-support-shift-select (org-region-active-p))
  15729. (org-call-for-shift-select 'forward-word))
  15730. ((and (not (eq org-support-shift-select 'always))
  15731. (org-at-heading-p))
  15732. (org-call-with-arg 'org-todo 'nextset))
  15733. (org-support-shift-select
  15734. (org-call-for-shift-select 'forward-word))
  15735. (t (org-shiftselect-error))))
  15736. (defun org-shiftcontrolleft ()
  15737. "Switch to previous TODO set."
  15738. (interactive)
  15739. (cond
  15740. ((and org-support-shift-select (org-region-active-p))
  15741. (org-call-for-shift-select 'backward-word))
  15742. ((and (not (eq org-support-shift-select 'always))
  15743. (org-at-heading-p))
  15744. (org-call-with-arg 'org-todo 'previousset))
  15745. (org-support-shift-select
  15746. (org-call-for-shift-select 'backward-word))
  15747. (t (org-shiftselect-error))))
  15748. (defun org-shiftcontrolup (&optional n)
  15749. "Change timestamps synchronously up in CLOCK log lines.
  15750. Optional argument N tells to change by that many units."
  15751. (interactive "P")
  15752. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15753. (let (org-support-shift-select)
  15754. (org-clock-timestamps-up n))
  15755. (user-error "Not at a clock log")))
  15756. (defun org-shiftcontroldown (&optional n)
  15757. "Change timestamps synchronously down in CLOCK log lines.
  15758. Optional argument N tells to change by that many units."
  15759. (interactive "P")
  15760. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15761. (let (org-support-shift-select)
  15762. (org-clock-timestamps-down n))
  15763. (user-error "Not at a clock log")))
  15764. (defun org-increase-number-at-point (&optional inc)
  15765. "Increment the number at point.
  15766. With an optional prefix numeric argument INC, increment using
  15767. this numeric value."
  15768. (interactive "p")
  15769. (if (not (number-at-point))
  15770. (user-error "Not on a number")
  15771. (unless inc (setq inc 1))
  15772. (let ((pos (point))
  15773. (beg (skip-chars-backward "-+^/*0-9eE."))
  15774. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15775. (setq nap (buffer-substring-no-properties
  15776. (+ pos beg) (+ pos beg end)))
  15777. (delete-region (+ pos beg) (+ pos beg end))
  15778. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15779. (when (org-at-table-p)
  15780. (org-table-align)
  15781. (org-table-end-of-field 1))))
  15782. (defun org-decrease-number-at-point (&optional inc)
  15783. "Decrement the number at point.
  15784. With an optional prefix numeric argument INC, decrement using
  15785. this numeric value."
  15786. (interactive "p")
  15787. (org-increase-number-at-point (- (or inc 1))))
  15788. (defun org-ctrl-c-ret ()
  15789. "Call `org-table-hline-and-move' or `org-insert-heading'."
  15790. (interactive)
  15791. (cond
  15792. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15793. (t (call-interactively 'org-insert-heading))))
  15794. (defun org-copy-visible (beg end)
  15795. "Copy the visible parts of the region."
  15796. (interactive "r")
  15797. (let ((result ""))
  15798. (while (/= beg end)
  15799. (when (get-char-property beg 'invisible)
  15800. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  15801. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  15802. (setq result (concat result (buffer-substring beg next)))
  15803. (setq beg next)))
  15804. (setq deactivate-mark t)
  15805. (kill-new result)
  15806. (message "Visible strings have been copied to the kill ring.")))
  15807. (defun org-copy-special ()
  15808. "Copy region in table or copy current subtree.
  15809. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  15810. context. See the individual commands for more information."
  15811. (interactive)
  15812. (call-interactively
  15813. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  15814. (defun org-cut-special ()
  15815. "Cut region in table or cut current subtree.
  15816. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  15817. context. See the individual commands for more information."
  15818. (interactive)
  15819. (call-interactively
  15820. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  15821. (defun org-paste-special (arg)
  15822. "Paste rectangular region into table, or past subtree relative to level.
  15823. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  15824. See the individual commands for more information."
  15825. (interactive "P")
  15826. (if (org-at-table-p)
  15827. (org-table-paste-rectangle)
  15828. (org-paste-subtree arg)))
  15829. (defun org-edit-special (&optional arg)
  15830. "Call a special editor for the element at point.
  15831. When at a table, call the formula editor with `org-table-edit-formulas'.
  15832. When in a source code block, call `org-edit-src-code'.
  15833. When in a fixed-width region, call `org-edit-fixed-width-region'.
  15834. When in an export block, call `org-edit-export-block'.
  15835. When in a LaTeX environment, call `org-edit-latex-environment'.
  15836. When at an #+INCLUDE keyword, visit the included file.
  15837. When at a footnote reference, call `org-edit-footnote-reference'.
  15838. When at a planning line call, `org-deadline' and/or `org-schedule'.
  15839. When at an active timestamp, call `org-time-stamp'.
  15840. When at an inactive timestamp, call `org-time-stamp-inactive'.
  15841. On a link, call `ffap' to visit the link at point.
  15842. Otherwise, return a user error."
  15843. (interactive "P")
  15844. (let ((element (org-element-at-point)))
  15845. (barf-if-buffer-read-only)
  15846. (pcase (org-element-type element)
  15847. (`src-block
  15848. (if (not arg) (org-edit-src-code)
  15849. (let* ((info (org-babel-get-src-block-info))
  15850. (lang (nth 0 info))
  15851. (params (nth 2 info))
  15852. (session (cdr (assq :session params))))
  15853. (if (not session) (org-edit-src-code)
  15854. ;; At a source block with a session and function called
  15855. ;; with an ARG: switch to the buffer related to the
  15856. ;; inferior process.
  15857. (switch-to-buffer
  15858. (funcall (intern (concat "org-babel-prep-session:" lang))
  15859. session params))))))
  15860. (`keyword
  15861. (unless (member (org-element-property :key element)
  15862. '("INCLUDE" "SETUPFILE"))
  15863. (user-error "No special environment to edit here"))
  15864. (let ((value (org-element-property :value element)))
  15865. (unless (org-string-nw-p value) (user-error "No file to edit"))
  15866. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  15867. (or (match-string 1 value)
  15868. (match-string 0 value)))))
  15869. (when (org-file-url-p file)
  15870. (user-error "Files located with a URL cannot be edited"))
  15871. (org-link-open-from-string
  15872. (format "[[%s]]" (expand-file-name file))))))
  15873. (`table
  15874. (if (eq (org-element-property :type element) 'table.el)
  15875. (org-edit-table.el)
  15876. (call-interactively 'org-table-edit-formulas)))
  15877. ;; Only Org tables contain `table-row' type elements.
  15878. (`table-row (call-interactively 'org-table-edit-formulas))
  15879. (`example-block (org-edit-src-code))
  15880. (`export-block (org-edit-export-block))
  15881. (`fixed-width (org-edit-fixed-width-region))
  15882. (`latex-environment (org-edit-latex-environment))
  15883. (`planning
  15884. (let ((proplist (cadr element)))
  15885. (mapc #'call-interactively
  15886. (remq nil
  15887. (list
  15888. (when (plist-get proplist :deadline) #'org-deadline)
  15889. (when (plist-get proplist :scheduled) #'org-schedule))))))
  15890. (_
  15891. ;; No notable element at point. Though, we may be at a link or
  15892. ;; a footnote reference, which are objects. Thus, scan deeper.
  15893. (let ((context (org-element-context element)))
  15894. (pcase (org-element-type context)
  15895. (`footnote-reference (org-edit-footnote-reference))
  15896. (`inline-src-block (org-edit-inline-src-code))
  15897. (`latex-fragment (org-edit-latex-fragment))
  15898. (`timestamp (if (eq 'inactive (org-element-property :type context))
  15899. (call-interactively #'org-time-stamp-inactive)
  15900. (call-interactively #'org-time-stamp)))
  15901. (`link (call-interactively #'ffap))
  15902. (_ (user-error "No special environment to edit here"))))))))
  15903. (defun org-ctrl-c-ctrl-c (&optional arg)
  15904. "Set tags in headline, or update according to changed information at point.
  15905. This command does many different things, depending on context:
  15906. - If column view is active, in agenda or org buffers, quit it.
  15907. - If there are highlights, remove them.
  15908. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  15909. this is what we do.
  15910. - If the cursor is on a statistics cookie, update it.
  15911. - If the cursor is in a headline, in an agenda or an org buffer,
  15912. prompt for tags and insert them into the current line, aligned
  15913. to `org-tags-column'. When called with prefix arg, realign all
  15914. tags in the current buffer.
  15915. - If the cursor is in one of the special #+KEYWORD lines, this
  15916. triggers scanning the buffer for these lines and updating the
  15917. information.
  15918. - If the cursor is inside a table, realign the table. This command
  15919. works even if the automatic table editor has been turned off.
  15920. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  15921. the entire table.
  15922. - If the cursor is at a footnote reference or definition, jump to
  15923. the corresponding definition or references, respectively.
  15924. - If the cursor is a the beginning of a dynamic block, update it.
  15925. - If the current buffer is a capture buffer, close note and file it.
  15926. - If the cursor is on a <<<target>>>, update radio targets and
  15927. corresponding links in this buffer.
  15928. - If the cursor is on a numbered item in a plain list, renumber the
  15929. ordered list.
  15930. - If the cursor is on a checkbox, toggle it.
  15931. - If the cursor is on a code block, evaluate it. The variable
  15932. `org-confirm-babel-evaluate' can be used to control prompting
  15933. before code block evaluation, by default every code block
  15934. evaluation requires confirmation. Code block evaluation can be
  15935. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  15936. (interactive "P")
  15937. (cond
  15938. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  15939. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  15940. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  15941. (org-remove-occur-highlights)
  15942. (message "Temporary highlights/overlays removed from current buffer"))
  15943. ((and (local-variable-p 'org-finish-function)
  15944. (fboundp org-finish-function))
  15945. (funcall org-finish-function))
  15946. ((org-babel-hash-at-point))
  15947. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  15948. (t
  15949. (let* ((context
  15950. (org-element-lineage
  15951. (org-element-context)
  15952. ;; Limit to supported contexts.
  15953. '(babel-call clock dynamic-block footnote-definition
  15954. footnote-reference inline-babel-call inline-src-block
  15955. inlinetask item keyword node-property paragraph
  15956. plain-list planning property-drawer radio-target
  15957. src-block statistics-cookie table table-cell table-row
  15958. timestamp)
  15959. t))
  15960. (radio-list-p (org-at-radio-list-p))
  15961. (type (org-element-type context)))
  15962. ;; For convenience: at the first line of a paragraph on the same
  15963. ;; line as an item, apply function on that item instead.
  15964. (when (eq type 'paragraph)
  15965. (let ((parent (org-element-property :parent context)))
  15966. (when (and (eq (org-element-type parent) 'item)
  15967. (= (line-beginning-position)
  15968. (org-element-property :begin parent)))
  15969. (setq context parent)
  15970. (setq type 'item))))
  15971. ;; Act according to type of element or object at point.
  15972. ;;
  15973. ;; Do nothing on a blank line, except if it is contained in
  15974. ;; a source block. Hence, we first check if point is in such
  15975. ;; a block and then if it is at a blank line.
  15976. (pcase type
  15977. ((or `inline-src-block `src-block)
  15978. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  15979. (org-babel-eval-wipe-error-buffer)
  15980. (org-babel-execute-src-block
  15981. current-prefix-arg (org-babel-get-src-block-info nil context))))
  15982. ((guard (org-match-line "[ \t]*$"))
  15983. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  15984. (user-error
  15985. (substitute-command-keys
  15986. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  15987. ((or `babel-call `inline-babel-call)
  15988. (let ((info (org-babel-lob-get-info context)))
  15989. (when info (org-babel-execute-src-block nil info))))
  15990. (`clock (org-clock-update-time-maybe))
  15991. (`dynamic-block
  15992. (save-excursion
  15993. (goto-char (org-element-property :post-affiliated context))
  15994. (org-update-dblock)))
  15995. (`footnote-definition
  15996. (goto-char (org-element-property :post-affiliated context))
  15997. (call-interactively 'org-footnote-action))
  15998. (`footnote-reference (call-interactively #'org-footnote-action))
  15999. ((or `headline `inlinetask)
  16000. (save-excursion (goto-char (org-element-property :begin context))
  16001. (call-interactively #'org-set-tags-command)))
  16002. (`item
  16003. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  16004. ;; unconditionally, whereas `C-u' will toggle its presence.
  16005. ;; Without a universal argument, if the item has a checkbox,
  16006. ;; toggle it. Otherwise repair the list.
  16007. (if (or radio-list-p
  16008. (and (boundp org-list-checkbox-radio-mode)
  16009. org-list-checkbox-radio-mode))
  16010. (org-toggle-radio-button arg)
  16011. (let* ((box (org-element-property :checkbox context))
  16012. (struct (org-element-property :structure context))
  16013. (old-struct (copy-tree struct))
  16014. (parents (org-list-parents-alist struct))
  16015. (prevs (org-list-prevs-alist struct))
  16016. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  16017. (org-list-set-checkbox
  16018. (org-element-property :begin context) struct
  16019. (cond ((equal arg '(16)) "[-]")
  16020. ((and (not box) (equal arg '(4))) "[ ]")
  16021. ((or (not box) (equal arg '(4))) nil)
  16022. ((eq box 'on) "[ ]")
  16023. (t "[X]")))
  16024. ;; Mimic `org-list-write-struct' but with grabbing a return
  16025. ;; value from `org-list-struct-fix-box'.
  16026. (org-list-struct-fix-ind struct parents 2)
  16027. (org-list-struct-fix-item-end struct)
  16028. (org-list-struct-fix-bul struct prevs)
  16029. (org-list-struct-fix-ind struct parents)
  16030. (let ((block-item
  16031. (org-list-struct-fix-box struct parents prevs orderedp)))
  16032. (if (and box (equal struct old-struct))
  16033. (if (equal arg '(16))
  16034. (message "Checkboxes already reset")
  16035. (user-error "Cannot toggle this checkbox: %s"
  16036. (if (eq box 'on)
  16037. "all subitems checked"
  16038. "unchecked subitems")))
  16039. (org-list-struct-apply-struct struct old-struct)
  16040. (org-update-checkbox-count-maybe))
  16041. (when block-item
  16042. (message "Checkboxes were removed due to empty box at line %d"
  16043. (org-current-line block-item)))))))
  16044. (`plain-list
  16045. ;; At a plain list, with a double C-u argument, set
  16046. ;; checkboxes of each item to "[-]", whereas a single one
  16047. ;; will toggle their presence according to the state of the
  16048. ;; first item in the list. Without an argument, repair the
  16049. ;; list.
  16050. (if (or radio-list-p
  16051. (and (boundp org-list-checkbox-radio-mode)
  16052. org-list-checkbox-radio-mode))
  16053. (org-toggle-radio-button arg)
  16054. (let* ((begin (org-element-property :contents-begin context))
  16055. (struct (org-element-property :structure context))
  16056. (old-struct (copy-tree struct))
  16057. (first-box (save-excursion
  16058. (goto-char begin)
  16059. (looking-at org-list-full-item-re)
  16060. (match-string-no-properties 3)))
  16061. (new-box (cond ((equal arg '(16)) "[-]")
  16062. ((equal arg '(4)) (unless first-box "[ ]"))
  16063. ((equal first-box "[X]") "[ ]")
  16064. (t "[X]"))))
  16065. (cond
  16066. (arg
  16067. (dolist (pos
  16068. (org-list-get-all-items
  16069. begin struct (org-list-prevs-alist struct)))
  16070. (org-list-set-checkbox pos struct new-box)))
  16071. ((and first-box (eq (point) begin))
  16072. ;; For convenience, when point is at bol on the first
  16073. ;; item of the list and no argument is provided, simply
  16074. ;; toggle checkbox of that item, if any.
  16075. (org-list-set-checkbox begin struct new-box)))
  16076. (when (equal
  16077. (org-list-write-struct
  16078. struct (org-list-parents-alist struct) old-struct)
  16079. old-struct)
  16080. (message "Cannot update this checkbox"))
  16081. (org-update-checkbox-count-maybe))))
  16082. (`keyword
  16083. (let ((org-inhibit-startup-visibility-stuff t)
  16084. (org-startup-align-all-tables nil))
  16085. (when (boundp 'org-table-coordinate-overlays)
  16086. (mapc #'delete-overlay org-table-coordinate-overlays)
  16087. (setq org-table-coordinate-overlays nil))
  16088. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  16089. (message "Local setup has been refreshed"))
  16090. ((or `property-drawer `node-property)
  16091. (call-interactively #'org-property-action))
  16092. (`radio-target
  16093. (call-interactively #'org-update-radio-target-regexp))
  16094. (`statistics-cookie
  16095. (call-interactively #'org-update-statistics-cookies))
  16096. ((or `table `table-cell `table-row)
  16097. ;; At a table, recalculate every field and align it. Also
  16098. ;; send the table if necessary. If the table has
  16099. ;; a `table.el' type, just give up. At a table row or cell,
  16100. ;; maybe recalculate line but always align table.
  16101. (if (eq (org-element-property :type context) 'table.el)
  16102. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16103. Use `\\[org-edit-special]' to edit table.el tables"))
  16104. (if (or (eq type 'table)
  16105. ;; Check if point is at a TBLFM line.
  16106. (and (eq type 'table-row)
  16107. (= (point) (org-element-property :end context))))
  16108. (save-excursion
  16109. (if (org-at-TBLFM-p)
  16110. (progn (require 'org-table)
  16111. (org-table-calc-current-TBLFM))
  16112. (goto-char (org-element-property :contents-begin context))
  16113. (org-call-with-arg 'org-table-recalculate (or arg t))
  16114. (orgtbl-send-table 'maybe)))
  16115. (org-table-maybe-eval-formula)
  16116. (cond (arg (call-interactively #'org-table-recalculate))
  16117. ((org-table-maybe-recalculate-line))
  16118. (t (org-table-align))))))
  16119. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16120. (org-timestamp-change 0 'day))
  16121. ((and `nil (guard (org-at-heading-p)))
  16122. ;; When point is on an unsupported object type, we can miss
  16123. ;; the fact that it also is at a heading. Handle it here.
  16124. (call-interactively #'org-set-tags-command))
  16125. ((guard
  16126. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16127. (_
  16128. (user-error
  16129. (substitute-command-keys
  16130. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16131. (defun org-mode-restart ()
  16132. "Restart `org-mode'."
  16133. (interactive)
  16134. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16135. (funcall major-mode)
  16136. (hack-local-variables)
  16137. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16138. (org-indent-mode -1))
  16139. (org-reset-file-cache))
  16140. (message "%s restarted" major-mode))
  16141. (defun org-flag-above-first-heading (&optional arg)
  16142. "Hide from bob up to the first heading.
  16143. Move point to the beginning of first heading or end of buffer."
  16144. (goto-char (point-min))
  16145. (unless (org-at-heading-p)
  16146. (outline-next-heading))
  16147. (unless (bobp)
  16148. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16149. (defun org-show-branches-buffer ()
  16150. "Show all branches in the buffer."
  16151. (org-flag-above-first-heading)
  16152. (outline-hide-sublevels 1)
  16153. (unless (eobp)
  16154. (outline-show-branches)
  16155. (while (outline-get-next-sibling)
  16156. (outline-show-branches)))
  16157. (goto-char (point-min)))
  16158. (defun org-kill-note-or-show-branches ()
  16159. "Abort storing current note, or show just branches."
  16160. (interactive)
  16161. (cond (org-finish-function
  16162. (let ((org-note-abort t)) (funcall org-finish-function)))
  16163. ((org-before-first-heading-p)
  16164. (org-show-branches-buffer)
  16165. (org-hide-archived-subtrees (point-min) (point-max)))
  16166. (t
  16167. (let ((beg (progn (org-back-to-heading) (point)))
  16168. (end (save-excursion (org-end-of-subtree t t) (point))))
  16169. (outline-hide-subtree)
  16170. (outline-show-branches)
  16171. (org-hide-archived-subtrees beg end)))))
  16172. (defun org-delete-indentation (&optional arg)
  16173. "Join current line to previous and fix whitespace at join.
  16174. If previous line is a headline add to headline title. Otherwise
  16175. the function calls `delete-indentation'.
  16176. I.e. with a non-nil optional argument, join the line with the
  16177. following one. If there is a region then join the lines in that
  16178. region."
  16179. (interactive "*P")
  16180. (if (save-excursion
  16181. (beginning-of-line (if arg 1 0))
  16182. (let ((case-fold-search nil))
  16183. (looking-at org-complex-heading-regexp)))
  16184. ;; At headline.
  16185. (let ((tags-column (when (match-beginning 5)
  16186. (save-excursion (goto-char (match-beginning 5))
  16187. (current-column))))
  16188. (string (concat " " (progn (when arg (forward-line 1))
  16189. (org-trim (delete-and-extract-region
  16190. (line-beginning-position)
  16191. (line-end-position)))))))
  16192. (unless (bobp) (delete-region (point) (1- (point))))
  16193. (goto-char (or (match-end 4)
  16194. (match-beginning 5)
  16195. (match-end 0)))
  16196. (skip-chars-backward " \t")
  16197. (save-excursion (insert string))
  16198. ;; Adjust alignment of tags.
  16199. (cond
  16200. ((not tags-column)) ;no tags
  16201. (org-auto-align-tags (org-align-tags))
  16202. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16203. (let ((current-prefix-arg arg))
  16204. (call-interactively #'delete-indentation))))
  16205. (defun org-open-line (n)
  16206. "Insert a new row in tables, call `open-line' elsewhere.
  16207. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16208. As a special case, when a document starts with a table, allow to
  16209. call `open-line' on the very first character."
  16210. (interactive "*p")
  16211. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16212. (org-table-insert-row)
  16213. (open-line n)))
  16214. (defun org--newline (indent arg interactive)
  16215. "Call `newline-and-indent' or just `newline'.
  16216. If INDENT is non-nil, call `newline-and-indent' with ARG to
  16217. indent unconditionally; otherwise, call `newline' with ARG and
  16218. INTERACTIVE, which can trigger indentation if
  16219. `electric-indent-mode' is enabled."
  16220. (if indent
  16221. (org-newline-and-indent arg)
  16222. (newline arg interactive)))
  16223. (defun org-return (&optional indent arg interactive)
  16224. "Goto next table row or insert a newline.
  16225. Calls `org-table-next-row' or `newline', depending on context.
  16226. When optional INDENT argument is non-nil, call
  16227. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  16228. and INTERACTIVE.
  16229. When `org-return-follows-link' is non-nil and point is on
  16230. a timestamp or a link, call `org-open-at-point'. However, it
  16231. will not happen if point is in a table or on a \"dead\"
  16232. object (e.g., within a comment). In these case, you need to use
  16233. `org-open-at-point' directly."
  16234. (interactive "i\nP\np")
  16235. (let ((context (if org-return-follows-link (org-element-context)
  16236. (org-element-at-point))))
  16237. (cond
  16238. ;; In a table, call `org-table-next-row'. However, before first
  16239. ;; column or after last one, split the table.
  16240. ((or (and (eq 'table (org-element-type context))
  16241. (not (eq 'table.el (org-element-property :type context)))
  16242. (>= (point) (org-element-property :contents-begin context))
  16243. (< (point) (org-element-property :contents-end context)))
  16244. (org-element-lineage context '(table-row table-cell) t))
  16245. (if (or (looking-at-p "[ \t]*$")
  16246. (save-excursion (skip-chars-backward " \t") (bolp)))
  16247. (insert "\n")
  16248. (org-table-justify-field-maybe)
  16249. (call-interactively #'org-table-next-row)))
  16250. ;; On a link or a timestamp, call `org-open-at-point' if
  16251. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16252. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16253. ((and org-return-follows-link
  16254. (or (and (eq 'link (org-element-type context))
  16255. ;; Ensure point is not on the white spaces after
  16256. ;; the link.
  16257. (let ((origin (point)))
  16258. (org-with-point-at (org-element-property :end context)
  16259. (skip-chars-backward " \t")
  16260. (> (point) origin))))
  16261. (org-in-regexp org-ts-regexp-both nil t)
  16262. (org-in-regexp org-tsr-regexp-both nil t)
  16263. (org-in-regexp org-link-any-re nil t)))
  16264. (call-interactively #'org-open-at-point))
  16265. ;; Insert newline in heading, but preserve tags.
  16266. ((and (not (bolp))
  16267. (let ((case-fold-search nil))
  16268. (org-match-line org-complex-heading-regexp)))
  16269. ;; At headline. Split line. However, if point is on keyword,
  16270. ;; priority cookie or tags, do not break any of them: add
  16271. ;; a newline after the headline instead.
  16272. (let ((tags-column (and (match-beginning 5)
  16273. (save-excursion (goto-char (match-beginning 5))
  16274. (current-column))))
  16275. (string
  16276. (when (and (match-end 4) (org-point-in-group (point) 4))
  16277. (delete-and-extract-region (point) (match-end 4)))))
  16278. ;; Adjust tag alignment.
  16279. (cond
  16280. ((not (and tags-column string)))
  16281. (org-auto-align-tags (org-align-tags))
  16282. (t (org--align-tags-here tags-column))) ;preserve tags column
  16283. (end-of-line)
  16284. (org-show-entry)
  16285. (org--newline indent arg interactive)
  16286. (when string (save-excursion (insert (org-trim string))))))
  16287. ;; In a list, make sure indenting keeps trailing text within.
  16288. ((and (not (eolp))
  16289. (org-element-lineage context '(item)))
  16290. (let ((trailing-data
  16291. (delete-and-extract-region (point) (line-end-position))))
  16292. (org--newline indent arg interactive)
  16293. (save-excursion (insert trailing-data))))
  16294. (t
  16295. ;; Do not auto-fill when point is in an Org property drawer.
  16296. (let ((auto-fill-function (and (not (org-at-property-p))
  16297. auto-fill-function)))
  16298. (org--newline indent arg interactive))))))
  16299. (defun org-return-and-maybe-indent ()
  16300. "Goto next table row, or insert a newline.
  16301. Call `org-table-next-row' or `org-return', depending on context.
  16302. See the individual commands for more information.
  16303. When inserting a newline, indent the new line if
  16304. `electric-indent-mode' is disabled."
  16305. (interactive)
  16306. (org-return (not electric-indent-mode)))
  16307. (defun org-ctrl-c-tab (&optional arg)
  16308. "Toggle columns width in a table, or show children.
  16309. Call `org-table-toggle-column-width' if point is in a table.
  16310. Otherwise provide a compact view of the children. ARG is the
  16311. level to hide."
  16312. (interactive "p")
  16313. (cond
  16314. ((org-at-table-p)
  16315. (call-interactively #'org-table-toggle-column-width))
  16316. ((org-before-first-heading-p)
  16317. (save-excursion
  16318. (org-flag-above-first-heading)
  16319. (outline-hide-sublevels (or arg 1))))
  16320. (t
  16321. (outline-hide-subtree)
  16322. (org-show-children arg))))
  16323. (defun org-ctrl-c-star ()
  16324. "Compute table, or change heading status of lines.
  16325. Calls `org-table-recalculate' or `org-toggle-heading',
  16326. depending on context."
  16327. (interactive)
  16328. (cond
  16329. ((org-at-table-p)
  16330. (call-interactively 'org-table-recalculate))
  16331. (t
  16332. ;; Convert all lines in region to list items
  16333. (call-interactively 'org-toggle-heading))))
  16334. (defun org-ctrl-c-minus ()
  16335. "Insert separator line in table or modify bullet status of line.
  16336. Also turns a plain line or a region of lines into list items.
  16337. Calls `org-table-insert-hline', `org-toggle-item', or
  16338. `org-cycle-list-bullet', depending on context."
  16339. (interactive)
  16340. (cond
  16341. ((org-at-table-p)
  16342. (call-interactively 'org-table-insert-hline))
  16343. ((org-region-active-p)
  16344. (call-interactively 'org-toggle-item))
  16345. ((org-in-item-p)
  16346. (call-interactively 'org-cycle-list-bullet))
  16347. (t
  16348. (call-interactively 'org-toggle-item))))
  16349. (defun org-toggle-heading (&optional nstars)
  16350. "Convert headings to normal text, or items or text to headings.
  16351. If there is no active region, only convert the current line.
  16352. With a `\\[universal-argument]' prefix, convert the whole list at
  16353. point into heading.
  16354. In a region:
  16355. - If the first non blank line is a headline, remove the stars
  16356. from all headlines in the region.
  16357. - If it is a normal line, turn each and every normal line (i.e.,
  16358. not an heading or an item) in the region into headings. If you
  16359. want to convert only the first line of this region, use one
  16360. universal prefix argument.
  16361. - If it is a plain list item, turn all plain list items into headings.
  16362. When converting a line into a heading, the number of stars is chosen
  16363. such that the lines become children of the current entry. However,
  16364. when a numeric prefix argument is given, its value determines the
  16365. number of stars to add."
  16366. (interactive "P")
  16367. (let ((skip-blanks
  16368. (function
  16369. ;; Return beginning of first non-blank line, starting from
  16370. ;; line at POS.
  16371. (lambda (pos)
  16372. (save-excursion
  16373. (goto-char pos)
  16374. (while (org-at-comment-p) (forward-line))
  16375. (skip-chars-forward " \r\t\n")
  16376. (point-at-bol)))))
  16377. beg end toggled)
  16378. ;; Determine boundaries of changes. If a universal prefix has
  16379. ;; been given, put the list in a region. If region ends at a bol,
  16380. ;; do not consider the last line to be in the region.
  16381. (when (and current-prefix-arg (org-at-item-p))
  16382. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16383. (org-mark-element))
  16384. (if (org-region-active-p)
  16385. (setq beg (funcall skip-blanks (region-beginning))
  16386. end (copy-marker (save-excursion
  16387. (goto-char (region-end))
  16388. (if (bolp) (point) (point-at-eol)))))
  16389. (setq beg (funcall skip-blanks (point-at-bol))
  16390. end (copy-marker (point-at-eol))))
  16391. ;; Ensure inline tasks don't count as headings.
  16392. (org-with-limited-levels
  16393. (save-excursion
  16394. (goto-char beg)
  16395. (cond
  16396. ;; Case 1. Started at an heading: de-star headings.
  16397. ((org-at-heading-p)
  16398. (while (< (point) end)
  16399. (when (org-at-heading-p t)
  16400. (looking-at org-outline-regexp) (replace-match "")
  16401. (setq toggled t))
  16402. (forward-line)))
  16403. ;; Case 2. Started at an item: change items into headlines.
  16404. ;; One star will be added by `org-list-to-subtree'.
  16405. ((org-at-item-p)
  16406. (while (< (point) end)
  16407. (when (org-at-item-p)
  16408. ;; Pay attention to cases when region ends before list.
  16409. (let* ((struct (org-list-struct))
  16410. (list-end
  16411. (min (org-list-get-bottom-point struct) (1+ end))))
  16412. (save-restriction
  16413. (narrow-to-region (point) list-end)
  16414. (insert (org-list-to-subtree
  16415. (org-list-to-lisp t)
  16416. (pcase (org-current-level)
  16417. (`nil 1)
  16418. (l (1+ (org-reduced-level l)))))
  16419. "\n")))
  16420. (setq toggled t))
  16421. (forward-line)))
  16422. ;; Case 3. Started at normal text: make every line an heading,
  16423. ;; skipping headlines and items.
  16424. (t (let* ((stars
  16425. (make-string
  16426. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16427. (add-stars
  16428. (cond (nstars "") ; stars from prefix only
  16429. ((equal stars "") "*") ; before first heading
  16430. (org-odd-levels-only "**") ; inside heading, odd
  16431. (t "*"))) ; inside heading, oddeven
  16432. (rpl (concat stars add-stars " "))
  16433. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16434. (while (< (point) (if (equal nstars '(4)) lend end))
  16435. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16436. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16437. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16438. (forward-line)))))))
  16439. (unless toggled (message "Cannot toggle heading from here"))))
  16440. (defun org-meta-return (&optional arg)
  16441. "Insert a new heading or wrap a region in a table.
  16442. Calls `org-insert-heading', `org-insert-item' or
  16443. `org-table-wrap-region', depending on context. When called with
  16444. an argument, unconditionally call `org-insert-heading'."
  16445. (interactive "P")
  16446. (org-check-before-invisible-edit 'insert)
  16447. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16448. (call-interactively (cond (arg #'org-insert-heading)
  16449. ((org-at-table-p) #'org-table-wrap-region)
  16450. ((org-in-item-p) #'org-insert-item)
  16451. (t #'org-insert-heading)))))
  16452. ;;; Menu entries
  16453. (defsubst org-in-subtree-not-table-p ()
  16454. "Are we in a subtree and not in a table?"
  16455. (and (not (org-before-first-heading-p))
  16456. (not (org-at-table-p))))
  16457. ;; Define the Org mode menus
  16458. (easy-menu-define org-org-menu org-mode-map "Org menu"
  16459. `("Org"
  16460. ("Show/Hide"
  16461. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16462. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16463. ["Sparse Tree..." org-sparse-tree t]
  16464. ["Reveal Context" org-reveal t]
  16465. ["Show All" org-show-all t]
  16466. "--"
  16467. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16468. "--"
  16469. ["New Heading" org-insert-heading t]
  16470. ("Navigate Headings"
  16471. ["Up" outline-up-heading t]
  16472. ["Next" outline-next-visible-heading t]
  16473. ["Previous" outline-previous-visible-heading t]
  16474. ["Next Same Level" outline-forward-same-level t]
  16475. ["Previous Same Level" outline-backward-same-level t]
  16476. "--"
  16477. ["Jump" org-goto t])
  16478. ("Edit Structure"
  16479. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16480. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16481. "--"
  16482. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16483. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16484. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16485. "--"
  16486. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16487. "--"
  16488. ["Copy visible text" org-copy-visible t]
  16489. "--"
  16490. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16491. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16492. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16493. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16494. "--"
  16495. ["Sort Region/Children" org-sort t]
  16496. "--"
  16497. ["Convert to odd levels" org-convert-to-odd-levels t]
  16498. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16499. ("Editing"
  16500. ["Emphasis..." org-emphasize t]
  16501. ["Add block structure" org-insert-structure-template t]
  16502. ["Edit Source Example" org-edit-special t]
  16503. "--"
  16504. ["Footnote new/jump" org-footnote-action t]
  16505. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16506. ("Archive"
  16507. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16508. "--"
  16509. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16510. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16511. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16512. "--"
  16513. ("Hyperlinks"
  16514. ["Store Link (Global)" org-store-link t]
  16515. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16516. ["Insert Link" org-insert-link t]
  16517. ["Follow Link" org-open-at-point t]
  16518. "--"
  16519. ["Next link" org-next-link t]
  16520. ["Previous link" org-previous-link t]
  16521. "--"
  16522. ["Descriptive Links"
  16523. org-toggle-link-display
  16524. :style radio
  16525. :selected org-descriptive-links
  16526. ]
  16527. ["Literal Links"
  16528. org-toggle-link-display
  16529. :style radio
  16530. :selected (not org-descriptive-links)])
  16531. "--"
  16532. ("TODO Lists"
  16533. ["TODO/DONE/-" org-todo t]
  16534. ("Select keyword"
  16535. ["Next keyword" org-shiftright (org-at-heading-p)]
  16536. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16537. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16538. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16539. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16540. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16541. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16542. "--"
  16543. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16544. :selected org-enforce-todo-dependencies :style toggle :active t]
  16545. "Settings for tree at point"
  16546. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16547. :selected (org-entry-get nil "ORDERED")
  16548. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16549. ["Do Children parallel" org-toggle-ordered-property :style radio
  16550. :selected (not (org-entry-get nil "ORDERED"))
  16551. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16552. "--"
  16553. ["Set Priority" org-priority t]
  16554. ["Priority Up" org-shiftup t]
  16555. ["Priority Down" org-shiftdown t]
  16556. "--"
  16557. ["Get news from all feeds" org-feed-update-all t]
  16558. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16559. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16560. ("TAGS and Properties"
  16561. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16562. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16563. "--"
  16564. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16565. ["Column view of properties" org-columns t]
  16566. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16567. ("Dates and Scheduling"
  16568. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16569. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16570. ("Change Date"
  16571. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16572. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16573. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16574. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16575. ["Compute Time Range" org-evaluate-time-range t]
  16576. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16577. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16578. "--"
  16579. ["Custom time format" org-toggle-time-stamp-overlays
  16580. :style radio :selected org-display-custom-times]
  16581. "--"
  16582. ["Goto Calendar" org-goto-calendar t]
  16583. ["Date from Calendar" org-date-from-calendar t]
  16584. "--"
  16585. ["Start/Restart Timer" org-timer-start t]
  16586. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16587. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16588. ["Insert Timer String" org-timer t]
  16589. ["Insert Timer Item" org-timer-item t])
  16590. ("Logging work"
  16591. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16592. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16593. ["Clock out" org-clock-out t]
  16594. ["Clock cancel" org-clock-cancel t]
  16595. "--"
  16596. ["Mark as default task" org-clock-mark-default-task t]
  16597. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16598. ["Goto running clock" org-clock-goto t]
  16599. "--"
  16600. ["Display times" org-clock-display t]
  16601. ["Create clock table" org-clock-report t]
  16602. "--"
  16603. ["Record DONE time"
  16604. (progn (setq org-log-done (not org-log-done))
  16605. (message "Switching to %s will %s record a timestamp"
  16606. (car org-done-keywords)
  16607. (if org-log-done "automatically" "not")))
  16608. :style toggle :selected org-log-done])
  16609. "--"
  16610. ["Agenda Command..." org-agenda t]
  16611. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16612. ("File List for Agenda")
  16613. ("Special views current file"
  16614. ["TODO Tree" org-show-todo-tree t]
  16615. ["Check Deadlines" org-check-deadlines t]
  16616. ["Tags/Property tree" org-match-sparse-tree t])
  16617. "--"
  16618. ["Export/Publish..." org-export-dispatch t]
  16619. ("LaTeX"
  16620. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16621. :style toggle :selected org-cdlatex-mode]
  16622. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16623. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16624. ["Modify math symbol" org-cdlatex-math-modify
  16625. (org-inside-LaTeX-fragment-p)]
  16626. ["Insert citation" org-reftex-citation t])
  16627. "--"
  16628. ("Documentation"
  16629. ["Show Version" org-version t]
  16630. ["Info Documentation" org-info t]
  16631. ["Browse Org News" org-browse-news t])
  16632. ("Customize"
  16633. ["Browse Org Group" org-customize t]
  16634. "--"
  16635. ["Expand This Menu" org-create-customize-menu t])
  16636. ["Send bug report" org-submit-bug-report t]
  16637. "--"
  16638. ("Refresh/Reload"
  16639. ["Refresh setup current buffer" org-mode-restart t]
  16640. ["Reload Org (after update)" org-reload t]
  16641. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16642. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu"
  16643. '("Table"
  16644. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16645. ["Next Field" org-cycle (org-at-table-p)]
  16646. ["Previous Field" org-shifttab (org-at-table-p)]
  16647. ["Next Row" org-return (org-at-table-p)]
  16648. "--"
  16649. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16650. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16651. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16652. "--"
  16653. ("Column"
  16654. ["Move Column Left" org-metaleft (org-at-table-p)]
  16655. ["Move Column Right" org-metaright (org-at-table-p)]
  16656. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16657. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16658. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16659. ("Row"
  16660. ["Move Row Up" org-metaup (org-at-table-p)]
  16661. ["Move Row Down" org-metadown (org-at-table-p)]
  16662. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16663. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16664. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16665. "--"
  16666. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16667. ("Rectangle"
  16668. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16669. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16670. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16671. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16672. "--"
  16673. ("Calculate"
  16674. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16675. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16676. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16677. "--"
  16678. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16679. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16680. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16681. "--"
  16682. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16683. "--"
  16684. ["Sum Column/Rectangle" org-table-sum
  16685. (or (org-at-table-p) (org-region-active-p))]
  16686. ["Which Column?" org-table-current-column (org-at-table-p)])
  16687. ["Debug Formulas"
  16688. org-table-toggle-formula-debugger
  16689. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16690. ["Show Col/Row Numbers"
  16691. org-table-toggle-coordinate-overlays
  16692. :style toggle
  16693. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16694. "--"
  16695. ["Create" org-table-create (not (org-at-table-p))]
  16696. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16697. ["Import from File" org-table-import (not (org-at-table-p))]
  16698. ["Export to File" org-table-export (org-at-table-p)]
  16699. "--"
  16700. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16701. "--"
  16702. ("Plot"
  16703. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16704. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16705. (defun org-info (&optional node)
  16706. "Read documentation for Org in the info system.
  16707. With optional NODE, go directly to that node."
  16708. (interactive)
  16709. (info (format "(org)%s" (or node ""))))
  16710. (defun org-browse-news ()
  16711. "Browse the news for the latest major release."
  16712. (interactive)
  16713. (browse-url "https://orgmode.org/Changes.html"))
  16714. ;;;###autoload
  16715. (defun org-submit-bug-report ()
  16716. "Submit a bug report on Org via mail.
  16717. Don't hesitate to report any problems or inaccurate documentation.
  16718. If you don't have setup sending mail from (X)Emacs, please copy the
  16719. output buffer into your mail program, as it gives us important
  16720. information about your Org version and configuration."
  16721. (interactive)
  16722. (require 'reporter)
  16723. (defvar reporter-prompt-for-summary-p)
  16724. (org-load-modules-maybe)
  16725. (org-require-autoloaded-modules)
  16726. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16727. (reporter-submit-bug-report
  16728. "emacs-orgmode@gnu.org"
  16729. (org-version nil 'full)
  16730. (let (list)
  16731. (save-window-excursion
  16732. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16733. (delete-other-windows)
  16734. (erase-buffer)
  16735. (insert "You are about to submit a bug report to the Org mailing list.
  16736. If your report is about Org installation, please read this section:
  16737. https://orgmode.org/org.html#Installation
  16738. Please read https://orgmode.org/org.html#Feedback on how to make
  16739. a good report, it will help Org contributors fixing your problem.
  16740. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16741. if the issue you are about to raise has already been dealt with.
  16742. We also would like to add your full Org and Outline configuration
  16743. to the bug report. It will help us debugging the issue.
  16744. *HOWEVER*, some variables you have customized may contain private
  16745. information. The names of customers, colleagues, or friends, might
  16746. appear in the form of file names, tags, todo states or search strings.
  16747. If you answer \"yes\" to the prompt, you might want to check and remove
  16748. such private information before sending the email.")
  16749. (add-text-properties (point-min) (point-max) '(face org-warning))
  16750. (when (yes-or-no-p "Include your Org configuration ")
  16751. (mapatoms
  16752. (lambda (v)
  16753. (and (boundp v)
  16754. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16755. (or (and (symbol-value v)
  16756. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16757. (and
  16758. (get v 'custom-type) (get v 'standard-value)
  16759. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  16760. (push v list)))))
  16761. (kill-buffer (get-buffer "*Warn about privacy*"))
  16762. list))
  16763. nil nil
  16764. "Remember to cover the basics, that is, what you expected to happen and
  16765. what in fact did happen. You don't know how to make a good report? See
  16766. https://orgmode.org/manual/Feedback.html#Feedback
  16767. Your bug report will be posted to the Org mailing list.
  16768. ------------------------------------------------------------------------")
  16769. (save-excursion
  16770. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16771. (replace-match "\\1Bug: \\3 [\\2]")))))
  16772. (defun org-install-agenda-files-menu ()
  16773. "Install agenda file menu."
  16774. (let ((bl (buffer-list)))
  16775. (save-excursion
  16776. (while bl
  16777. (set-buffer (pop bl))
  16778. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16779. (when (derived-mode-p 'org-mode)
  16780. (easy-menu-change
  16781. '("Org") "File List for Agenda"
  16782. (append
  16783. (list
  16784. ["Edit File List" (org-edit-agenda-file-list) t]
  16785. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  16786. ["Remove Current File from List" org-remove-file t]
  16787. ["Cycle through agenda files" org-cycle-agenda-files t]
  16788. ["Occur in all agenda files" org-occur-in-agenda-files t]
  16789. "--")
  16790. (mapcar 'org-file-menu-entry
  16791. ;; Prevent initialization from failing.
  16792. (ignore-errors (org-agenda-files t)))))))))
  16793. ;;;; Documentation
  16794. (defun org-require-autoloaded-modules ()
  16795. (interactive)
  16796. (mapc #'require
  16797. '(org-agenda org-archive org-attach org-clock org-colview org-id
  16798. org-table org-timer)))
  16799. ;;;###autoload
  16800. (defun org-reload (&optional uncompiled)
  16801. "Reload all Org Lisp files.
  16802. With prefix arg UNCOMPILED, load the uncompiled versions."
  16803. (interactive "P")
  16804. (require 'loadhist)
  16805. (let* ((org-dir (org-find-library-dir "org"))
  16806. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  16807. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  16808. (remove-re (format "\\`%s\\'"
  16809. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  16810. (feats (delete-dups
  16811. (mapcar 'file-name-sans-extension
  16812. (mapcar 'file-name-nondirectory
  16813. (delq nil
  16814. (mapcar 'feature-file
  16815. features))))))
  16816. (lfeat (append
  16817. (sort
  16818. (setq feats
  16819. (delq nil (mapcar
  16820. (lambda (f)
  16821. (if (and (string-match feature-re f)
  16822. (not (string-match remove-re f)))
  16823. f nil))
  16824. feats)))
  16825. 'string-lessp)
  16826. (list "org-version" "org")))
  16827. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  16828. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  16829. load-uncore load-misses)
  16830. (setq load-misses
  16831. (delq 't
  16832. (mapcar (lambda (f)
  16833. (or (org-load-noerror-mustsuffix (concat org-dir f))
  16834. (and (string= org-dir contrib-dir)
  16835. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  16836. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  16837. (push f load-uncore)
  16838. 't)
  16839. f))
  16840. lfeat)))
  16841. (when load-uncore
  16842. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  16843. (if (> (length load-uncore) 1) "s were" " was")
  16844. (reverse load-uncore)))
  16845. (if load-misses
  16846. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  16847. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  16848. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  16849. ;;;###autoload
  16850. (defun org-customize ()
  16851. "Call the customize function with org as argument."
  16852. (interactive)
  16853. (org-load-modules-maybe)
  16854. (org-require-autoloaded-modules)
  16855. (customize-browse 'org))
  16856. (defun org-create-customize-menu ()
  16857. "Create a full customization menu for Org mode, insert it into the menu."
  16858. (interactive)
  16859. (org-load-modules-maybe)
  16860. (org-require-autoloaded-modules)
  16861. (easy-menu-change
  16862. '("Org") "Customize"
  16863. `(["Browse Org group" org-customize t]
  16864. "--"
  16865. ,(customize-menu-create 'org)
  16866. ["Set" Custom-set t]
  16867. ["Save" Custom-save t]
  16868. ["Reset to Current" Custom-reset-current t]
  16869. ["Reset to Saved" Custom-reset-saved t]
  16870. ["Reset to Standard Settings" Custom-reset-standard t]))
  16871. (message "\"Org\"-menu now contains full customization menu"))
  16872. ;;;; Miscellaneous stuff
  16873. ;;; Generally useful functions
  16874. (defun org-in-clocktable-p ()
  16875. "Check if the cursor is in a clocktable."
  16876. (let ((pos (point)) start)
  16877. (save-excursion
  16878. (end-of-line 1)
  16879. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  16880. (setq start (match-beginning 0))
  16881. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  16882. (>= (match-end 0) pos)
  16883. start))))
  16884. (defun org-in-verbatim-emphasis ()
  16885. (save-match-data
  16886. (and (org-in-regexp org-verbatim-re 2)
  16887. (>= (point) (match-beginning 3))
  16888. (<= (point) (match-end 4)))))
  16889. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  16890. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  16891. (if (and marker (marker-buffer marker)
  16892. (buffer-live-p (marker-buffer marker)))
  16893. (progn
  16894. (pop-to-buffer-same-window (marker-buffer marker))
  16895. (when (or (> marker (point-max)) (< marker (point-min)))
  16896. (widen))
  16897. (goto-char marker)
  16898. (org-show-context 'org-goto))
  16899. (if bookmark
  16900. (bookmark-jump bookmark)
  16901. (error "Cannot find location"))))
  16902. (defun org-quote-csv-field (s)
  16903. "Quote field for inclusion in CSV material."
  16904. (if (string-match "[\",]" s)
  16905. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  16906. s))
  16907. (defun org-force-self-insert (N)
  16908. "Needed to enforce self-insert under remapping."
  16909. (interactive "p")
  16910. (self-insert-command N))
  16911. (defun org-quote-vert (s)
  16912. "Replace \"|\" with \"\\vert\"."
  16913. (while (string-match "|" s)
  16914. (setq s (replace-match "\\vert" t t s)))
  16915. s)
  16916. (defun org-uuidgen-p (s)
  16917. "Is S an ID created by UUIDGEN?"
  16918. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  16919. (defun org-in-src-block-p (&optional inside)
  16920. "Whether point is in a code source block.
  16921. When INSIDE is non-nil, don't consider we are within a source
  16922. block when point is at #+BEGIN_SRC or #+END_SRC."
  16923. (let ((case-fold-search t))
  16924. (or (and (eq (get-char-property (point) 'src-block) t))
  16925. (and (not inside)
  16926. (save-match-data
  16927. (save-excursion
  16928. (beginning-of-line)
  16929. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  16930. (defun org-context ()
  16931. "Return a list of contexts of the current cursor position.
  16932. If several contexts apply, all are returned.
  16933. Each context entry is a list with a symbol naming the context, and
  16934. two positions indicating start and end of the context. Possible
  16935. contexts are:
  16936. :headline anywhere in a headline
  16937. :headline-stars on the leading stars in a headline
  16938. :todo-keyword on a TODO keyword (including DONE) in a headline
  16939. :tags on the TAGS in a headline
  16940. :priority on the priority cookie in a headline
  16941. :item on the first line of a plain list item
  16942. :item-bullet on the bullet/number of a plain list item
  16943. :checkbox on the checkbox in a plain list item
  16944. :table in an Org table
  16945. :table-special on a special filed in a table
  16946. :table-table in a table.el table
  16947. :clocktable in a clocktable
  16948. :src-block in a source block
  16949. :link on a hyperlink
  16950. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  16951. :latex-fragment on a LaTeX fragment
  16952. :latex-preview on a LaTeX fragment with overlaid preview image
  16953. This function expects the position to be visible because it uses font-lock
  16954. faces as a help to recognize the following contexts: :table-special, :link,
  16955. and :keyword."
  16956. (let* ((f (get-text-property (point) 'face))
  16957. (faces (if (listp f) f (list f)))
  16958. (case-fold-search t)
  16959. (p (point)) clist o)
  16960. ;; First the large context
  16961. (cond
  16962. ((org-at-heading-p t)
  16963. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  16964. (when (progn
  16965. (beginning-of-line 1)
  16966. (looking-at org-todo-line-tags-regexp))
  16967. (push (org-point-in-group p 1 :headline-stars) clist)
  16968. (push (org-point-in-group p 2 :todo-keyword) clist)
  16969. (push (org-point-in-group p 4 :tags) clist))
  16970. (goto-char p)
  16971. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  16972. (when (looking-at "\\[#[A-Z0-9]\\]")
  16973. (push (org-point-in-group p 0 :priority) clist)))
  16974. ((org-at-item-p)
  16975. (push (org-point-in-group p 2 :item-bullet) clist)
  16976. (push (list :item (point-at-bol)
  16977. (save-excursion (org-end-of-item) (point)))
  16978. clist)
  16979. (and (org-at-item-checkbox-p)
  16980. (push (org-point-in-group p 0 :checkbox) clist)))
  16981. ((org-at-table-p)
  16982. (push (list :table (org-table-begin) (org-table-end)) clist)
  16983. (when (memq 'org-formula faces)
  16984. (push (list :table-special
  16985. (previous-single-property-change p 'face)
  16986. (next-single-property-change p 'face))
  16987. clist)))
  16988. ((org-at-table-p 'any)
  16989. (push (list :table-table) clist)))
  16990. (goto-char p)
  16991. (let ((case-fold-search t))
  16992. ;; New the "medium" contexts: clocktables, source blocks
  16993. (cond ((org-in-clocktable-p)
  16994. (push (list :clocktable
  16995. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  16996. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  16997. (match-beginning 1))
  16998. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  16999. (match-end 0)))
  17000. clist))
  17001. ((org-in-src-block-p)
  17002. (push (list :src-block
  17003. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  17004. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  17005. (match-beginning 1))
  17006. (and (search-forward "#+END_SRC" nil t)
  17007. (match-beginning 0)))
  17008. clist))))
  17009. (goto-char p)
  17010. ;; Now the small context
  17011. (cond
  17012. ((org-at-timestamp-p)
  17013. (push (org-point-in-group p 0 :timestamp) clist))
  17014. ((memq 'org-link faces)
  17015. (push (list :link
  17016. (previous-single-property-change p 'face)
  17017. (next-single-property-change p 'face))
  17018. clist))
  17019. ((memq 'org-special-keyword faces)
  17020. (push (list :keyword
  17021. (previous-single-property-change p 'face)
  17022. (next-single-property-change p 'face))
  17023. clist))
  17024. ((setq o (cl-some
  17025. (lambda (o)
  17026. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  17027. o))
  17028. (overlays-at (point))))
  17029. (push (list :latex-fragment
  17030. (overlay-start o) (overlay-end o))
  17031. clist)
  17032. (push (list :latex-preview
  17033. (overlay-start o) (overlay-end o))
  17034. clist))
  17035. ((org-inside-LaTeX-fragment-p)
  17036. ;; FIXME: positions wrong.
  17037. (push (list :latex-fragment (point) (point)) clist)))
  17038. (setq clist (nreverse (delq nil clist)))
  17039. clist))
  17040. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  17041. "Non-nil when point is between matches of START-RE and END-RE.
  17042. Also return a non-nil value when point is on one of the matches.
  17043. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  17044. buffer positions. Default values are the positions of headlines
  17045. surrounding the point.
  17046. The functions returns a cons cell whose car (resp. cdr) is the
  17047. position before START-RE (resp. after END-RE)."
  17048. (save-match-data
  17049. (let ((pos (point))
  17050. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  17051. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  17052. beg end)
  17053. (save-excursion
  17054. ;; Point is on a block when on START-RE or if START-RE can be
  17055. ;; found before it...
  17056. (and (or (org-in-regexp start-re)
  17057. (re-search-backward start-re limit-up t))
  17058. (setq beg (match-beginning 0))
  17059. ;; ... and END-RE after it...
  17060. (goto-char (match-end 0))
  17061. (re-search-forward end-re limit-down t)
  17062. (> (setq end (match-end 0)) pos)
  17063. ;; ... without another START-RE in-between.
  17064. (goto-char (match-beginning 0))
  17065. (not (re-search-backward start-re (1+ beg) t))
  17066. ;; Return value.
  17067. (cons beg end))))))
  17068. (defun org-in-block-p (names)
  17069. "Non-nil when point belongs to a block whose name belongs to NAMES.
  17070. NAMES is a list of strings containing names of blocks.
  17071. Return first block name matched, or nil. Beware that in case of
  17072. nested blocks, the returned name may not belong to the closest
  17073. block from point."
  17074. (save-match-data
  17075. (catch 'exit
  17076. (let ((case-fold-search t)
  17077. (lim-up (save-excursion (outline-previous-heading)))
  17078. (lim-down (save-excursion (outline-next-heading))))
  17079. (dolist (name names)
  17080. (let ((n (regexp-quote name)))
  17081. (when (org-between-regexps-p
  17082. (concat "^[ \t]*#\\+begin_" n)
  17083. (concat "^[ \t]*#\\+end_" n)
  17084. lim-up lim-down)
  17085. (throw 'exit n)))))
  17086. nil)))
  17087. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  17088. "Call `multi-occur' with buffers for all agenda files."
  17089. (interactive "sOrg-files matching: ")
  17090. (let* ((files (org-agenda-files))
  17091. (tnames (mapcar #'file-truename files))
  17092. (extra org-agenda-text-search-extra-files))
  17093. (when (eq (car extra) 'agenda-archives)
  17094. (setq extra (cdr extra))
  17095. (setq files (org-add-archive-files files)))
  17096. (dolist (f extra)
  17097. (unless (member (file-truename f) tnames)
  17098. (unless (member f files) (setq files (append files (list f))))
  17099. (setq tnames (append tnames (list (file-truename f))))))
  17100. (multi-occur
  17101. (mapcar (lambda (x)
  17102. (with-current-buffer
  17103. ;; FIXME: Why not just (find-file-noselect x)?
  17104. ;; Is it to avoid the "revert buffer" prompt?
  17105. (or (get-file-buffer x) (find-file-noselect x))
  17106. (widen)
  17107. (current-buffer)))
  17108. files)
  17109. regexp)))
  17110. (add-hook 'occur-mode-find-occurrence-hook
  17111. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17112. (defun org-occur-link-in-agenda-files ()
  17113. "Create a link and search for it in the agendas.
  17114. The link is not stored in `org-stored-links', it is just created
  17115. for the search purpose."
  17116. (interactive)
  17117. (let ((link (condition-case nil
  17118. (org-store-link nil)
  17119. (error "Unable to create a link to here"))))
  17120. (org-occur-in-agenda-files (regexp-quote link))))
  17121. (defun org-back-over-empty-lines ()
  17122. "Move backwards over whitespace, to the beginning of the first empty line.
  17123. Returns the number of empty lines passed."
  17124. (let ((pos (point)))
  17125. (if (cdr (assq 'heading org-blank-before-new-entry))
  17126. (skip-chars-backward " \t\n\r")
  17127. (unless (eobp)
  17128. (forward-line -1)))
  17129. (beginning-of-line 2)
  17130. (goto-char (min (point) pos))
  17131. (count-lines (point) pos)))
  17132. ;;; TODO: Only called once, from ox-odt which should probably use
  17133. ;;; org-export-inline-image-p or something.
  17134. (defun org-file-image-p (file)
  17135. "Return non-nil if FILE is an image."
  17136. (save-match-data
  17137. (string-match (image-file-name-regexp) file)))
  17138. (defun org-get-cursor-date (&optional with-time)
  17139. "Return the date at cursor in as a time.
  17140. This works in the calendar and in the agenda, anywhere else it just
  17141. returns the current time.
  17142. If WITH-TIME is non-nil, returns the time of the event at point (in
  17143. the agenda) or the current time of the day; otherwise returns the
  17144. earliest time on the cursor date that Org treats as that date
  17145. (bearing in mind `org-extend-today-until')."
  17146. (let (date day defd tp hod mod)
  17147. (when with-time
  17148. (setq tp (get-text-property (point) 'time))
  17149. (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  17150. (setq hod (string-to-number (match-string 1 tp))
  17151. mod (string-to-number (match-string 2 tp))))
  17152. (or tp (let ((now (decode-time)))
  17153. (setq hod (nth 2 now)
  17154. mod (nth 1 now)))))
  17155. (cond
  17156. ((eq major-mode 'calendar-mode)
  17157. (setq date (calendar-cursor-to-date)
  17158. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17159. (nth 1 date) (nth 0 date) (nth 2 date))))
  17160. ((eq major-mode 'org-agenda-mode)
  17161. (setq day (get-text-property (point) 'day))
  17162. (when day
  17163. (setq date (calendar-gregorian-from-absolute day)
  17164. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17165. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17166. (or defd (current-time))))
  17167. (defun org-mark-subtree (&optional up)
  17168. "Mark the current subtree.
  17169. This puts point at the start of the current subtree, and mark at
  17170. the end. If a numeric prefix UP is given, move up into the
  17171. hierarchy of headlines by UP levels before marking the subtree."
  17172. (interactive "P")
  17173. (org-with-limited-levels
  17174. (cond ((org-at-heading-p) (beginning-of-line))
  17175. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17176. (t (outline-previous-visible-heading 1))))
  17177. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17178. (if (called-interactively-p 'any)
  17179. (call-interactively 'org-mark-element)
  17180. (org-mark-element)))
  17181. ;;; Indentation
  17182. (defvar org-element-greater-elements)
  17183. (defun org--get-expected-indentation (element contentsp)
  17184. "Expected indentation column for current line, according to ELEMENT.
  17185. ELEMENT is an element containing point. CONTENTSP is non-nil
  17186. when indentation is to be computed according to contents of
  17187. ELEMENT."
  17188. (let ((type (org-element-type element))
  17189. (start (org-element-property :begin element))
  17190. (post-affiliated (org-element-property :post-affiliated element)))
  17191. (org-with-wide-buffer
  17192. (cond
  17193. (contentsp
  17194. (cl-case type
  17195. ((diary-sexp footnote-definition) 0)
  17196. ((headline inlinetask nil)
  17197. (if (not org-adapt-indentation) 0
  17198. (let ((level (org-current-level)))
  17199. (if level (1+ level) 0))))
  17200. ((item plain-list) (org-list-item-body-column post-affiliated))
  17201. (t
  17202. (goto-char start)
  17203. (current-indentation))))
  17204. ((and
  17205. (eq org-adapt-indentation 'headline-data)
  17206. (memq type '(planning clock node-property property-drawer drawer)))
  17207. (org--get-expected-indentation
  17208. (org-element-property :parent element) t))
  17209. ((memq type '(headline inlinetask nil))
  17210. (if (org-match-line "[ \t]*$")
  17211. (org--get-expected-indentation element t)
  17212. 0))
  17213. ((memq type '(diary-sexp footnote-definition)) 0)
  17214. ;; First paragraph of a footnote definition or an item.
  17215. ;; Indent like parent.
  17216. ((< (line-beginning-position) start)
  17217. (org--get-expected-indentation
  17218. (org-element-property :parent element) t))
  17219. ;; At first line: indent according to previous sibling, if any,
  17220. ;; ignoring footnote definitions and inline tasks, or parent's
  17221. ;; contents.
  17222. ((and ( = (line-beginning-position) start)
  17223. (eq org-adapt-indentation t))
  17224. (catch 'exit
  17225. (while t
  17226. (if (= (point-min) start) (throw 'exit 0)
  17227. (goto-char (1- start))
  17228. (let* ((previous (org-element-at-point))
  17229. (parent previous))
  17230. (while (and parent (<= (org-element-property :end parent) start))
  17231. (setq previous parent
  17232. parent (org-element-property :parent parent)))
  17233. (cond
  17234. ((not previous) (throw 'exit 0))
  17235. ((> (org-element-property :end previous) start)
  17236. (throw 'exit (org--get-expected-indentation previous t)))
  17237. ((memq (org-element-type previous)
  17238. '(footnote-definition inlinetask))
  17239. (setq start (org-element-property :begin previous)))
  17240. (t (goto-char (org-element-property :begin previous))
  17241. (throw 'exit
  17242. (if (bolp) (current-indentation)
  17243. ;; At first paragraph in an item or
  17244. ;; a footnote definition.
  17245. (org--get-expected-indentation
  17246. (org-element-property :parent previous) t))))))))))
  17247. ;; Otherwise, move to the first non-blank line above.
  17248. ((not (eq org-adapt-indentation 'headline-data))
  17249. (beginning-of-line)
  17250. (let ((pos (point)))
  17251. (skip-chars-backward " \r\t\n")
  17252. (cond
  17253. ;; Two blank lines end a footnote definition or a plain
  17254. ;; list. When we indent an empty line after them, the
  17255. ;; containing list or footnote definition is over, so it
  17256. ;; qualifies as a previous sibling. Therefore, we indent
  17257. ;; like its first line.
  17258. ((and (memq type '(footnote-definition plain-list))
  17259. (> (count-lines (point) pos) 2))
  17260. (goto-char start)
  17261. (current-indentation))
  17262. ;; Line above is the first one of a paragraph at the
  17263. ;; beginning of an item or a footnote definition. Indent
  17264. ;; like parent.
  17265. ((< (line-beginning-position) start)
  17266. (org--get-expected-indentation
  17267. (org-element-property :parent element) t))
  17268. ;; Line above is the beginning of an element, i.e., point
  17269. ;; was originally on the blank lines between element's start
  17270. ;; and contents.
  17271. ((= (line-beginning-position) post-affiliated)
  17272. (org--get-expected-indentation element t))
  17273. ;; POS is after contents in a greater element. Indent like
  17274. ;; the beginning of the element.
  17275. ((and (memq type org-element-greater-elements)
  17276. (let ((cend (org-element-property :contents-end element)))
  17277. (and cend (<= cend pos))))
  17278. ;; As a special case, if point is at the end of a footnote
  17279. ;; definition or an item, indent like the very last element
  17280. ;; within. If that last element is an item, indent like
  17281. ;; its contents.
  17282. (if (memq type '(footnote-definition item plain-list))
  17283. (let ((last (org-element-at-point)))
  17284. (goto-char pos)
  17285. (org--get-expected-indentation
  17286. last (eq (org-element-type last) 'item)))
  17287. (goto-char start)
  17288. (current-indentation)))
  17289. ;; In any other case, indent like the current line.
  17290. (t (current-indentation)))))
  17291. ;; Finally, no indentation is needed, fall back to 0.
  17292. (t (current-indentation))))))
  17293. (defun org--align-node-property ()
  17294. "Align node property at point.
  17295. Alignment is done according to `org-property-format', which see."
  17296. (when (save-excursion
  17297. (beginning-of-line)
  17298. (looking-at org-property-re))
  17299. (replace-match
  17300. (concat (match-string 4)
  17301. (org-trim
  17302. (format org-property-format (match-string 1) (match-string 3))))
  17303. t t)))
  17304. (defun org-indent-line ()
  17305. "Indent line depending on context.
  17306. Indentation is done according to the following rules:
  17307. - Footnote definitions, diary sexps, headlines and inline tasks
  17308. have to start at column 0.
  17309. - On the very first line of an element, consider, in order, the
  17310. next rules until one matches:
  17311. 1. If there's a sibling element before, ignoring footnote
  17312. definitions and inline tasks, indent like its first line.
  17313. 2. If element has a parent, indent like its contents. More
  17314. precisely, if parent is an item, indent after the bullet.
  17315. Else, indent like parent's first line.
  17316. 3. Otherwise, indent relatively to current level, if
  17317. `org-adapt-indentation' is non-nil, or to left margin.
  17318. - On a blank line at the end of an element, indent according to
  17319. the type of the element. More precisely
  17320. 1. If element is a plain list, an item, or a footnote
  17321. definition, indent like the very last element within.
  17322. 2. If element is a paragraph, indent like its last non blank
  17323. line.
  17324. 3. Otherwise, indent like its very first line.
  17325. - In the code part of a source block, use language major mode
  17326. to indent current line if `org-src-tab-acts-natively' is
  17327. non-nil. If it is nil, do nothing.
  17328. - Otherwise, indent like the first non-blank line above.
  17329. The function doesn't indent an item as it could break the whole
  17330. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17331. `\\[org-shiftmetaright]'.
  17332. Also align node properties according to `org-property-format'."
  17333. (interactive)
  17334. (unless (org-at-heading-p)
  17335. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17336. (type (org-element-type element)))
  17337. (cond ((and (memq type '(plain-list item))
  17338. (= (line-beginning-position)
  17339. (org-element-property :post-affiliated element)))
  17340. nil)
  17341. ((and (eq type 'latex-environment)
  17342. (>= (point) (org-element-property :post-affiliated element))
  17343. (< (point)
  17344. (org-with-point-at (org-element-property :end element)
  17345. (skip-chars-backward " \t\n")
  17346. (line-beginning-position 2))))
  17347. nil)
  17348. ((and (eq type 'src-block)
  17349. org-src-tab-acts-natively
  17350. (> (line-beginning-position)
  17351. (org-element-property :post-affiliated element))
  17352. (< (line-beginning-position)
  17353. (org-with-point-at (org-element-property :end element)
  17354. (skip-chars-backward " \t\n")
  17355. (line-beginning-position))))
  17356. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17357. (t
  17358. (let ((column (org--get-expected-indentation element nil)))
  17359. ;; Preserve current column.
  17360. (if (<= (current-column) (current-indentation))
  17361. (indent-line-to column)
  17362. (save-excursion (indent-line-to column))))
  17363. ;; Align node property. Also preserve current column.
  17364. (when (eq type 'node-property)
  17365. (let ((column (current-column)))
  17366. (org--align-node-property)
  17367. (org-move-to-column column))))))))
  17368. (defun org-indent-region (start end)
  17369. "Indent each non-blank line in the region.
  17370. Called from a program, START and END specify the region to
  17371. indent. The function will not indent contents of example blocks,
  17372. verse blocks and export blocks as leading white spaces are
  17373. assumed to be significant there."
  17374. (interactive "r")
  17375. (save-excursion
  17376. (goto-char start)
  17377. (skip-chars-forward " \r\t\n")
  17378. (unless (eobp) (beginning-of-line))
  17379. (let ((indent-to
  17380. (lambda (ind pos)
  17381. ;; Set IND as indentation for all lines between point and
  17382. ;; POS. Blank lines are ignored. Leave point after POS
  17383. ;; once done.
  17384. (let ((limit (copy-marker pos)))
  17385. (while (< (point) limit)
  17386. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17387. (forward-line))
  17388. (set-marker limit nil))))
  17389. (end (copy-marker end)))
  17390. (while (< (point) end)
  17391. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17392. (let* ((element (org-element-at-point))
  17393. (type (org-element-type element))
  17394. (element-end (copy-marker (org-element-property :end element)))
  17395. (ind (org--get-expected-indentation element nil)))
  17396. (cond
  17397. ;; Element indented as a single block. Example blocks
  17398. ;; preserving indentation are a special case since the
  17399. ;; "contents" must not be indented whereas the block
  17400. ;; boundaries can.
  17401. ((or (memq type '(export-block latex-environment))
  17402. (and (eq type 'example-block)
  17403. (not
  17404. (or org-src-preserve-indentation
  17405. (org-element-property :preserve-indent element)))))
  17406. (let ((offset (- ind (current-indentation))))
  17407. (unless (zerop offset)
  17408. (indent-rigidly (org-element-property :begin element)
  17409. (org-element-property :end element)
  17410. offset)))
  17411. (goto-char element-end))
  17412. ;; Elements indented line wise. Be sure to exclude
  17413. ;; example blocks (preserving indentation) and source
  17414. ;; blocks from this category as they are treated
  17415. ;; specially later.
  17416. ((or (memq type '(paragraph table table-row))
  17417. (not (or (org-element-property :contents-begin element)
  17418. (memq type '(example-block src-block)))))
  17419. (when (eq type 'node-property)
  17420. (org--align-node-property)
  17421. (beginning-of-line))
  17422. (funcall indent-to ind (min element-end end)))
  17423. ;; Elements consisting of three parts: before the
  17424. ;; contents, the contents, and after the contents. The
  17425. ;; contents are treated specially, according to the
  17426. ;; element type, or not indented at all. Other parts are
  17427. ;; indented as a single block.
  17428. (t
  17429. (let* ((post (copy-marker
  17430. (org-element-property :post-affiliated element)))
  17431. (cbeg
  17432. (copy-marker
  17433. (cond
  17434. ((not (org-element-property :contents-begin element))
  17435. ;; Fake contents for source blocks.
  17436. (org-with-wide-buffer
  17437. (goto-char post)
  17438. (line-beginning-position 2)))
  17439. ((memq type '(footnote-definition item plain-list))
  17440. ;; Contents in these elements could start on
  17441. ;; the same line as the beginning of the
  17442. ;; element. Make sure we start indenting
  17443. ;; from the second line.
  17444. (org-with-wide-buffer
  17445. (goto-char post)
  17446. (end-of-line)
  17447. (skip-chars-forward " \r\t\n")
  17448. (if (eobp) (point) (line-beginning-position))))
  17449. (t (org-element-property :contents-begin element)))))
  17450. (cend (copy-marker
  17451. (or (org-element-property :contents-end element)
  17452. ;; Fake contents for source blocks.
  17453. (org-with-wide-buffer
  17454. (goto-char element-end)
  17455. (skip-chars-backward " \r\t\n")
  17456. (line-beginning-position)))
  17457. t)))
  17458. ;; Do not change items indentation individually as it
  17459. ;; might break the list as a whole. On the other
  17460. ;; hand, when at a plain list, indent it as a whole.
  17461. (cond ((eq type 'plain-list)
  17462. (let ((offset (- ind (current-indentation))))
  17463. (unless (zerop offset)
  17464. (indent-rigidly (org-element-property :begin element)
  17465. (org-element-property :end element)
  17466. offset))
  17467. (goto-char cbeg)))
  17468. ((eq type 'item) (goto-char cbeg))
  17469. (t (funcall indent-to ind (min cbeg end))))
  17470. (when (< (point) end)
  17471. (cl-case type
  17472. ((example-block verse-block))
  17473. (src-block
  17474. ;; In a source block, indent source code
  17475. ;; according to language major mode, but only if
  17476. ;; `org-src-tab-acts-natively' is non-nil.
  17477. (when (and (< (point) end) org-src-tab-acts-natively)
  17478. (ignore-errors
  17479. (org-babel-do-in-edit-buffer
  17480. (indent-region (point-min) (point-max))))))
  17481. (t (org-indent-region (point) (min cend end))))
  17482. (goto-char (min cend end))
  17483. (when (< (point) end)
  17484. (funcall indent-to ind (min element-end end))))
  17485. (set-marker post nil)
  17486. (set-marker cbeg nil)
  17487. (set-marker cend nil))))
  17488. (set-marker element-end nil))))
  17489. (set-marker end nil))))
  17490. (defun org-indent-drawer ()
  17491. "Indent the drawer at point."
  17492. (interactive)
  17493. (unless (save-excursion
  17494. (beginning-of-line)
  17495. (looking-at-p org-drawer-regexp))
  17496. (user-error "Not at a drawer"))
  17497. (let ((element (org-element-at-point)))
  17498. (unless (memq (org-element-type element) '(drawer property-drawer))
  17499. (user-error "Not at a drawer"))
  17500. (org-with-wide-buffer
  17501. (org-indent-region (org-element-property :begin element)
  17502. (org-element-property :end element))))
  17503. (message "Drawer at point indented"))
  17504. (defun org-indent-block ()
  17505. "Indent the block at point."
  17506. (interactive)
  17507. (unless (save-excursion
  17508. (beginning-of-line)
  17509. (let ((case-fold-search t))
  17510. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17511. (user-error "Not at a block"))
  17512. (let ((element (org-element-at-point)))
  17513. (unless (memq (org-element-type element)
  17514. '(comment-block center-block dynamic-block example-block
  17515. export-block quote-block special-block
  17516. src-block verse-block))
  17517. (user-error "Not at a block"))
  17518. (org-with-wide-buffer
  17519. (org-indent-region (org-element-property :begin element)
  17520. (org-element-property :end element))))
  17521. (message "Block at point indented"))
  17522. ;;; Filling
  17523. ;; We use our own fill-paragraph and auto-fill functions.
  17524. ;; `org-fill-paragraph' relies on adaptive filling and context
  17525. ;; checking. Appropriate `fill-prefix' is computed with
  17526. ;; `org-adaptive-fill-function'.
  17527. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17528. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17529. ;; `org-adaptive-fill-function' value. Internally,
  17530. ;; `org-comment-line-break-function' breaks the line.
  17531. ;; `org-setup-filling' installs filling and auto-filling related
  17532. ;; variables during `org-mode' initialization.
  17533. (defun org-setup-filling ()
  17534. (require 'org-element)
  17535. ;; Prevent auto-fill from inserting unwanted new items.
  17536. (when (boundp 'fill-nobreak-predicate)
  17537. (setq-local
  17538. fill-nobreak-predicate
  17539. (org-uniquify
  17540. (append fill-nobreak-predicate
  17541. '(org-fill-line-break-nobreak-p
  17542. org-fill-n-macro-as-item-nobreak-p
  17543. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17544. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17545. (setq-local paragraph-start paragraph-ending)
  17546. (setq-local paragraph-separate paragraph-ending))
  17547. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17548. (setq-local auto-fill-inhibit-regexp nil)
  17549. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17550. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17551. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17552. (defun org-fill-line-break-nobreak-p ()
  17553. "Non-nil when a new line at point would create an Org line break."
  17554. (save-excursion
  17555. (skip-chars-backward " \t")
  17556. (skip-chars-backward "\\\\")
  17557. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17558. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17559. "Non-nil when a new line at point would split a timestamp."
  17560. (and (org-at-timestamp-p 'lax)
  17561. (not (looking-at org-ts-regexp-both))))
  17562. (defun org-fill-n-macro-as-item-nobreak-p ()
  17563. "Non-nil when a new line at point would create a new list."
  17564. ;; During export, a "n" macro followed by a dot or a closing
  17565. ;; parenthesis can end up being parsed as a new list item.
  17566. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17567. (defun org-adaptive-fill-function ()
  17568. "Compute a fill prefix for the current line.
  17569. Return fill prefix, as a string, or nil if current line isn't
  17570. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17571. matches in paragraphs or comments, use it."
  17572. (org-with-wide-buffer
  17573. (unless (org-at-heading-p)
  17574. (let* ((p (line-beginning-position))
  17575. (element (save-excursion
  17576. (beginning-of-line)
  17577. (org-element-at-point)))
  17578. (type (org-element-type element))
  17579. (post-affiliated (org-element-property :post-affiliated element)))
  17580. (unless (< p post-affiliated)
  17581. (cl-case type
  17582. (comment
  17583. (save-excursion
  17584. (beginning-of-line)
  17585. (looking-at "[ \t]*")
  17586. (concat (match-string 0) "# ")))
  17587. (footnote-definition "")
  17588. ((item plain-list)
  17589. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17590. (paragraph
  17591. ;; Fill prefix is usually the same as the current line,
  17592. ;; unless the paragraph is at the beginning of an item.
  17593. (let ((parent (org-element-property :parent element)))
  17594. (save-excursion
  17595. (beginning-of-line)
  17596. (cond ((eq (org-element-type parent) 'item)
  17597. (make-string (org-list-item-body-column
  17598. (org-element-property :begin parent))
  17599. ?\s))
  17600. ((and adaptive-fill-regexp
  17601. ;; Locally disable
  17602. ;; `adaptive-fill-function' to let
  17603. ;; `fill-context-prefix' handle
  17604. ;; `adaptive-fill-regexp' variable.
  17605. (let (adaptive-fill-function)
  17606. (fill-context-prefix
  17607. post-affiliated
  17608. (org-element-property :end element)))))
  17609. ((looking-at "[ \t]+") (match-string 0))
  17610. (t "")))))
  17611. (comment-block
  17612. ;; Only fill contents if P is within block boundaries.
  17613. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17614. (forward-line)
  17615. (point)))
  17616. (cend (save-excursion
  17617. (goto-char (org-element-property :end element))
  17618. (skip-chars-backward " \r\t\n")
  17619. (line-beginning-position))))
  17620. (when (and (>= p cbeg) (< p cend))
  17621. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17622. (match-string 0)
  17623. ""))))))))))
  17624. (defun org-fill-element (&optional justify)
  17625. "Fill element at point, when applicable.
  17626. This function only applies to comment blocks, comments, example
  17627. blocks and paragraphs. Also, as a special case, re-align table
  17628. when point is at one.
  17629. If JUSTIFY is non-nil (interactively, with prefix argument),
  17630. justify as well. If `sentence-end-double-space' is non-nil, then
  17631. period followed by one space does not end a sentence, so don't
  17632. break a line there. The variable `fill-column' controls the
  17633. width for filling.
  17634. For convenience, when point is at a plain list, an item or
  17635. a footnote definition, try to fill the first paragraph within."
  17636. (with-syntax-table org-mode-transpose-word-syntax-table
  17637. ;; Move to end of line in order to get the first paragraph within
  17638. ;; a plain list or a footnote definition.
  17639. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17640. ;; First check if point is in a blank line at the beginning of
  17641. ;; the buffer. In that case, ignore filling.
  17642. (cl-case (org-element-type element)
  17643. ;; Use major mode filling function is source blocks.
  17644. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  17645. ;; Align Org tables, leave table.el tables as-is.
  17646. (table-row (org-table-align) t)
  17647. (table
  17648. (when (eq (org-element-property :type element) 'org)
  17649. (save-excursion
  17650. (goto-char (org-element-property :post-affiliated element))
  17651. (org-table-align)))
  17652. t)
  17653. (paragraph
  17654. ;; Paragraphs may contain `line-break' type objects.
  17655. (let ((beg (max (point-min)
  17656. (org-element-property :contents-begin element)))
  17657. (end (min (point-max)
  17658. (org-element-property :contents-end element))))
  17659. ;; Do nothing if point is at an affiliated keyword.
  17660. (if (< (line-end-position) beg) t
  17661. ;; Fill paragraph, taking line breaks into account.
  17662. (save-excursion
  17663. (goto-char beg)
  17664. (let ((cuts (list beg)))
  17665. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17666. (when (eq 'line-break
  17667. (org-element-type
  17668. (save-excursion (backward-char)
  17669. (org-element-context))))
  17670. (push (point) cuts)))
  17671. (dolist (c (delq end cuts))
  17672. (fill-region-as-paragraph c end justify)
  17673. (setq end c))))
  17674. t)))
  17675. ;; Contents of `comment-block' type elements should be
  17676. ;; filled as plain text, but only if point is within block
  17677. ;; markers.
  17678. (comment-block
  17679. (let* ((case-fold-search t)
  17680. (beg (save-excursion
  17681. (goto-char (org-element-property :begin element))
  17682. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17683. (forward-line)
  17684. (point)))
  17685. (end (save-excursion
  17686. (goto-char (org-element-property :end element))
  17687. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17688. (line-beginning-position))))
  17689. (if (or (< (point) beg) (> (point) end)) t
  17690. (fill-region-as-paragraph
  17691. (save-excursion (end-of-line)
  17692. (re-search-backward "^[ \t]*$" beg 'move)
  17693. (line-beginning-position))
  17694. (save-excursion (beginning-of-line)
  17695. (re-search-forward "^[ \t]*$" end 'move)
  17696. (line-beginning-position))
  17697. justify))))
  17698. ;; Fill comments.
  17699. (comment
  17700. (let ((begin (org-element-property :post-affiliated element))
  17701. (end (org-element-property :end element)))
  17702. (when (and (>= (point) begin) (<= (point) end))
  17703. (let ((begin (save-excursion
  17704. (end-of-line)
  17705. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17706. (progn (forward-line) (point))
  17707. begin)))
  17708. (end (save-excursion
  17709. (end-of-line)
  17710. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17711. (1- (line-beginning-position))
  17712. (skip-chars-backward " \r\t\n")
  17713. (line-end-position)))))
  17714. ;; Do not fill comments when at a blank line.
  17715. (when (> end begin)
  17716. (let ((fill-prefix
  17717. (save-excursion
  17718. (beginning-of-line)
  17719. (looking-at "[ \t]*#")
  17720. (let ((comment-prefix (match-string 0)))
  17721. (goto-char (match-end 0))
  17722. (if (looking-at adaptive-fill-regexp)
  17723. (concat comment-prefix (match-string 0))
  17724. (concat comment-prefix " "))))))
  17725. (save-excursion
  17726. (fill-region-as-paragraph begin end justify))))))
  17727. t))
  17728. ;; Ignore every other element.
  17729. (otherwise t)))))
  17730. (defun org-fill-paragraph (&optional justify region)
  17731. "Fill element at point, when applicable.
  17732. This function only applies to comment blocks, comments, example
  17733. blocks and paragraphs. Also, as a special case, re-align table
  17734. when point is at one.
  17735. For convenience, when point is at a plain list, an item or
  17736. a footnote definition, try to fill the first paragraph within.
  17737. If JUSTIFY is non-nil (interactively, with prefix argument),
  17738. justify as well. If `sentence-end-double-space' is non-nil, then
  17739. period followed by one space does not end a sentence, so don't
  17740. break a line there. The variable `fill-column' controls the
  17741. width for filling.
  17742. The REGION argument is non-nil if called interactively; in that
  17743. case, if Transient Mark mode is enabled and the mark is active,
  17744. fill each of the elements in the active region, instead of just
  17745. filling the current element."
  17746. (interactive (progn
  17747. (barf-if-buffer-read-only)
  17748. (list (when current-prefix-arg 'full) t)))
  17749. (let ((hash (and (not (buffer-modified-p))
  17750. (org-buffer-hash))))
  17751. (cond
  17752. ((and region transient-mark-mode mark-active
  17753. (not (eq (region-beginning) (region-end))))
  17754. (let ((origin (point-marker))
  17755. (start (region-beginning)))
  17756. (unwind-protect
  17757. (progn
  17758. (goto-char (region-end))
  17759. (skip-chars-backward " \t\n")
  17760. (while (> (point) start)
  17761. (org-fill-element justify)
  17762. (org-backward-paragraph)))
  17763. (goto-char origin)
  17764. (set-marker origin nil))))
  17765. (t
  17766. (save-excursion
  17767. (when (org-match-line "[ \t]*$")
  17768. (skip-chars-forward " \t\n"))
  17769. (org-fill-element justify))))
  17770. ;; If we didn't change anything in the buffer (and the buffer was
  17771. ;; previously unmodified), then flip the modification status back
  17772. ;; to "unchanged".
  17773. (when (and hash (equal hash (org-buffer-hash)))
  17774. (set-buffer-modified-p nil))))
  17775. (defun org-auto-fill-function ()
  17776. "Auto-fill function."
  17777. ;; Check if auto-filling is meaningful.
  17778. (let ((fc (current-fill-column)))
  17779. (when (and fc (> (current-column) fc))
  17780. (let* ((fill-prefix (org-adaptive-fill-function))
  17781. ;; Enforce empty fill prefix, if required. Otherwise, it
  17782. ;; will be computed again.
  17783. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17784. (when fill-prefix (do-auto-fill))))))
  17785. (defun org-comment-line-break-function (&optional soft)
  17786. "Break line at point and indent, continuing comment if within one.
  17787. The inserted newline is marked hard if variable
  17788. `use-hard-newlines' is true, unless optional argument SOFT is
  17789. non-nil."
  17790. (if soft (insert-and-inherit ?\n) (newline 1))
  17791. (save-excursion (forward-char -1) (delete-horizontal-space))
  17792. (delete-horizontal-space)
  17793. (indent-to-left-margin)
  17794. (insert-before-markers-and-inherit fill-prefix))
  17795. ;;; Fixed Width Areas
  17796. (defun org-toggle-fixed-width ()
  17797. "Toggle fixed-width markup.
  17798. Add or remove fixed-width markup on current line, whenever it
  17799. makes sense. Return an error otherwise.
  17800. If a region is active and if it contains only fixed-width areas
  17801. or blank lines, remove all fixed-width markup in it. If the
  17802. region contains anything else, convert all non-fixed-width lines
  17803. to fixed-width ones.
  17804. Blank lines at the end of the region are ignored unless the
  17805. region only contains such lines."
  17806. (interactive)
  17807. (if (not (org-region-active-p))
  17808. ;; No region:
  17809. ;;
  17810. ;; Remove fixed width marker only in a fixed-with element.
  17811. ;;
  17812. ;; Add fixed width maker in paragraphs, in blank lines after
  17813. ;; elements or at the beginning of a headline or an inlinetask,
  17814. ;; and before any one-line elements (e.g., a clock).
  17815. (progn
  17816. (beginning-of-line)
  17817. (let* ((element (org-element-at-point))
  17818. (type (org-element-type element)))
  17819. (cond
  17820. ((and (eq type 'fixed-width)
  17821. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  17822. (replace-match
  17823. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  17824. ((and (memq type '(babel-call clock comment diary-sexp headline
  17825. horizontal-rule keyword paragraph
  17826. planning))
  17827. (<= (org-element-property :post-affiliated element) (point)))
  17828. (skip-chars-forward " \t")
  17829. (insert ": "))
  17830. ((and (looking-at-p "[ \t]*$")
  17831. (or (eq type 'inlinetask)
  17832. (save-excursion
  17833. (skip-chars-forward " \r\t\n")
  17834. (<= (org-element-property :end element) (point)))))
  17835. (delete-region (point) (line-end-position))
  17836. (org-indent-line)
  17837. (insert ": "))
  17838. (t (user-error "Cannot insert a fixed-width line here")))))
  17839. ;; Region active.
  17840. (let* ((begin (save-excursion
  17841. (goto-char (region-beginning))
  17842. (line-beginning-position)))
  17843. (end (copy-marker
  17844. (save-excursion
  17845. (goto-char (region-end))
  17846. (unless (eolp) (beginning-of-line))
  17847. (if (save-excursion (re-search-backward "\\S-" begin t))
  17848. (progn (skip-chars-backward " \r\t\n") (point))
  17849. (point)))))
  17850. (all-fixed-width-p
  17851. (catch 'not-all-p
  17852. (save-excursion
  17853. (goto-char begin)
  17854. (skip-chars-forward " \r\t\n")
  17855. (when (eobp) (throw 'not-all-p nil))
  17856. (while (< (point) end)
  17857. (let ((element (org-element-at-point)))
  17858. (if (eq (org-element-type element) 'fixed-width)
  17859. (goto-char (org-element-property :end element))
  17860. (throw 'not-all-p nil))))
  17861. t))))
  17862. (if all-fixed-width-p
  17863. (save-excursion
  17864. (goto-char begin)
  17865. (while (< (point) end)
  17866. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  17867. (replace-match
  17868. "" nil nil nil
  17869. (if (= (line-end-position) (match-end 0)) 0 1)))
  17870. (forward-line)))
  17871. (let ((min-ind (point-max)))
  17872. ;; Find minimum indentation across all lines.
  17873. (save-excursion
  17874. (goto-char begin)
  17875. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  17876. (setq min-ind 0)
  17877. (catch 'zerop
  17878. (while (< (point) end)
  17879. (unless (looking-at-p "[ \t]*$")
  17880. (let ((ind (current-indentation)))
  17881. (setq min-ind (min min-ind ind))
  17882. (when (zerop ind) (throw 'zerop t))))
  17883. (forward-line)))))
  17884. ;; Loop over all lines and add fixed-width markup everywhere
  17885. ;; but in fixed-width lines.
  17886. (save-excursion
  17887. (goto-char begin)
  17888. (while (< (point) end)
  17889. (cond
  17890. ((org-at-heading-p)
  17891. (insert ": ")
  17892. (forward-line)
  17893. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  17894. (insert ":")
  17895. (forward-line)))
  17896. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  17897. (let* ((element (org-element-at-point))
  17898. (element-end (org-element-property :end element)))
  17899. (if (eq (org-element-type element) 'fixed-width)
  17900. (progn (goto-char element-end)
  17901. (skip-chars-backward " \r\t\n")
  17902. (forward-line))
  17903. (let ((limit (min end element-end)))
  17904. (while (< (point) limit)
  17905. (org-move-to-column min-ind t)
  17906. (insert ": ")
  17907. (forward-line))))))
  17908. (t
  17909. (org-move-to-column min-ind t)
  17910. (insert ": ")
  17911. (forward-line)))))))
  17912. (set-marker end nil))))
  17913. ;;; Blocks
  17914. (defun org-block-map (function &optional start end)
  17915. "Call FUNCTION at the head of all source blocks in the current buffer.
  17916. Optional arguments START and END can be used to limit the range."
  17917. (let ((start (or start (point-min)))
  17918. (end (or end (point-max))))
  17919. (save-excursion
  17920. (goto-char start)
  17921. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  17922. (save-excursion
  17923. (save-match-data
  17924. (goto-char (match-beginning 0))
  17925. (funcall function)))))))
  17926. (defun org-next-block (arg &optional backward block-regexp)
  17927. "Jump to the next block.
  17928. With a prefix argument ARG, jump forward ARG many blocks.
  17929. When BACKWARD is non-nil, jump to the previous block.
  17930. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  17931. Match data is set according to this regexp when the function
  17932. returns.
  17933. Return point at beginning of the opening line of found block.
  17934. Throw an error if no block is found."
  17935. (interactive "p")
  17936. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  17937. (case-fold-search t)
  17938. (search-fn (if backward #'re-search-backward #'re-search-forward))
  17939. (count (or arg 1))
  17940. (origin (point))
  17941. last-element)
  17942. (if backward (beginning-of-line) (end-of-line))
  17943. (while (and (> count 0) (funcall search-fn re nil t))
  17944. (let ((element (save-excursion
  17945. (goto-char (match-beginning 0))
  17946. (save-match-data (org-element-at-point)))))
  17947. (when (and (memq (org-element-type element)
  17948. '(center-block comment-block dynamic-block
  17949. example-block export-block quote-block
  17950. special-block src-block verse-block))
  17951. (<= (match-beginning 0)
  17952. (org-element-property :post-affiliated element)))
  17953. (setq last-element element)
  17954. (cl-decf count))))
  17955. (if (= count 0)
  17956. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  17957. (save-match-data (org-show-context)))
  17958. (goto-char origin)
  17959. (user-error "No %s code blocks" (if backward "previous" "further")))))
  17960. (defun org-previous-block (arg &optional block-regexp)
  17961. "Jump to the previous block.
  17962. With a prefix argument ARG, jump backward ARG many source blocks.
  17963. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  17964. (interactive "p")
  17965. (org-next-block arg t block-regexp))
  17966. ;;; Comments
  17967. ;; Org comments syntax is quite complex. It requires the entire line
  17968. ;; to be just a comment. Also, even with the right syntax at the
  17969. ;; beginning of line, some elements (e.g., verse-block or
  17970. ;; example-block) don't accept comments. Usual Emacs comment commands
  17971. ;; cannot cope with those requirements. Therefore, Org replaces them.
  17972. ;; Org still relies on `comment-dwim', but cannot trust
  17973. ;; `comment-only-p'. So, `comment-region-function' and
  17974. ;; `uncomment-region-function' both point
  17975. ;; to`org-comment-or-uncomment-region'. Eventually,
  17976. ;; `org-insert-comment' takes care of insertion of comments at the
  17977. ;; beginning of line.
  17978. ;; `org-setup-comments-handling' install comments related variables
  17979. ;; during `org-mode' initialization.
  17980. (defun org-setup-comments-handling ()
  17981. (interactive)
  17982. (setq-local comment-use-syntax nil)
  17983. (setq-local comment-start "# ")
  17984. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  17985. (setq-local comment-insert-comment-function 'org-insert-comment)
  17986. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  17987. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  17988. (defun org-insert-comment ()
  17989. "Insert an empty comment above current line.
  17990. If the line is empty, insert comment at its beginning. When
  17991. point is within a source block, comment according to the related
  17992. major mode."
  17993. (if (let ((element (org-element-at-point)))
  17994. (and (eq (org-element-type element) 'src-block)
  17995. (< (save-excursion
  17996. (goto-char (org-element-property :post-affiliated element))
  17997. (line-end-position))
  17998. (point))
  17999. (> (save-excursion
  18000. (goto-char (org-element-property :end element))
  18001. (skip-chars-backward " \r\t\n")
  18002. (line-beginning-position))
  18003. (point))))
  18004. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  18005. (beginning-of-line)
  18006. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  18007. (open-line 1))
  18008. (org-indent-line)
  18009. (insert "# ")))
  18010. (defvar comment-empty-lines) ; From newcomment.el.
  18011. (defun org-comment-or-uncomment-region (beg end &rest _)
  18012. "Comment or uncomment each non-blank line in the region.
  18013. Uncomment each non-blank line between BEG and END if it only
  18014. contains commented lines. Otherwise, comment them. If region is
  18015. strictly within a source block, use appropriate comment syntax."
  18016. (if (let ((element (org-element-at-point)))
  18017. (and (eq (org-element-type element) 'src-block)
  18018. (< (save-excursion
  18019. (goto-char (org-element-property :post-affiliated element))
  18020. (line-end-position))
  18021. beg)
  18022. (>= (save-excursion
  18023. (goto-char (org-element-property :end element))
  18024. (skip-chars-backward " \r\t\n")
  18025. (line-beginning-position))
  18026. end)))
  18027. ;; Translate region boundaries for the Org buffer to the source
  18028. ;; buffer.
  18029. (let ((offset (- end beg)))
  18030. (save-excursion
  18031. (goto-char beg)
  18032. (org-babel-do-in-edit-buffer
  18033. (comment-or-uncomment-region (point) (+ offset (point))))))
  18034. (save-restriction
  18035. ;; Restrict region
  18036. (narrow-to-region (save-excursion (goto-char beg)
  18037. (skip-chars-forward " \r\t\n" end)
  18038. (line-beginning-position))
  18039. (save-excursion (goto-char end)
  18040. (skip-chars-backward " \r\t\n" beg)
  18041. (line-end-position)))
  18042. (let ((uncommentp
  18043. ;; UNCOMMENTP is non-nil when every non blank line between
  18044. ;; BEG and END is a comment.
  18045. (save-excursion
  18046. (goto-char (point-min))
  18047. (while (and (not (eobp))
  18048. (let ((element (org-element-at-point)))
  18049. (and (eq (org-element-type element) 'comment)
  18050. (goto-char (min (point-max)
  18051. (org-element-property
  18052. :end element)))))))
  18053. (eobp))))
  18054. (if uncommentp
  18055. ;; Only blank lines and comments in region: uncomment it.
  18056. (save-excursion
  18057. (goto-char (point-min))
  18058. (while (not (eobp))
  18059. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  18060. (replace-match "" nil nil nil 1))
  18061. (forward-line)))
  18062. ;; Comment each line in region.
  18063. (let ((min-indent (point-max)))
  18064. ;; First find the minimum indentation across all lines.
  18065. (save-excursion
  18066. (goto-char (point-min))
  18067. (while (and (not (eobp)) (not (zerop min-indent)))
  18068. (unless (looking-at "[ \t]*$")
  18069. (setq min-indent (min min-indent (current-indentation))))
  18070. (forward-line)))
  18071. ;; Then loop over all lines.
  18072. (save-excursion
  18073. (goto-char (point-min))
  18074. (while (not (eobp))
  18075. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18076. ;; Don't get fooled by invisible text (e.g. link path)
  18077. ;; when moving to column MIN-INDENT.
  18078. (let ((buffer-invisibility-spec nil))
  18079. (org-move-to-column min-indent t))
  18080. (insert comment-start))
  18081. (forward-line)))))))))
  18082. (defun org-comment-dwim (_arg)
  18083. "Call the comment command you mean.
  18084. Call `org-toggle-comment' if on a heading, otherwise call
  18085. `comment-dwim', within a source edit buffer if needed."
  18086. (interactive "*P")
  18087. (cond ((org-at-heading-p)
  18088. (call-interactively #'org-toggle-comment))
  18089. ((org-in-src-block-p)
  18090. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18091. (t (call-interactively #'comment-dwim))))
  18092. ;;; Timestamps API
  18093. ;; This section contains tools to operate on, or create, timestamp
  18094. ;; objects, as returned by, e.g. `org-element-context'.
  18095. (defun org-timestamp-from-string (s)
  18096. "Convert Org timestamp S, as a string, into a timestamp object.
  18097. Return nil if S is not a valid timestamp string."
  18098. (when (org-string-nw-p s)
  18099. (with-temp-buffer
  18100. (save-excursion (insert s))
  18101. (org-element-timestamp-parser))))
  18102. (defun org-timestamp-from-time (time &optional with-time inactive)
  18103. "Convert a time value into a timestamp object.
  18104. TIME is an Emacs internal time representation, as returned, e.g.,
  18105. by `current-time'.
  18106. When optional argument WITH-TIME is non-nil, return a timestamp
  18107. object with a time part, i.e., with hours and minutes.
  18108. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18109. return an active timestamp."
  18110. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18111. (org-element-create 'timestamp
  18112. (list :type (if inactive 'inactive 'active)
  18113. :year-start year
  18114. :month-start month
  18115. :day-start day
  18116. :hour-start (and with-time hour)
  18117. :minute-start (and with-time minute)))))
  18118. (defun org-timestamp-to-time (timestamp &optional end)
  18119. "Convert TIMESTAMP object into an Emacs internal time value.
  18120. Use end of date range or time range when END is non-nil.
  18121. Otherwise, use its start."
  18122. (apply #'encode-time 0
  18123. (mapcar
  18124. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18125. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18126. '(:minute-start :hour-start :day-start :month-start
  18127. :year-start)))))
  18128. (defun org-timestamp-has-time-p (timestamp)
  18129. "Non-nil when TIMESTAMP has a time specified."
  18130. (org-element-property :hour-start timestamp))
  18131. (defun org-timestamp-format (timestamp format &optional end utc)
  18132. "Format a TIMESTAMP object into a string.
  18133. FORMAT is a format specifier to be passed to
  18134. `format-time-string'.
  18135. When optional argument END is non-nil, use end of date-range or
  18136. time-range, if possible.
  18137. When optional argument UTC is non-nil, time is be expressed as
  18138. Universal Time."
  18139. (format-time-string format (org-timestamp-to-time timestamp end)
  18140. (and utc t)))
  18141. (defun org-timestamp-split-range (timestamp &optional end)
  18142. "Extract a TIMESTAMP object from a date or time range.
  18143. END, when non-nil, means extract the end of the range.
  18144. Otherwise, extract its start.
  18145. Return a new timestamp object."
  18146. (let ((type (org-element-property :type timestamp)))
  18147. (if (memq type '(active inactive diary)) timestamp
  18148. (let ((split-ts (org-element-copy timestamp)))
  18149. ;; Set new type.
  18150. (org-element-put-property
  18151. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18152. ;; Copy start properties over end properties if END is
  18153. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18154. (let ((p-alist '((:minute-start . :minute-end)
  18155. (:hour-start . :hour-end)
  18156. (:day-start . :day-end)
  18157. (:month-start . :month-end)
  18158. (:year-start . :year-end))))
  18159. (dolist (p-cell p-alist)
  18160. (org-element-put-property
  18161. split-ts
  18162. (funcall (if end #'car #'cdr) p-cell)
  18163. (org-element-property
  18164. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18165. ;; Eventually refresh `:raw-value'.
  18166. (org-element-put-property split-ts :raw-value nil)
  18167. (org-element-put-property
  18168. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18169. (defun org-timestamp-translate (timestamp &optional boundary)
  18170. "Translate TIMESTAMP object to custom format.
  18171. Format string is defined in `org-time-stamp-custom-formats',
  18172. which see.
  18173. When optional argument BOUNDARY is non-nil, it is either the
  18174. symbol `start' or `end'. In this case, only translate the
  18175. starting or ending part of TIMESTAMP if it is a date or time
  18176. range. Otherwise, translate both parts.
  18177. Return timestamp as-is if `org-display-custom-times' is nil or if
  18178. it has a `diary' type."
  18179. (let ((type (org-element-property :type timestamp)))
  18180. (if (or (not org-display-custom-times) (eq type 'diary))
  18181. (org-element-interpret-data timestamp)
  18182. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18183. org-time-stamp-custom-formats)))
  18184. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18185. (concat (org-timestamp-format timestamp fmt)
  18186. "--"
  18187. (org-timestamp-format timestamp fmt t))
  18188. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18189. ;;; Other stuff
  18190. (defvar reftex-docstruct-symbol)
  18191. (defvar org--rds)
  18192. (defun org-reftex-citation ()
  18193. "Use reftex-citation to insert a citation into the buffer.
  18194. This looks for a line like
  18195. #+BIBLIOGRAPHY: foo plain option:-d
  18196. and derives from it that foo.bib is the bibliography file relevant
  18197. for this document. It then installs the necessary environment for RefTeX
  18198. to work in this buffer and calls `reftex-citation' to insert a citation
  18199. into the buffer.
  18200. Export of such citations to both LaTeX and HTML is handled by the contributed
  18201. package ox-bibtex by Taru Karttunen."
  18202. (interactive)
  18203. (let ((reftex-docstruct-symbol 'org--rds)
  18204. org--rds bib)
  18205. (org-with-wide-buffer
  18206. (let ((case-fold-search t)
  18207. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18208. (if (not (save-excursion
  18209. (or (re-search-forward re nil t)
  18210. (re-search-backward re nil t))))
  18211. (user-error "No bibliography defined in file")
  18212. (setq bib (concat (match-string 1) ".bib")
  18213. org--rds (list (list 'bib bib))))))
  18214. (call-interactively 'reftex-citation)))
  18215. ;;;; Functions extending outline functionality
  18216. (defun org-beginning-of-line (&optional n)
  18217. "Go to the beginning of the current visible line.
  18218. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18219. symbol `reversed', on the first attempt move to where the
  18220. headline text starts, and only move to beginning of line when the
  18221. cursor is already before the start of the text of the headline.
  18222. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18223. start of the text on the second attempt.
  18224. With argument N not nil or 1, move forward N - 1 lines first."
  18225. (interactive "^p")
  18226. (let ((origin (point))
  18227. (special (pcase org-special-ctrl-a/e
  18228. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18229. deactivate-mark)
  18230. ;; First move to a visible line.
  18231. (if (bound-and-true-p visual-line-mode)
  18232. (beginning-of-visual-line n)
  18233. (move-beginning-of-line n)
  18234. ;; `move-beginning-of-line' may leave point after invisible
  18235. ;; characters if line starts with such of these (e.g., with
  18236. ;; a link at column 0). Really move to the beginning of the
  18237. ;; current visible line.
  18238. (beginning-of-line))
  18239. (cond
  18240. ;; No special behavior. Point is already at the beginning of
  18241. ;; a line, logical or visual.
  18242. ((not special))
  18243. ;; `beginning-of-visual-line' left point before logical beginning
  18244. ;; of line: point is at the beginning of a visual line. Bail
  18245. ;; out.
  18246. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18247. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18248. ;; At a headline, special position is before the title, but
  18249. ;; after any TODO keyword or priority cookie.
  18250. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18251. (line-end-position)))
  18252. (bol (point)))
  18253. (if (eq special 'reversed)
  18254. (when (and (= origin bol) (eq last-command this-command))
  18255. (goto-char refpos))
  18256. (when (or (> origin refpos) (= origin bol))
  18257. (goto-char refpos)))))
  18258. ((and (looking-at org-list-full-item-re)
  18259. (memq (org-element-type (save-match-data (org-element-at-point)))
  18260. '(item plain-list)))
  18261. ;; Set special position at first white space character after
  18262. ;; bullet, and check-box, if any.
  18263. (let ((after-bullet
  18264. (let ((box (match-end 3)))
  18265. (cond ((not box) (match-end 1))
  18266. ((eq (char-after box) ?\s) (1+ box))
  18267. (t box)))))
  18268. (if (eq special 'reversed)
  18269. (when (and (= (point) origin) (eq last-command this-command))
  18270. (goto-char after-bullet))
  18271. (when (or (> origin after-bullet) (= (point) origin))
  18272. (goto-char after-bullet)))))
  18273. ;; No special context. Point is already at beginning of line.
  18274. (t nil))))
  18275. (defun org-end-of-line (&optional n)
  18276. "Go to the end of the line, but before ellipsis, if any.
  18277. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18278. symbol `reversed', ignore tags on the first attempt, and only
  18279. move to after the tags when the cursor is already beyond the end
  18280. of the headline.
  18281. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18282. on the second attempt.
  18283. With argument N not nil or 1, move forward N - 1 lines first."
  18284. (interactive "^p")
  18285. (let ((origin (point))
  18286. (special (pcase org-special-ctrl-a/e
  18287. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18288. deactivate-mark)
  18289. ;; First move to a visible line.
  18290. (if (bound-and-true-p visual-line-mode)
  18291. (beginning-of-visual-line n)
  18292. (move-beginning-of-line n))
  18293. (cond
  18294. ;; At a headline, with tags.
  18295. ((and special
  18296. (save-excursion
  18297. (beginning-of-line)
  18298. (let ((case-fold-search nil))
  18299. (looking-at org-complex-heading-regexp)))
  18300. (match-end 5))
  18301. (let ((tags (save-excursion
  18302. (goto-char (match-beginning 5))
  18303. (skip-chars-backward " \t")
  18304. (point)))
  18305. (visual-end (and (bound-and-true-p visual-line-mode)
  18306. (save-excursion
  18307. (end-of-visual-line)
  18308. (point)))))
  18309. ;; If `end-of-visual-line' brings us before end of line or
  18310. ;; even tags, i.e., the headline spans over multiple visual
  18311. ;; lines, move there.
  18312. (cond ((and visual-end
  18313. (< visual-end tags)
  18314. (<= origin visual-end))
  18315. (goto-char visual-end))
  18316. ((eq special 'reversed)
  18317. (if (and (= origin (line-end-position))
  18318. (eq this-command last-command))
  18319. (goto-char tags)
  18320. (end-of-line)))
  18321. (t
  18322. (if (or (< origin tags) (= origin (line-end-position)))
  18323. (goto-char tags)
  18324. (end-of-line))))))
  18325. ((bound-and-true-p visual-line-mode)
  18326. (let ((bol (line-beginning-position)))
  18327. (end-of-visual-line)
  18328. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18329. ;; end of a line, backtrack and use `end-of-line' instead.
  18330. (when (/= bol (line-beginning-position))
  18331. (goto-char bol)
  18332. (end-of-line))))
  18333. (t (end-of-line)))))
  18334. (defun org-backward-sentence (&optional _arg)
  18335. "Go to beginning of sentence, or beginning of table field.
  18336. This will call `backward-sentence' or `org-table-beginning-of-field',
  18337. depending on context."
  18338. (interactive)
  18339. (let* ((element (org-element-at-point))
  18340. (contents-begin (org-element-property :contents-begin element))
  18341. (table (org-element-lineage element '(table) t)))
  18342. (if (and table
  18343. (> (point) contents-begin)
  18344. (<= (point) (org-element-property :contents-end table)))
  18345. (call-interactively #'org-table-beginning-of-field)
  18346. (save-restriction
  18347. (when (and contents-begin
  18348. (< (point-min) contents-begin)
  18349. (> (point) contents-begin))
  18350. (narrow-to-region contents-begin
  18351. (org-element-property :contents-end element)))
  18352. (call-interactively #'backward-sentence)))))
  18353. (defun org-forward-sentence (&optional _arg)
  18354. "Go to end of sentence, or end of table field.
  18355. This will call `forward-sentence' or `org-table-end-of-field',
  18356. depending on context."
  18357. (interactive)
  18358. (if (and (org-at-heading-p)
  18359. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18360. (save-restriction
  18361. (narrow-to-region (line-beginning-position) (line-end-position))
  18362. (call-interactively #'forward-sentence))
  18363. (let* ((element (org-element-at-point))
  18364. (contents-end (org-element-property :contents-end element))
  18365. (table (org-element-lineage element '(table) t)))
  18366. (if (and table
  18367. (>= (point) (org-element-property :contents-begin table))
  18368. (< (point) contents-end))
  18369. (call-interactively #'org-table-end-of-field)
  18370. (save-restriction
  18371. (when (and contents-end
  18372. (> (point-max) contents-end)
  18373. ;; Skip blank lines between elements.
  18374. (< (org-element-property :end element)
  18375. (save-excursion (goto-char contents-end)
  18376. (skip-chars-forward " \r\t\n"))))
  18377. (narrow-to-region (org-element-property :contents-begin element)
  18378. contents-end))
  18379. ;; End of heading is considered as the end of a sentence.
  18380. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18381. (call-interactively #'forward-sentence)))))))
  18382. (defun org-kill-line (&optional _arg)
  18383. "Kill line, to tags or end of line."
  18384. (interactive)
  18385. (cond
  18386. ((or (not org-special-ctrl-k)
  18387. (bolp)
  18388. (not (org-at-heading-p)))
  18389. (when (and (get-char-property (line-end-position) 'invisible)
  18390. org-ctrl-k-protect-subtree
  18391. (or (eq org-ctrl-k-protect-subtree 'error)
  18392. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18393. (user-error
  18394. (substitute-command-keys
  18395. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18396. (call-interactively
  18397. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18398. ((org-match-line org-tag-line-re)
  18399. (let ((end (save-excursion
  18400. (goto-char (match-beginning 1))
  18401. (skip-chars-backward " \t")
  18402. (point))))
  18403. (if (<= end (point)) ;on tags part
  18404. (kill-region (point) (line-end-position))
  18405. (kill-region (point) end)))
  18406. ;; Only align tags when we are still on a heading:
  18407. (if (org-at-heading-p) (org-align-tags)))
  18408. (t (kill-region (point) (line-end-position)))))
  18409. (defun org-yank (&optional arg)
  18410. "Yank. If the kill is a subtree, treat it specially.
  18411. This command will look at the current kill and check if is a single
  18412. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18413. cursor is at the beginning of a line or after the stars of a currently
  18414. empty headline, then the yank is handled specially. How exactly depends
  18415. on the value of the following variables.
  18416. `org-yank-folded-subtrees'
  18417. By default, this variable is non-nil, which results in
  18418. subtree(s) being folded after insertion, except if doing so
  18419. would swallow text after the yanked text.
  18420. `org-yank-adjusted-subtrees'
  18421. When non-nil (the default value is nil), the subtree will be
  18422. promoted or demoted in order to fit into the local outline tree
  18423. structure, which means that the level will be adjusted so that it
  18424. becomes the smaller one of the two *visible* surrounding headings.
  18425. Any prefix to this command will cause `yank' to be called directly with
  18426. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18427. will just
  18428. plainly yank the text as it is.
  18429. \[1] The test checks if the first non-white line is a heading
  18430. and if there are no other headings with fewer stars."
  18431. (interactive "P")
  18432. (org-yank-generic 'yank arg))
  18433. (defun org-yank-generic (command arg)
  18434. "Perform some yank-like command.
  18435. This function implements the behavior described in the `org-yank'
  18436. documentation. However, it has been generalized to work for any
  18437. interactive command with similar behavior."
  18438. ;; pretend to be command COMMAND
  18439. (setq this-command command)
  18440. (if arg
  18441. (call-interactively command)
  18442. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18443. (and (org-kill-is-subtree-p)
  18444. (or (bolp)
  18445. (and (looking-at "[ \t]*$")
  18446. (string-match
  18447. "\\`\\*+\\'"
  18448. (buffer-substring (point-at-bol) (point)))))))
  18449. swallowp)
  18450. (cond
  18451. ((and subtreep org-yank-folded-subtrees)
  18452. (let ((beg (point))
  18453. end)
  18454. (if (and subtreep org-yank-adjusted-subtrees)
  18455. (org-paste-subtree nil nil 'for-yank)
  18456. (call-interactively command))
  18457. (setq end (point))
  18458. (goto-char beg)
  18459. (when (and (bolp) subtreep
  18460. (not (setq swallowp
  18461. (org-yank-folding-would-swallow-text beg end))))
  18462. (org-with-limited-levels
  18463. (or (looking-at org-outline-regexp)
  18464. (re-search-forward org-outline-regexp-bol end t))
  18465. (while (and (< (point) end) (looking-at org-outline-regexp))
  18466. (org-flag-subtree t)
  18467. (org-cycle-show-empty-lines 'folded)
  18468. (condition-case nil
  18469. (outline-forward-same-level 1)
  18470. (error (goto-char end))))))
  18471. (when swallowp
  18472. (message
  18473. "Inserted text not folded because that would swallow text"))
  18474. (goto-char end)
  18475. (skip-chars-forward " \t\n\r")
  18476. (beginning-of-line 1)
  18477. (push-mark beg 'nomsg)))
  18478. ((and subtreep org-yank-adjusted-subtrees)
  18479. (let ((beg (point-at-bol)))
  18480. (org-paste-subtree nil nil 'for-yank)
  18481. (push-mark beg 'nomsg)))
  18482. (t
  18483. (call-interactively command))))))
  18484. (defun org-yank-folding-would-swallow-text (beg end)
  18485. "Would hide-subtree at BEG swallow any text after END?"
  18486. (let (level)
  18487. (org-with-limited-levels
  18488. (save-excursion
  18489. (goto-char beg)
  18490. (when (or (looking-at org-outline-regexp)
  18491. (re-search-forward org-outline-regexp-bol end t))
  18492. (setq level (org-outline-level)))
  18493. (goto-char end)
  18494. (skip-chars-forward " \t\r\n\v\f")
  18495. (not (or (eobp)
  18496. (and (bolp) (looking-at-p org-outline-regexp)
  18497. (<= (org-outline-level) level))))))))
  18498. (defun org-back-to-heading (&optional invisible-ok)
  18499. "Call `outline-back-to-heading', but provide a better error message."
  18500. (condition-case nil
  18501. (outline-back-to-heading invisible-ok)
  18502. (error
  18503. (user-error "Before first headline at position %d in buffer %s"
  18504. (point) (current-buffer)))))
  18505. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18506. "Go back to heading or first point in buffer.
  18507. If point is before first heading go to first point in buffer
  18508. instead of back to heading."
  18509. (condition-case nil
  18510. (outline-back-to-heading invisible-ok)
  18511. (error
  18512. (goto-char (point-min)))))
  18513. (defun org-before-first-heading-p ()
  18514. "Before first heading?"
  18515. (org-with-limited-levels
  18516. (save-excursion
  18517. (end-of-line)
  18518. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18519. (defun org-at-heading-p (&optional _)
  18520. "Non-nil when on a headline."
  18521. (outline-on-heading-p t))
  18522. (defun org-in-commented-heading-p (&optional no-inheritance)
  18523. "Non-nil if point is under a commented heading.
  18524. This function also checks ancestors of the current headline,
  18525. unless optional argument NO-INHERITANCE is non-nil."
  18526. (cond
  18527. ((org-before-first-heading-p) nil)
  18528. ((let ((headline (nth 4 (org-heading-components))))
  18529. (and headline
  18530. (let ((case-fold-search nil))
  18531. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18532. headline)))))
  18533. (no-inheritance nil)
  18534. (t
  18535. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18536. (defun org-in-archived-heading-p (&optional no-inheritance)
  18537. "Non-nil if point is under an archived heading.
  18538. This function also checks ancestors of the current headline,
  18539. unless optional argument NO-INHERITANCE is non-nil."
  18540. (cond
  18541. ((org-before-first-heading-p) nil)
  18542. ((let ((tags (org-get-tags nil 'local)))
  18543. (and tags
  18544. (cl-some (apply-partially #'string= org-archive-tag) tags))))
  18545. (no-inheritance nil)
  18546. (t
  18547. (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p))))))
  18548. (defun org-at-comment-p nil
  18549. "Return t if cursor is in a commented line."
  18550. (save-excursion
  18551. (save-match-data
  18552. (beginning-of-line)
  18553. (looking-at org-comment-regexp))))
  18554. (defun org-at-keyword-p nil
  18555. "Return t if cursor is at a keyword-line."
  18556. (save-excursion
  18557. (move-beginning-of-line 1)
  18558. (looking-at org-keyword-regexp)))
  18559. (defun org-at-drawer-p nil
  18560. "Return t if cursor is at a drawer keyword."
  18561. (save-excursion
  18562. (move-beginning-of-line 1)
  18563. (looking-at org-drawer-regexp)))
  18564. (defun org-at-block-p nil
  18565. "Return t if cursor is at a block keyword."
  18566. (save-excursion
  18567. (move-beginning-of-line 1)
  18568. (looking-at org-block-regexp)))
  18569. (defun org-point-at-end-of-empty-headline ()
  18570. "If point is at the end of an empty headline, return t, else nil.
  18571. If the heading only contains a TODO keyword, it is still still considered
  18572. empty."
  18573. (let ((case-fold-search nil))
  18574. (and (looking-at "[ \t]*$")
  18575. org-todo-line-regexp
  18576. (save-excursion
  18577. (beginning-of-line)
  18578. (looking-at org-todo-line-regexp)
  18579. (string= (match-string 3) "")))))
  18580. (defun org-at-heading-or-item-p ()
  18581. (or (org-at-heading-p) (org-at-item-p)))
  18582. (defun org-up-heading-all (arg)
  18583. "Move to the heading line of which the present line is a subheading.
  18584. This function considers both visible and invisible heading lines.
  18585. With argument, move up ARG levels."
  18586. (outline-up-heading arg t))
  18587. (defun org-up-heading-safe ()
  18588. "Move to the heading line of which the present line is a subheading.
  18589. This version will not throw an error. It will return the level of the
  18590. headline found, or nil if no higher level is found.
  18591. Also, this function will be a lot faster than `outline-up-heading',
  18592. because it relies on stars being the outline starters. This can really
  18593. make a significant difference in outlines with very many siblings."
  18594. (when (ignore-errors (org-back-to-heading t))
  18595. (let ((level-up (1- (funcall outline-level))))
  18596. (and (> level-up 0)
  18597. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  18598. (funcall outline-level)))))
  18599. (defun org-up-heading-or-point-min ()
  18600. "Move to the heading line of which the present is a subheading, or point-min.
  18601. This version is needed to make point-min behave like a virtual
  18602. heading of level 0 for property-inheritance. It will return the
  18603. level of the headline found (down to 0) or nil if already at a
  18604. point before the first headline or at point-min."
  18605. (when (ignore-errors (org-back-to-heading t))
  18606. (if (< 1 (funcall outline-level))
  18607. (org-up-heading-safe)
  18608. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18609. (defun org-first-sibling-p ()
  18610. "Is this heading the first child of its parents?"
  18611. (interactive)
  18612. (let ((re org-outline-regexp-bol)
  18613. level l)
  18614. (unless (org-at-heading-p t)
  18615. (user-error "Not at a heading"))
  18616. (setq level (funcall outline-level))
  18617. (save-excursion
  18618. (if (not (re-search-backward re nil t))
  18619. t
  18620. (setq l (funcall outline-level))
  18621. (< l level)))))
  18622. (defun org-goto-sibling (&optional previous)
  18623. "Goto the next sibling, even if it is invisible.
  18624. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18625. when a sibling was found. When none is found, return nil and don't
  18626. move point."
  18627. (let ((fun (if previous 're-search-backward 're-search-forward))
  18628. (pos (point))
  18629. (re org-outline-regexp-bol)
  18630. level l)
  18631. (when (ignore-errors (org-back-to-heading t))
  18632. (setq level (funcall outline-level))
  18633. (catch 'exit
  18634. (or previous (forward-char 1))
  18635. (while (funcall fun re nil t)
  18636. (setq l (funcall outline-level))
  18637. (when (< l level) (goto-char pos) (throw 'exit nil))
  18638. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18639. (goto-char pos)
  18640. nil))))
  18641. (defun org-show-siblings ()
  18642. "Show all siblings of the current headline."
  18643. (save-excursion
  18644. (while (org-goto-sibling) (org-flag-heading nil)))
  18645. (save-excursion
  18646. (while (org-goto-sibling 'previous)
  18647. (org-flag-heading nil))))
  18648. (defun org-goto-first-child ()
  18649. "Goto the first child, even if it is invisible.
  18650. Return t when a child was found. Otherwise don't move point and
  18651. return nil."
  18652. (let (level (pos (point)) (re org-outline-regexp-bol))
  18653. (when (ignore-errors (org-back-to-heading t))
  18654. (setq level (outline-level))
  18655. (forward-char 1)
  18656. (if (and (re-search-forward re nil t) (> (outline-level) level))
  18657. (progn (goto-char (match-beginning 0)) t)
  18658. (goto-char pos) nil))))
  18659. (defun org-show-hidden-entry ()
  18660. "Show an entry where even the heading is hidden."
  18661. (save-excursion
  18662. (org-show-entry)))
  18663. (defun org-flag-heading (flag &optional entry)
  18664. "Flag the current heading. FLAG non-nil means make invisible.
  18665. When ENTRY is non-nil, show the entire entry."
  18666. (save-excursion
  18667. (org-back-to-heading t)
  18668. ;; Check if we should show the entire entry
  18669. (if (not entry)
  18670. (org-flag-region
  18671. (line-end-position 0) (line-end-position) flag 'outline)
  18672. (org-show-entry)
  18673. (save-excursion
  18674. (and (outline-next-heading)
  18675. (org-flag-heading nil))))))
  18676. (defun org-get-next-sibling ()
  18677. "Move to next heading of the same level, and return point.
  18678. If there is no such heading, return nil.
  18679. This is like outline-next-sibling, but invisible headings are ok."
  18680. (let ((level (funcall outline-level)))
  18681. (outline-next-heading)
  18682. (while (and (not (eobp)) (> (funcall outline-level) level))
  18683. (outline-next-heading))
  18684. (unless (or (eobp) (< (funcall outline-level) level))
  18685. (point))))
  18686. (defun org-get-last-sibling ()
  18687. "Move to previous heading of the same level, and return point.
  18688. If there is no such heading, return nil."
  18689. (let ((opoint (point))
  18690. (level (funcall outline-level)))
  18691. (outline-previous-heading)
  18692. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18693. (while (and (> (funcall outline-level) level)
  18694. (not (bobp)))
  18695. (outline-previous-heading))
  18696. (unless (< (funcall outline-level) level)
  18697. (point)))))
  18698. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18699. "Goto to the end of a subtree."
  18700. ;; This contains an exact copy of the original function, but it uses
  18701. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18702. ;; trees and before first headline. And is uses an invisible-ok argument.
  18703. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18704. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18705. ;; with many children and grandchildren etc, this can be much faster
  18706. ;; than the outline version.
  18707. (org-back-to-heading-or-point-min invisible-ok)
  18708. (let ((first t)
  18709. (level (funcall outline-level)))
  18710. (cond ((= level 0)
  18711. (goto-char (point-max)))
  18712. ((and (derived-mode-p 'org-mode) (< level 1000))
  18713. ;; A true heading (not a plain list item), in Org
  18714. ;; This means we can easily find the end by looking
  18715. ;; only for the right number of stars. Using a regexp to do
  18716. ;; this is so much faster than using a Lisp loop.
  18717. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18718. (forward-char 1)
  18719. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18720. (t
  18721. ;; something else, do it the slow way
  18722. (while (and (not (eobp))
  18723. (or first (> (funcall outline-level) level)))
  18724. (setq first nil)
  18725. (outline-next-heading))))
  18726. (unless to-heading
  18727. (when (memq (preceding-char) '(?\n ?\^M))
  18728. ;; Go to end of line before heading
  18729. (forward-char -1)
  18730. (when (memq (preceding-char) '(?\n ?\^M))
  18731. ;; leave blank line before heading
  18732. (forward-char -1)))))
  18733. (point))
  18734. (defun org-end-of-meta-data (&optional full)
  18735. "Skip planning line and properties drawer in current entry.
  18736. When optional argument FULL is t, also skip planning information,
  18737. clocking lines and any kind of drawer.
  18738. When FULL is non-nil but not t, skip planning information,
  18739. clocking lines and only non-regular drawers, i.e. properties and
  18740. logbook drawers."
  18741. (org-back-to-heading t)
  18742. (forward-line)
  18743. ;; Skip planning information.
  18744. (when (looking-at-p org-planning-line-re) (forward-line))
  18745. ;; Skip property drawer.
  18746. (when (looking-at org-property-drawer-re)
  18747. (goto-char (match-end 0))
  18748. (forward-line))
  18749. ;; When FULL is not nil, skip more.
  18750. (when (and full (not (org-at-heading-p)))
  18751. (catch 'exit
  18752. (let ((end (save-excursion (outline-next-heading) (point)))
  18753. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18754. (while (not (eobp))
  18755. (cond ;; Skip clock lines.
  18756. ((looking-at-p re) (forward-line))
  18757. ;; Skip logbook drawer.
  18758. ((looking-at-p org-logbook-drawer-re)
  18759. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18760. (forward-line)
  18761. (throw 'exit t)))
  18762. ;; When FULL is t, skip regular drawer too.
  18763. ((and (eq full t) (looking-at-p org-drawer-regexp))
  18764. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18765. (forward-line)
  18766. (throw 'exit t)))
  18767. (t (throw 'exit t))))))))
  18768. (defun org--line-fully-invisible-p ()
  18769. "Return non-nil if the current line is fully invisible."
  18770. (let ((line-beg (line-beginning-position))
  18771. (line-pos (1- (line-end-position)))
  18772. (is-invisible t))
  18773. (while (and (< line-beg line-pos) is-invisible)
  18774. (setq is-invisible (org-invisible-p line-pos))
  18775. (setq line-pos (1- line-pos)))
  18776. is-invisible))
  18777. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18778. "Move forward to the ARG'th subheading at same level as this one.
  18779. Stop at the first and last subheadings of a superior heading.
  18780. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18781. non-nil it will also look at invisible ones."
  18782. (interactive "p")
  18783. (let ((backward? (and arg (< arg 0))))
  18784. (if (org-before-first-heading-p)
  18785. (if backward? (goto-char (point-min)) (outline-next-heading))
  18786. (org-back-to-heading invisible-ok)
  18787. (unless backward? (end-of-line)) ;do not match current headline
  18788. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18789. (f (if backward? #'re-search-backward #'re-search-forward))
  18790. (count (if arg (abs arg) 1))
  18791. (result (point)))
  18792. (while (and (> count 0)
  18793. (funcall f org-outline-regexp-bol nil 'move))
  18794. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18795. (cond ((< l level) (setq count 0))
  18796. ((and (= l level)
  18797. (or invisible-ok
  18798. ;; FIXME: See commit a700fadd72 and the
  18799. ;; related discussion on why using
  18800. ;; `org--line-fully-invisible-p' is needed
  18801. ;; here, which is to serve the needs of an
  18802. ;; external package. If the change is
  18803. ;; wrong regarding Org itself, it should
  18804. ;; be removed.
  18805. (not (org--line-fully-invisible-p))))
  18806. (cl-decf count)
  18807. (when (= l level) (setq result (point)))))))
  18808. (goto-char result))
  18809. (beginning-of-line))))
  18810. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18811. "Move backward to the ARG'th subheading at same level as this one.
  18812. Stop at the first and last subheadings of a superior heading."
  18813. (interactive "p")
  18814. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18815. (defun org-next-visible-heading (arg)
  18816. "Move to the next visible heading line.
  18817. With ARG, repeats or can move backward if negative."
  18818. (interactive "p")
  18819. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  18820. (if (< arg 0)
  18821. (beginning-of-line)
  18822. (end-of-line))
  18823. (while (and (< arg 0) (re-search-backward regexp nil :move))
  18824. (unless (bobp)
  18825. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  18826. (`(outline . ,o)
  18827. (goto-char (overlay-start o))
  18828. (re-search-backward regexp nil :move))
  18829. (_ nil))))
  18830. (cl-incf arg))
  18831. (while (and (> arg 0) (re-search-forward regexp nil t))
  18832. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  18833. (`(outline . ,o)
  18834. (goto-char (overlay-end o))
  18835. (re-search-forward regexp nil :move))
  18836. (_
  18837. (end-of-line)
  18838. nil))) ;leave the loop
  18839. (cl-decf arg))
  18840. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  18841. (defun org-previous-visible-heading (arg)
  18842. "Move to the previous visible heading.
  18843. With ARG, repeats or can move forward if negative."
  18844. (interactive "p")
  18845. (org-next-visible-heading (- arg)))
  18846. (defun org-forward-paragraph (&optional arg)
  18847. "Move forward by a paragraph, or equivalent, unit.
  18848. With argument ARG, do it ARG times;
  18849. a negative argument ARG = -N means move backward N paragraphs.
  18850. The function moves point between two structural
  18851. elements (paragraphs, tables, lists, etc.).
  18852. It also provides the following special moves for convenience:
  18853. - on a table or a property drawer, move to its beginning;
  18854. - on comment, example, export, source and verse blocks, stop
  18855. at blank lines;
  18856. - skip consecutive clocks, diary S-exps, and keywords."
  18857. (interactive "^p")
  18858. (unless arg (setq arg 1))
  18859. (if (< arg 0) (org-backward-paragraph (- arg))
  18860. (while (and (> arg 0) (not (eobp)))
  18861. (org--forward-paragraph-once)
  18862. (cl-decf arg))
  18863. ;; Return moves left.
  18864. arg))
  18865. (defun org-backward-paragraph (&optional arg)
  18866. "Move backward by a paragraph, or equivalent, unit.
  18867. With argument ARG, do it ARG times;
  18868. a negative argument ARG = -N means move forward N paragraphs.
  18869. The function moves point between two structural
  18870. elements (paragraphs, tables, lists, etc.).
  18871. It also provides the following special moves for convenience:
  18872. - on a table or a property drawer, move to its beginning;
  18873. - on comment, example, export, source and verse blocks, stop
  18874. at blank lines;
  18875. - skip consecutive clocks, diary S-exps, and keywords."
  18876. (interactive "^p")
  18877. (unless arg (setq arg 1))
  18878. (if (< arg 0) (org-forward-paragraph (- arg))
  18879. (while (and (> arg 0) (not (bobp)))
  18880. (org--backward-paragraph-once)
  18881. (cl-decf arg))
  18882. ;; Return moves left.
  18883. arg))
  18884. (defun org--paragraph-at-point ()
  18885. "Return paragraph, or equivalent, element at point.
  18886. Paragraph element at point is the element at point, with the
  18887. following special cases:
  18888. - treat table rows (resp. node properties) as the table
  18889. \(resp. property drawer) containing them.
  18890. - treat plain lists with an item every line as a whole.
  18891. - treat consecutive keywords, clocks, and diary-sexps as a single
  18892. block.
  18893. Function may return a real element, or a pseudo-element with type
  18894. `pseudo-paragraph'."
  18895. (let* ((e (org-element-at-point))
  18896. (type (org-element-type e))
  18897. ;; If we need to fake a new pseudo-element, triplet is
  18898. ;;
  18899. ;; (BEG END PARENT)
  18900. ;;
  18901. ;; where BEG and END are element boundaries, and PARENT the
  18902. ;; element containing it, or nil.
  18903. (triplet
  18904. (cond
  18905. ((memq type '(table property-drawer))
  18906. (list (org-element-property :begin e)
  18907. (org-element-property :end e)
  18908. (org-element-property :parent e)))
  18909. ((memq type '(node-property table-row))
  18910. (let ((e (org-element-property :parent e)))
  18911. (list (org-element-property :begin e)
  18912. (org-element-property :end e)
  18913. (org-element-property :parent e))))
  18914. ((memq type '(clock diary-sexp keyword))
  18915. (let* ((regexp (pcase type
  18916. (`clock org-clock-line-re)
  18917. (`diary-sexp "%%(")
  18918. (_ org-keyword-regexp)))
  18919. (end (if (< 0 (org-element-property :post-blank e))
  18920. (org-element-property :end e)
  18921. (org-with-wide-buffer
  18922. (forward-line)
  18923. (while (looking-at regexp) (forward-line))
  18924. (skip-chars-forward " \t\n")
  18925. (line-beginning-position))))
  18926. (begin (org-with-point-at (org-element-property :begin e)
  18927. (while (and (not (bobp)) (looking-at regexp))
  18928. (forward-line -1))
  18929. ;; We may have gotten one line too far.
  18930. (if (looking-at regexp)
  18931. (point)
  18932. (line-beginning-position 2)))))
  18933. (list begin end (org-element-property :parent e))))
  18934. ;; Find the full plain list containing point, the check it
  18935. ;; contains exactly one line per item.
  18936. ((let ((l (org-element-lineage e '(plain-list) t)))
  18937. (while (memq (org-element-type (org-element-property :parent l))
  18938. '(item plain-list))
  18939. (setq l (org-element-property :parent l)))
  18940. (and l
  18941. (org-with-point-at (org-element-property :post-affiliated l)
  18942. (forward-line (length (org-element-property :structure l)))
  18943. (= (point) (org-element-property :contents-end l)))
  18944. ;; Return value.
  18945. (list (org-element-property :begin l)
  18946. (org-element-property :end l)
  18947. (org-element-property :parent l)))))
  18948. (t nil)))) ;no triplet: return element
  18949. (pcase triplet
  18950. (`(,b ,e ,p)
  18951. (org-element-create
  18952. 'pseudo-paragraph
  18953. (list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  18954. (_ e))))
  18955. (defun org--forward-paragraph-once ()
  18956. "Move forward to end of paragraph or equivalent, once.
  18957. See `org-forward-paragraph'."
  18958. (interactive)
  18959. (save-restriction
  18960. (widen)
  18961. (skip-chars-forward " \t\n")
  18962. (cond
  18963. ((eobp) nil)
  18964. ;; When inside a folded part, move out of it.
  18965. ((pcase (get-char-property-and-overlay (point) 'invisible)
  18966. (`(,(or `outline `org-hide-block) . ,o)
  18967. (goto-char (overlay-end o))
  18968. (forward-line)
  18969. t)
  18970. (_ nil)))
  18971. (t
  18972. (let* ((element (org--paragraph-at-point))
  18973. (type (org-element-type element))
  18974. (contents-begin (org-element-property :contents-begin element))
  18975. (end (org-element-property :end element))
  18976. (post-affiliated (org-element-property :post-affiliated element)))
  18977. (cond
  18978. ((eq type 'plain-list)
  18979. (forward-char)
  18980. (org--forward-paragraph-once))
  18981. ;; If the element is folded, skip it altogether.
  18982. ((pcase (org-with-point-at post-affiliated
  18983. (get-char-property-and-overlay (line-end-position)
  18984. 'invisible))
  18985. (`(,(or `outline `org-hide-block) . ,o)
  18986. (goto-char (overlay-end o))
  18987. (forward-line)
  18988. t)
  18989. (_ nil)))
  18990. ;; At a greater element, move inside.
  18991. ((and contents-begin
  18992. (> contents-begin (point))
  18993. (not (eq type 'paragraph)))
  18994. (goto-char contents-begin)
  18995. ;; Items and footnote definitions contents may not start at
  18996. ;; the beginning of the line. In this case, skip until the
  18997. ;; next paragraph.
  18998. (cond
  18999. ((not (bolp)) (org--forward-paragraph-once))
  19000. ((org-previous-line-empty-p) (forward-line -1))
  19001. (t nil)))
  19002. ;; Move between empty lines in some blocks.
  19003. ((memq type '(comment-block example-block export-block src-block
  19004. verse-block))
  19005. (let ((contents-start
  19006. (org-with-point-at post-affiliated
  19007. (line-beginning-position 2))))
  19008. (if (< (point) contents-start)
  19009. (goto-char contents-start)
  19010. (let ((contents-end
  19011. (org-with-point-at end
  19012. (skip-chars-backward " \t\n")
  19013. (line-beginning-position))))
  19014. (cond
  19015. ((>= (point) contents-end)
  19016. (goto-char end)
  19017. (skip-chars-backward " \t\n")
  19018. (forward-line))
  19019. ((re-search-forward "^[ \t]*\n" contents-end :move)
  19020. (forward-line -1))
  19021. (t nil))))))
  19022. (t
  19023. ;; Move to element's end.
  19024. (goto-char end)
  19025. (skip-chars-backward " \t\n")
  19026. (forward-line))))))))
  19027. (defun org--backward-paragraph-once ()
  19028. "Move backward to start of paragraph or equivalent, once.
  19029. See `org-backward-paragraph'."
  19030. (interactive)
  19031. (save-restriction
  19032. (widen)
  19033. (cond
  19034. ((bobp) nil)
  19035. ;; Blank lines at the beginning of the buffer.
  19036. ((and (org-match-line "^[ \t]*$")
  19037. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  19038. (goto-char (point-min)))
  19039. ;; When inside a folded part, move out of it.
  19040. ((pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  19041. (`(,(or `outline `org-hide-block) . ,o)
  19042. (goto-char (1- (overlay-start o)))
  19043. (org--backward-paragraph-once)
  19044. t)
  19045. (_ nil)))
  19046. (t
  19047. (let* ((element (org--paragraph-at-point))
  19048. (type (org-element-type element))
  19049. (begin (org-element-property :begin element))
  19050. (post-affiliated (org-element-property :post-affiliated element))
  19051. (contents-end (org-element-property :contents-end element))
  19052. (end (org-element-property :end element))
  19053. (parent (org-element-property :parent element))
  19054. (reach
  19055. ;; Move to the visible empty line above position P, or
  19056. ;; to position P. Return t.
  19057. (lambda (p)
  19058. (goto-char p)
  19059. (when (and (org-previous-line-empty-p)
  19060. (let ((end (line-end-position 0)))
  19061. (or (= end (point-min))
  19062. (not (org-invisible-p (1- end))))))
  19063. (forward-line -1))
  19064. t)))
  19065. (cond
  19066. ;; Already at the beginning of an element.
  19067. ((= begin (point))
  19068. (cond
  19069. ;; There is a blank line above. Move there.
  19070. ((and (org-previous-line-empty-p)
  19071. (not (org-invisible-p (1- (line-end-position 0)))))
  19072. (forward-line -1))
  19073. ;; At the beginning of the first element within a greater
  19074. ;; element. Move to the beginning of the greater element.
  19075. ((and parent (= begin (org-element-property :contents-begin parent)))
  19076. (funcall reach (org-element-property :begin parent)))
  19077. ;; Since we have to move anyway, find the beginning
  19078. ;; position of the element above.
  19079. (t
  19080. (forward-char -1)
  19081. (org--backward-paragraph-once))))
  19082. ;; Skip paragraphs at the very beginning of footnote
  19083. ;; definitions or items.
  19084. ((and (eq type 'paragraph)
  19085. (org-with-point-at begin (not (bolp))))
  19086. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  19087. ;; If the element is folded, skip it altogether.
  19088. ((org-with-point-at post-affiliated
  19089. (org-invisible-p (line-end-position) t))
  19090. (funcall reach begin))
  19091. ;; At the end of a greater element, move inside.
  19092. ((and contents-end
  19093. (<= contents-end (point))
  19094. (not (eq type 'paragraph)))
  19095. (cond
  19096. ((memq type '(footnote-definition plain-list))
  19097. (skip-chars-backward " \t\n")
  19098. (org--backward-paragraph-once))
  19099. ((= contents-end (point))
  19100. (forward-char -1)
  19101. (org--backward-paragraph-once))
  19102. (t
  19103. (goto-char contents-end))))
  19104. ;; Move between empty lines in some blocks.
  19105. ((and (memq type '(comment-block example-block export-block src-block
  19106. verse-block))
  19107. (let ((contents-start
  19108. (org-with-point-at post-affiliated
  19109. (line-beginning-position 2))))
  19110. (when (> (point) contents-start)
  19111. (let ((contents-end
  19112. (org-with-point-at end
  19113. (skip-chars-backward " \t\n")
  19114. (line-beginning-position))))
  19115. (if (> (point) contents-end)
  19116. (progn (goto-char contents-end) t)
  19117. (skip-chars-backward " \t\n" begin)
  19118. (re-search-backward "^[ \t]*\n" contents-start :move)
  19119. t))))))
  19120. ;; Move to element's start.
  19121. (t
  19122. (funcall reach begin))))))))
  19123. (defun org-forward-element ()
  19124. "Move forward by one element.
  19125. Move to the next element at the same level, when possible."
  19126. (interactive)
  19127. (cond ((eobp) (user-error "Cannot move further down"))
  19128. ((org-with-limited-levels (org-at-heading-p))
  19129. (let ((origin (point)))
  19130. (goto-char (org-end-of-subtree nil t))
  19131. (unless (org-with-limited-levels (org-at-heading-p))
  19132. (goto-char origin)
  19133. (user-error "Cannot move further down"))))
  19134. (t
  19135. (let* ((elem (org-element-at-point))
  19136. (end (org-element-property :end elem))
  19137. (parent (org-element-property :parent elem)))
  19138. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19139. (goto-char (org-element-property :end parent)))
  19140. ((integer-or-marker-p end) (goto-char end))
  19141. (t (message "No element at point")))))))
  19142. (defun org-backward-element ()
  19143. "Move backward by one element.
  19144. Move to the previous element at the same level, when possible."
  19145. (interactive)
  19146. (cond ((bobp) (user-error "Cannot move further up"))
  19147. ((org-with-limited-levels (org-at-heading-p))
  19148. ;; At a headline, move to the previous one, if any, or stay
  19149. ;; here.
  19150. (let ((origin (point)))
  19151. (org-with-limited-levels (org-backward-heading-same-level 1))
  19152. ;; When current headline has no sibling above, move to its
  19153. ;; parent.
  19154. (when (= (point) origin)
  19155. (or (org-with-limited-levels (org-up-heading-safe))
  19156. (progn (goto-char origin)
  19157. (user-error "Cannot move further up"))))))
  19158. (t
  19159. (let* ((elem (org-element-at-point))
  19160. (beg (org-element-property :begin elem)))
  19161. (cond
  19162. ;; Move to beginning of current element if point isn't
  19163. ;; there already.
  19164. ((null beg) (message "No element at point"))
  19165. ((/= (point) beg) (goto-char beg))
  19166. (t (goto-char beg)
  19167. (skip-chars-backward " \r\t\n")
  19168. (unless (bobp)
  19169. (let ((prev (org-element-at-point)))
  19170. (goto-char (org-element-property :begin prev))
  19171. (while (and (setq prev (org-element-property :parent prev))
  19172. (<= (org-element-property :end prev) beg))
  19173. (goto-char (org-element-property :begin prev)))))))))))
  19174. (defun org-up-element ()
  19175. "Move to upper element."
  19176. (interactive)
  19177. (if (org-with-limited-levels (org-at-heading-p))
  19178. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19179. (let* ((elem (org-element-at-point))
  19180. (parent (org-element-property :parent elem)))
  19181. (if parent (goto-char (org-element-property :begin parent))
  19182. (if (org-with-limited-levels (org-before-first-heading-p))
  19183. (user-error "No surrounding element")
  19184. (org-with-limited-levels (org-back-to-heading)))))))
  19185. (defun org-down-element ()
  19186. "Move to inner element."
  19187. (interactive)
  19188. (let ((element (org-element-at-point)))
  19189. (cond
  19190. ((memq (org-element-type element) '(plain-list table))
  19191. (goto-char (org-element-property :contents-begin element))
  19192. (forward-char))
  19193. ((memq (org-element-type element) org-element-greater-elements)
  19194. ;; If contents are hidden, first disclose them.
  19195. (when (org-invisible-p (line-end-position)) (org-cycle))
  19196. (goto-char (or (org-element-property :contents-begin element)
  19197. (user-error "No content for this element"))))
  19198. (t (user-error "No inner element")))))
  19199. (defun org-drag-element-backward ()
  19200. "Move backward element at point."
  19201. (interactive)
  19202. (let ((elem (or (org-element-at-point)
  19203. (user-error "No element at point"))))
  19204. (if (eq (org-element-type elem) 'headline)
  19205. ;; Preserve point when moving a whole tree, even if point was
  19206. ;; on blank lines below the headline.
  19207. (let ((offset (skip-chars-backward " \t\n")))
  19208. (unwind-protect (org-move-subtree-up)
  19209. (forward-char (- offset))))
  19210. (let ((prev-elem
  19211. (save-excursion
  19212. (goto-char (org-element-property :begin elem))
  19213. (skip-chars-backward " \r\t\n")
  19214. (unless (bobp)
  19215. (let* ((beg (org-element-property :begin elem))
  19216. (prev (org-element-at-point))
  19217. (up prev))
  19218. (while (and (setq up (org-element-property :parent up))
  19219. (<= (org-element-property :end up) beg))
  19220. (setq prev up))
  19221. prev)))))
  19222. ;; Error out if no previous element or previous element is
  19223. ;; a parent of the current one.
  19224. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19225. (user-error "Cannot drag element backward")
  19226. (let ((pos (point)))
  19227. (org-element-swap-A-B prev-elem elem)
  19228. (goto-char (+ (org-element-property :begin prev-elem)
  19229. (- pos (org-element-property :begin elem))))))))))
  19230. (defun org-drag-element-forward ()
  19231. "Move forward element at point."
  19232. (interactive)
  19233. (let* ((pos (point))
  19234. (elem (or (org-element-at-point)
  19235. (user-error "No element at point"))))
  19236. (when (= (point-max) (org-element-property :end elem))
  19237. (user-error "Cannot drag element forward"))
  19238. (goto-char (org-element-property :end elem))
  19239. (let ((next-elem (org-element-at-point)))
  19240. (when (or (org-element-nested-p elem next-elem)
  19241. (and (eq (org-element-type next-elem) 'headline)
  19242. (not (eq (org-element-type elem) 'headline))))
  19243. (goto-char pos)
  19244. (user-error "Cannot drag element forward"))
  19245. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19246. ;; body's length (without final blanks) and by the length of
  19247. ;; blanks between ELEM and NEXT-ELEM.
  19248. (let ((size-next (- (save-excursion
  19249. (goto-char (org-element-property :end next-elem))
  19250. (skip-chars-backward " \r\t\n")
  19251. (forward-line)
  19252. ;; Small correction if buffer doesn't end
  19253. ;; with a newline character.
  19254. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19255. (org-element-property :begin next-elem)))
  19256. (size-blank (- (org-element-property :end elem)
  19257. (save-excursion
  19258. (goto-char (org-element-property :end elem))
  19259. (skip-chars-backward " \r\t\n")
  19260. (forward-line)
  19261. (point)))))
  19262. (org-element-swap-A-B elem next-elem)
  19263. (goto-char (+ pos size-next size-blank))))))
  19264. (defun org-drag-line-forward (arg)
  19265. "Drag the line at point ARG lines forward."
  19266. (interactive "p")
  19267. (dotimes (_ (abs arg))
  19268. (let ((c (current-column)))
  19269. (if (< 0 arg)
  19270. (progn
  19271. (beginning-of-line 2)
  19272. (transpose-lines 1)
  19273. (beginning-of-line 0))
  19274. (transpose-lines 1)
  19275. (beginning-of-line -1))
  19276. (org-move-to-column c))))
  19277. (defun org-drag-line-backward (arg)
  19278. "Drag the line at point ARG lines backward."
  19279. (interactive "p")
  19280. (org-drag-line-forward (- arg)))
  19281. (defun org-mark-element ()
  19282. "Put point at beginning of this element, mark at end.
  19283. Interactively, if this command is repeated or (in Transient Mark
  19284. mode) if the mark is active, it marks the next element after the
  19285. ones already marked."
  19286. (interactive)
  19287. (let (deactivate-mark)
  19288. (if (and (called-interactively-p 'any)
  19289. (or (and (eq last-command this-command) (mark t))
  19290. (and transient-mark-mode mark-active)))
  19291. (set-mark
  19292. (save-excursion
  19293. (goto-char (mark))
  19294. (goto-char (org-element-property :end (org-element-at-point)))
  19295. (point)))
  19296. (let ((element (org-element-at-point)))
  19297. (end-of-line)
  19298. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19299. (goto-char (org-element-property :begin element))))))
  19300. (defun org-narrow-to-element ()
  19301. "Narrow buffer to current element."
  19302. (interactive)
  19303. (let ((elem (org-element-at-point)))
  19304. (cond
  19305. ((eq (car elem) 'headline)
  19306. (narrow-to-region
  19307. (org-element-property :begin elem)
  19308. (org-element-property :end elem)))
  19309. ((memq (car elem) org-element-greater-elements)
  19310. (narrow-to-region
  19311. (org-element-property :contents-begin elem)
  19312. (org-element-property :contents-end elem)))
  19313. (t
  19314. (narrow-to-region
  19315. (org-element-property :begin elem)
  19316. (org-element-property :end elem))))))
  19317. (defun org-transpose-element ()
  19318. "Transpose current and previous elements, keeping blank lines between.
  19319. Point is moved after both elements."
  19320. (interactive)
  19321. (org-skip-whitespace)
  19322. (let ((end (org-element-property :end (org-element-at-point))))
  19323. (org-drag-element-backward)
  19324. (goto-char end)))
  19325. (defun org-unindent-buffer ()
  19326. "Un-indent the visible part of the buffer.
  19327. Relative indentation (between items, inside blocks, etc.) isn't
  19328. modified."
  19329. (interactive)
  19330. (unless (eq major-mode 'org-mode)
  19331. (user-error "Cannot un-indent a buffer not in Org mode"))
  19332. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19333. (unindent-tree
  19334. (lambda (contents)
  19335. (dolist (element (reverse contents))
  19336. (if (memq (org-element-type element) '(headline section))
  19337. (funcall unindent-tree (org-element-contents element))
  19338. (save-excursion
  19339. (save-restriction
  19340. (narrow-to-region
  19341. (org-element-property :begin element)
  19342. (org-element-property :end element))
  19343. (org-do-remove-indentation))))))))
  19344. (funcall unindent-tree (org-element-contents parse-tree))))
  19345. (defun org-make-options-regexp (kwds &optional extra)
  19346. "Make a regular expression for keyword lines.
  19347. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19348. when non-nil, is a regexp matching keywords names."
  19349. (concat "^[ \t]*#\\+\\("
  19350. (regexp-opt kwds)
  19351. (and extra (concat (and kwds "\\|") extra))
  19352. "\\):[ \t]*\\(.*\\)"))
  19353. ;;; Conveniently switch to Info nodes
  19354. (defun org-info-find-node (&optional nodename)
  19355. "Find Info documentation NODENAME or Org documentation according context.
  19356. Started from `gnus-info-find-node'."
  19357. (interactive)
  19358. (Info-goto-node
  19359. (or nodename
  19360. (let ((default-org-info-node "(org) Top"))
  19361. (cond
  19362. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19363. ((eq 'org-mode major-mode)
  19364. (let* ((context (org-element-at-point))
  19365. (element-info-nodes ; compare to `org-element-all-elements'.
  19366. `((babel-call . "(org) Evaluating Code Blocks")
  19367. (center-block . "(org) Paragraphs")
  19368. (clock . ,default-org-info-node)
  19369. (comment . "(org) Comment Lines")
  19370. (comment-block . "(org) Comment Lines")
  19371. (diary-sexp . ,default-org-info-node)
  19372. (drawer . "(org) Drawers")
  19373. (dynamic-block . "(org) Dynamic Blocks")
  19374. (example-block . "(org) Literal Examples")
  19375. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19376. (fixed-width . ,default-org-info-node)
  19377. (footnote-definition . "(org) Creating Footnotes")
  19378. (headline . "(org) Document Structure")
  19379. (horizontal-rule . "(org) Built-in Table Editor")
  19380. (inlinetask . ,default-org-info-node)
  19381. (item . "(org) Plain Lists")
  19382. (keyword . "(org) Per-file keywords")
  19383. (latex-environment . "(org) LaTeX Export")
  19384. (node-property . "(org) Properties and Columns")
  19385. (paragraph . "(org) Paragraphs")
  19386. (plain-list . "(org) Plain Lists")
  19387. (planning . "(org) Deadlines and Scheduling")
  19388. (property-drawer . "(org) Properties and Columns")
  19389. (quote-block . "(org) Paragraphs")
  19390. (section . ,default-org-info-node)
  19391. (special-block . ,default-org-info-node)
  19392. (src-block . "(org) Working with Source Code")
  19393. (table . "(org) Tables")
  19394. (table-row . "(org) Tables")
  19395. (verse-block . "(org) Paragraphs"))))
  19396. (or (cdr (assoc (car context) element-info-nodes))
  19397. default-org-info-node)))
  19398. (t default-org-info-node))))))
  19399. ;;; Finish up
  19400. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19401. (lambda () (add-hook 'change-major-mode-hook
  19402. 'org-show-all 'append 'local)))
  19403. (provide 'org)
  19404. (run-hooks 'org-load-hook)
  19405. ;; Local variables:
  19406. ;; generated-autoload-file: "org-loaddefs.el"
  19407. ;; End:
  19408. ;;; org.el ends here