org.el 809 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2020 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Bastien Guerry <bzg@gnu.org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Version: 9.4-dev
  10. ;;
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the homepage of
  55. ;; Org mode, you can read the same text online as HTML. There is also an
  56. ;; excellent reference card made by Philip Rooke. This card can be found
  57. ;; in the doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar org-inlinetask-min-level)
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (eval-and-compile (require 'org-macs))
  82. (require 'org-compat)
  83. (require 'org-keys)
  84. (require 'ol)
  85. (require 'org-table)
  86. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  87. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  88. (defvar org-outline-regexp "\\*+ "
  89. "Regexp to match Org headlines.")
  90. (defvar org-outline-regexp-bol "^\\*+ "
  91. "Regexp to match Org headlines.
  92. This is similar to `org-outline-regexp' but additionally makes
  93. sure that we are at the beginning of the line.")
  94. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  95. "Matches a headline, putting stars and text into groups.
  96. Stars are put in group 1 and the trimmed body in group 2.")
  97. (declare-function calendar-check-holidays "holidays" (date))
  98. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  99. (declare-function cdlatex-math-symbol "ext:cdlatex")
  100. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  105. (declare-function org-agenda-redo "org-agenda" (&optional all))
  106. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  107. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  108. (declare-function org-archive-subtree-default "org-archive" ())
  109. (declare-function org-archive-to-archive-sibling "org-archive" ())
  110. (declare-function org-attach "org-attach" ())
  111. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  112. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  113. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  114. (declare-function org-clock-cancel "org-clock" ())
  115. (declare-function org-clock-display "org-clock" (&optional arg))
  116. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  117. (declare-function org-clock-goto "org-clock" (&optional select))
  118. (declare-function org-clock-in "org-clock" (&optional select start-time))
  119. (declare-function org-clock-in-last "org-clock" (&optional arg))
  120. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  121. (declare-function org-clock-out-if-current "org-clock" ())
  122. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  123. (declare-function org-clock-report "org-clock" (&optional arg))
  124. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  125. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  126. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  127. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  128. (declare-function org-clock-update-time-maybe "org-clock" ())
  129. (declare-function org-clocking-buffer "org-clock" ())
  130. (declare-function org-clocktable-shift "org-clock" (dir n))
  131. (declare-function org-columns-quit "org-colview" ())
  132. (declare-function org-columns-insert-dblock "org-colview" ())
  133. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  134. (declare-function org-element-at-point "org-element" ())
  135. (declare-function org-element-cache-refresh "org-element" (pos))
  136. (declare-function org-element-cache-reset "org-element" (&optional all))
  137. (declare-function org-element-contents "org-element" (element))
  138. (declare-function org-element-context "org-element" (&optional element))
  139. (declare-function org-element-copy "org-element" (datum))
  140. (declare-function org-element-create "org-element" (type &optional props &rest children))
  141. (declare-function org-element-interpret-data "org-element" (data))
  142. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  143. (declare-function org-element-link-parser "org-element" ())
  144. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  145. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  146. (declare-function org-element-property "org-element" (property element))
  147. (declare-function org-element-put-property "org-element" (element property value))
  148. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  149. (declare-function org-element-timestamp-parser "org-element" ())
  150. (declare-function org-element-type "org-element" (element))
  151. (declare-function org-export-dispatch "ox" (&optional arg))
  152. (declare-function org-export-get-backend "ox" (name))
  153. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  154. (declare-function org-feed-goto-inbox "org-feed" (feed))
  155. (declare-function org-feed-update-all "org-feed" ())
  156. (declare-function org-goto "org-goto" (&optional alternative-interface))
  157. (declare-function org-id-find-id-file "org-id" (id))
  158. (declare-function org-id-get-create "org-id" (&optional force))
  159. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  160. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  161. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  162. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  163. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  164. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  165. (declare-function org-timer "org-timer" (&optional restart no-insert))
  166. (declare-function org-timer-item "org-timer" (&optional arg))
  167. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  168. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  169. (declare-function org-timer-start "org-timer" (&optional offset))
  170. (declare-function org-timer-stop "org-timer" ())
  171. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  172. (declare-function org-update-radio-target-regexp "ol" ())
  173. (defvar ffap-url-regexp)
  174. (defvar org-element-paragraph-separate)
  175. (defvar org-indent-indentation-per-level)
  176. (defvar org-radio-target-regexp)
  177. (defvar org-target-link-regexp)
  178. (defvar org-target-regexp)
  179. ;; load languages based on value of `org-babel-load-languages'
  180. (defvar org-babel-load-languages)
  181. ;;;###autoload
  182. (defun org-babel-do-load-languages (sym value)
  183. "Load the languages defined in `org-babel-load-languages'."
  184. (set-default sym value)
  185. (dolist (pair org-babel-load-languages)
  186. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  187. (if active
  188. (require (intern (concat "ob-" lang)))
  189. (fmakunbound
  190. (intern (concat "org-babel-execute:" lang)))
  191. (fmakunbound
  192. (intern (concat "org-babel-expand-body:" lang)))))))
  193. ;;;###autoload
  194. (defun org-babel-load-file (file &optional compile)
  195. "Load Emacs Lisp source code blocks in the Org FILE.
  196. This function exports the source code using `org-babel-tangle'
  197. and then loads the resulting file using `load-file'. With
  198. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  199. byte-compiled before it is loaded."
  200. (interactive "fFile to load: \nP")
  201. (let* ((tangled-file (concat (file-name-sans-extension file) ".el")))
  202. ;; Tangle only if the Org file is newer than the Elisp file.
  203. (unless (org-file-newer-than-p
  204. tangled-file
  205. (file-attribute-modification-time (file-attributes file)))
  206. (org-babel-tangle-file file tangled-file "emacs-lisp"))
  207. (if compile
  208. (progn
  209. (byte-compile-file tangled-file 'load)
  210. (message "Compiled and loaded %s" tangled-file))
  211. (load-file tangled-file)
  212. (message "Loaded %s" tangled-file))))
  213. (defcustom org-babel-load-languages '((emacs-lisp . t))
  214. "Languages which can be evaluated in Org buffers.
  215. \\<org-mode-map>
  216. This list can be used to load support for any of the languages
  217. below. Each language will depend on a different set of system
  218. executables and/or Emacs modes.
  219. When a language is \"loaded\", code blocks in that language can
  220. be evaluated with `org-babel-execute-src-block', which is bound
  221. by default to \\[org-ctrl-c-ctrl-c].
  222. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  223. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  224. default, only Emacs Lisp is loaded, since it has no specific
  225. requirement."
  226. :group 'org-babel
  227. :set 'org-babel-do-load-languages
  228. :version "24.1"
  229. :type '(alist :tag "Babel Languages"
  230. :key-type
  231. (choice
  232. (const :tag "Awk" awk)
  233. (const :tag "C" C)
  234. (const :tag "R" R)
  235. (const :tag "Asymptote" asymptote)
  236. (const :tag "Calc" calc)
  237. (const :tag "Clojure" clojure)
  238. (const :tag "CSS" css)
  239. (const :tag "Ditaa" ditaa)
  240. (const :tag "Dot" dot)
  241. (const :tag "Ebnf2ps" ebnf2ps)
  242. (const :tag "Emacs Lisp" emacs-lisp)
  243. (const :tag "Forth" forth)
  244. (const :tag "Fortran" fortran)
  245. (const :tag "Gnuplot" gnuplot)
  246. (const :tag "Haskell" haskell)
  247. (const :tag "hledger" hledger)
  248. (const :tag "IO" io)
  249. (const :tag "J" J)
  250. (const :tag "Java" java)
  251. (const :tag "Javascript" js)
  252. (const :tag "LaTeX" latex)
  253. (const :tag "Ledger" ledger)
  254. (const :tag "Lilypond" lilypond)
  255. (const :tag "Lisp" lisp)
  256. (const :tag "Makefile" makefile)
  257. (const :tag "Maxima" maxima)
  258. (const :tag "Matlab" matlab)
  259. (const :tag "Mscgen" mscgen)
  260. (const :tag "Ocaml" ocaml)
  261. (const :tag "Octave" octave)
  262. (const :tag "Org" org)
  263. (const :tag "Perl" perl)
  264. (const :tag "Pico Lisp" picolisp)
  265. (const :tag "PlantUML" plantuml)
  266. (const :tag "Python" python)
  267. (const :tag "Ruby" ruby)
  268. (const :tag "Sass" sass)
  269. (const :tag "Scala" scala)
  270. (const :tag "Scheme" scheme)
  271. (const :tag "Screen" screen)
  272. (const :tag "Shell Script" shell)
  273. (const :tag "Shen" shen)
  274. (const :tag "Sql" sql)
  275. (const :tag "Sqlite" sqlite)
  276. (const :tag "Stan" stan)
  277. (const :tag "Vala" vala))
  278. :value-type (boolean :tag "Activate" :value t)))
  279. ;;;; Customization variables
  280. (defcustom org-clone-delete-id nil
  281. "Remove ID property of clones of a subtree.
  282. When non-nil, clones of a subtree don't inherit the ID property.
  283. Otherwise they inherit the ID property with a new unique
  284. identifier."
  285. :type 'boolean
  286. :version "24.1"
  287. :group 'org-id)
  288. ;;; Version
  289. (org-check-version)
  290. ;;;###autoload
  291. (defun org-version (&optional here full message)
  292. "Show the Org version.
  293. Interactively, or when MESSAGE is non-nil, show it in echo area.
  294. With prefix argument, or when HERE is non-nil, insert it at point.
  295. In non-interactive uses, a reduced version string is output unless
  296. FULL is given."
  297. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  298. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  299. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  300. (load-suffixes (list ".el"))
  301. (org-install-dir
  302. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  303. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  304. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  305. (let* ((load-suffixes save-load-suffixes)
  306. (release (org-release))
  307. (git-version (org-git-version))
  308. (version (format "Org mode version %s (%s @ %s)"
  309. release
  310. git-version
  311. (if org-install-dir
  312. (if (string= org-dir org-install-dir)
  313. org-install-dir
  314. (concat "mixed installation! "
  315. org-install-dir
  316. " and "
  317. org-dir))
  318. "org-loaddefs.el can not be found!")))
  319. (version1 (if full version release)))
  320. (when here (insert version1))
  321. (when message (message "%s" version1))
  322. version1)))
  323. (defconst org-version (org-version))
  324. ;;; Syntax Constants
  325. ;;;; Keyword
  326. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  327. "Regular expression for keyword-lines")
  328. ;;;; Block
  329. (defconst org-block-regexp
  330. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  331. "Regular expression for hiding blocks.")
  332. (defconst org-dblock-start-re
  333. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  334. "Matches the start line of a dynamic block, with parameters.")
  335. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  336. "Matches the end of a dynamic block.")
  337. ;;;; Clock and Planning
  338. (defconst org-clock-string "CLOCK:"
  339. "String used as prefix for timestamps clocking work hours on an item.")
  340. (defvar org-closed-string "CLOSED:"
  341. "String used as the prefix for timestamps logging closing a TODO entry.")
  342. (defvar org-deadline-string "DEADLINE:"
  343. "String to mark deadline entries.
  344. \\<org-mode-map>
  345. A deadline is this string, followed by a time stamp. It must be
  346. a word, terminated by a colon. You can insert a schedule keyword
  347. and a timestamp with `\\[org-deadline]'.")
  348. (defvar org-scheduled-string "SCHEDULED:"
  349. "String to mark scheduled TODO entries.
  350. \\<org-mode-map>
  351. A schedule is this string, followed by a time stamp. It must be
  352. a word, terminated by a colon. You can insert a schedule keyword
  353. and a timestamp with `\\[org-schedule]'.")
  354. (defconst org-ds-keyword-length
  355. (+ 2
  356. (apply #'max
  357. (mapcar #'length
  358. (list org-deadline-string org-scheduled-string
  359. org-clock-string org-closed-string))))
  360. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  361. (defconst org-planning-line-re
  362. (concat "^[ \t]*"
  363. (regexp-opt
  364. (list org-closed-string org-deadline-string org-scheduled-string)
  365. t))
  366. "Matches a line with planning info.
  367. Matched keyword is in group 1.")
  368. (defconst org-clock-line-re
  369. (concat "^[ \t]*" org-clock-string)
  370. "Matches a line with clock info.")
  371. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  372. "Matches the DEADLINE keyword.")
  373. (defconst org-deadline-time-regexp
  374. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  375. "Matches the DEADLINE keyword together with a time stamp.")
  376. (defconst org-deadline-time-hour-regexp
  377. (concat "\\<" org-deadline-string
  378. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy \t.-]*\\)>")
  379. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  380. (defconst org-deadline-line-regexp
  381. (concat "\\<\\(" org-deadline-string "\\).*")
  382. "Matches the DEADLINE keyword and the rest of the line.")
  383. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  384. "Matches the SCHEDULED keyword.")
  385. (defconst org-scheduled-time-regexp
  386. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  387. "Matches the SCHEDULED keyword together with a time stamp.")
  388. (defconst org-scheduled-time-hour-regexp
  389. (concat "\\<" org-scheduled-string
  390. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy \t.-]*\\)>")
  391. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  392. (defconst org-closed-time-regexp
  393. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  394. "Matches the CLOSED keyword together with a time stamp.")
  395. (defconst org-keyword-time-regexp
  396. (concat "\\<"
  397. (regexp-opt
  398. (list org-scheduled-string org-deadline-string org-closed-string
  399. org-clock-string)
  400. t)
  401. " *[[<]\\([^]>]+\\)[]>]")
  402. "Matches any of the 4 keywords, together with the time stamp.")
  403. (defconst org-keyword-time-not-clock-regexp
  404. (concat
  405. "\\<"
  406. (regexp-opt
  407. (list org-scheduled-string org-deadline-string org-closed-string) t)
  408. " *[[<]\\([^]>]+\\)[]>]")
  409. "Matches any of the 3 keywords, together with the time stamp.")
  410. (defconst org-maybe-keyword-time-regexp
  411. (concat "\\(\\<"
  412. (regexp-opt
  413. (list org-scheduled-string org-deadline-string org-closed-string
  414. org-clock-string)
  415. t)
  416. "\\)?"
  417. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  418. "\\|"
  419. "<%%([^\r\n>]*>\\)")
  420. "Matches a timestamp, possibly preceded by a keyword.")
  421. (defconst org-all-time-keywords
  422. (mapcar (lambda (w) (substring w 0 -1))
  423. (list org-scheduled-string org-deadline-string
  424. org-clock-string org-closed-string))
  425. "List of time keywords.")
  426. ;;;; Drawer
  427. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  428. "Matches first or last line of a hidden block.
  429. Group 1 contains drawer's name or \"END\".")
  430. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  431. "Regular expression matching the first line of a property drawer.")
  432. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  433. "Regular expression matching the last line of a property drawer.")
  434. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  435. "Regular expression matching the first line of a clock drawer.")
  436. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  437. "Regular expression matching the last line of a clock drawer.")
  438. (defconst org-property-drawer-re
  439. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  440. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  441. "[ \t]*:END:[ \t]*$")
  442. "Matches an entire property drawer.")
  443. (defconst org-clock-drawer-re
  444. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  445. org-clock-drawer-end-re "\\)\n?")
  446. "Matches an entire clock drawer.")
  447. ;;;; Headline
  448. (defconst org-heading-keyword-regexp-format
  449. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  450. "Printf format for a regexp matching a headline with some keyword.
  451. This regexp will match the headline of any node which has the
  452. exact keyword that is put into the format. The keyword isn't in
  453. any group by default, but the stars and the body are.")
  454. (defconst org-heading-keyword-maybe-regexp-format
  455. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  456. "Printf format for a regexp matching a headline, possibly with some keyword.
  457. This regexp can match any headline with the specified keyword, or
  458. without a keyword. The keyword isn't in any group by default,
  459. but the stars and the body are.")
  460. (defconst org-archive-tag "ARCHIVE"
  461. "The tag that marks a subtree as archived.
  462. An archived subtree does not open during visibility cycling, and does
  463. not contribute to the agenda listings.")
  464. (defconst org-tag-re "[[:alnum:]_@#%]+"
  465. "Regexp matching a single tag.")
  466. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  467. "Regexp matching the tag group at the end of a line, with leading spaces.
  468. Tags are stored in match group 1. Match group 2 stores the tags
  469. without the enclosing colons.")
  470. (defconst org-tag-line-re
  471. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  472. "Regexp matching tags in a headline.
  473. Tags are stored in match group 1. Match group 2 stores the tags
  474. without the enclosing colons.")
  475. (eval-and-compile
  476. (defconst org-comment-string "COMMENT"
  477. "Entries starting with this keyword will never be exported.
  478. \\<org-mode-map>
  479. An entry can be toggled between COMMENT and normal with
  480. `\\[org-toggle-comment]'."))
  481. ;;;; LaTeX Environments and Fragments
  482. (defconst org-latex-regexps
  483. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  484. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  485. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  486. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  487. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  488. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  489. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  490. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  491. "Regular expressions for matching embedded LaTeX.")
  492. ;;;; Node Property
  493. (defconst org-effort-property "Effort"
  494. "The property that is being used to keep track of effort estimates.
  495. Effort estimates given in this property need to have the format H:MM.")
  496. ;;;; Timestamp
  497. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  498. "Regular expression for fast time stamp matching.")
  499. (defconst org-ts-regexp-inactive
  500. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  501. "Regular expression for fast inactive time stamp matching.")
  502. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  503. "Regular expression for fast time stamp matching.")
  504. (defconst org-ts-regexp0
  505. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  506. "Regular expression matching time strings for analysis.
  507. This one does not require the space after the date, so it can be used
  508. on a string that terminates immediately after the date.")
  509. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  510. "Regular expression matching time strings for analysis.")
  511. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  512. "Regular expression matching time stamps, with groups.")
  513. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  514. "Regular expression matching time stamps (also [..]), with groups.")
  515. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  516. "Regular expression matching a time stamp range.")
  517. (defconst org-tr-regexp-both
  518. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  519. "Regular expression matching a time stamp range.")
  520. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  521. org-ts-regexp "\\)?")
  522. "Regular expression matching a time stamp or time stamp range.")
  523. (defconst org-tsr-regexp-both
  524. (concat org-ts-regexp-both "\\(--?-?"
  525. org-ts-regexp-both "\\)?")
  526. "Regular expression matching a time stamp or time stamp range.
  527. The time stamps may be either active or inactive.")
  528. (defconst org-repeat-re
  529. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  530. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  531. "Regular expression for specifying repeated events.
  532. After a match, group 1 contains the repeat expression.")
  533. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  534. "Formats for `format-time-string' which are used for time stamps.")
  535. ;;; The custom variables
  536. (defgroup org nil
  537. "Outline-based notes management and organizer."
  538. :tag "Org"
  539. :group 'outlines
  540. :group 'calendar)
  541. (defcustom org-mode-hook nil
  542. "Mode hook for Org mode, run after the mode was turned on."
  543. :group 'org
  544. :type 'hook)
  545. (defcustom org-load-hook nil
  546. "Hook that is run after org.el has been loaded."
  547. :group 'org
  548. :type 'hook)
  549. (defcustom org-log-buffer-setup-hook nil
  550. "Hook that is run after an Org log buffer is created."
  551. :group 'org
  552. :version "24.1"
  553. :type 'hook)
  554. (defvar org-modules) ; defined below
  555. (defvar org-modules-loaded nil
  556. "Have the modules been loaded already?")
  557. (defun org-load-modules-maybe (&optional force)
  558. "Load all extensions listed in `org-modules'."
  559. (when (or force (not org-modules-loaded))
  560. (dolist (ext org-modules)
  561. (condition-case nil (require ext)
  562. (error (message "Problems while trying to load feature `%s'" ext))))
  563. (setq org-modules-loaded t)))
  564. (defun org-set-modules (var value)
  565. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  566. (set var value)
  567. (when (featurep 'org)
  568. (org-load-modules-maybe 'force)
  569. (org-element-cache-reset 'all)))
  570. (defcustom org-modules '(ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  571. "Modules that should always be loaded together with org.el.
  572. If a description starts with <C>, the file is not part of Emacs
  573. and loading it will require that you have downloaded and properly
  574. installed the Org mode distribution.
  575. You can also use this system to load external packages (i.e. neither Org
  576. core modules, nor modules from the CONTRIB directory). Just add symbols
  577. to the end of the list. If the package is called org-xyz.el, then you need
  578. to add the symbol `xyz', and the package must have a call to:
  579. (provide \\='org-xyz)
  580. For export specific modules, see also `org-export-backends'."
  581. :group 'org
  582. :set 'org-set-modules
  583. :version "26.1"
  584. :package-version '(Org . "9.2")
  585. :type
  586. '(set :greedy t
  587. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  588. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  589. (const :tag " crypt: Encryption of subtrees" org-crypt)
  590. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  591. (const :tag " docview: Links to Docview buffers" ol-docview)
  592. (const :tag " eww: Store link to URL of Eww" ol-eww)
  593. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  594. (const :tag " habit: Track your consistency with habits" org-habit)
  595. (const :tag " id: Global IDs for identifying entries" org-id)
  596. (const :tag " info: Links to Info nodes" ol-info)
  597. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  598. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  599. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  600. (const :tag " mouse: Additional mouse support" org-mouse)
  601. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  602. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  603. (const :tag " tempo: Fast completion for structures" org-tempo)
  604. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  605. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  606. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  607. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  608. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  609. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  610. (const :tag "C collector: Collect properties into tables" org-collector)
  611. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  612. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  613. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  614. (const :tag "C eval: Include command output as text" org-eval)
  615. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  616. (const :tag "C git-link: Links to specific file version" ol-git-link)
  617. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  618. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  619. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  620. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  621. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  622. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  623. (const :tag "C man: Links to man pages in Org mode" ol-man)
  624. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  625. (const :tag "C notify: Notifications for Org mode" org-notify)
  626. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  627. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  628. (const :tag "C registry: A registry for Org links" org-registry)
  629. (const :tag "C screen: Visit screen sessions through links" org-screen)
  630. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  631. (const :tag "C secretary: Team management with Org" org-secretary)
  632. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  633. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  634. (const :tag "C track: Keep up with Org mode development" org-track)
  635. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  636. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  637. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  638. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  639. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  640. (defvar org-export-registered-backends) ; From ox.el.
  641. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  642. (declare-function org-export-backend-name "ox" (backend) t)
  643. (defcustom org-export-backends '(ascii html icalendar latex odt)
  644. "List of export back-ends that should be always available.
  645. If a description starts with <C>, the file is not part of Emacs
  646. and loading it will require that you have downloaded and properly
  647. installed the Org mode distribution.
  648. Unlike to `org-modules', libraries in this list will not be
  649. loaded along with Org, but only once the export framework is
  650. needed.
  651. This variable needs to be set before org.el is loaded. If you
  652. need to make a change while Emacs is running, use the customize
  653. interface or run the following code, where VAL stands for the new
  654. value of the variable, after updating it:
  655. (progn
  656. (setq org-export-registered-backends
  657. (cl-remove-if-not
  658. (lambda (backend)
  659. (let ((name (org-export-backend-name backend)))
  660. (or (memq name val)
  661. (catch \\='parentp
  662. (dolist (b val)
  663. (and (org-export-derived-backend-p b name)
  664. (throw \\='parentp t)))))))
  665. org-export-registered-backends))
  666. (let ((new-list (mapcar #\\='org-export-backend-name
  667. org-export-registered-backends)))
  668. (dolist (backend val)
  669. (cond
  670. ((not (load (format \"ox-%s\" backend) t t))
  671. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  672. backend))
  673. ((not (memq backend new-list)) (push backend new-list))))
  674. (set-default \\='org-export-backends new-list)))
  675. Adding a back-end to this list will also pull the back-end it
  676. depends on, if any."
  677. :group 'org
  678. :group 'org-export
  679. :version "26.1"
  680. :package-version '(Org . "9.0")
  681. :initialize 'custom-initialize-set
  682. :set (lambda (var val)
  683. (if (not (featurep 'ox)) (set-default var val)
  684. ;; Any back-end not required anymore (not present in VAL and not
  685. ;; a parent of any back-end in the new value) is removed from the
  686. ;; list of registered back-ends.
  687. (setq org-export-registered-backends
  688. (cl-remove-if-not
  689. (lambda (backend)
  690. (let ((name (org-export-backend-name backend)))
  691. (or (memq name val)
  692. (catch 'parentp
  693. (dolist (b val)
  694. (and (org-export-derived-backend-p b name)
  695. (throw 'parentp t)))))))
  696. org-export-registered-backends))
  697. ;; Now build NEW-LIST of both new back-ends and required
  698. ;; parents.
  699. (let ((new-list (mapcar #'org-export-backend-name
  700. org-export-registered-backends)))
  701. (dolist (backend val)
  702. (cond
  703. ((not (load (format "ox-%s" backend) t t))
  704. (message "Problems while trying to load export back-end `%s'"
  705. backend))
  706. ((not (memq backend new-list)) (push backend new-list))))
  707. ;; Set VAR to that list with fixed dependencies.
  708. (set-default var new-list))))
  709. :type '(set :greedy t
  710. (const :tag " ascii Export buffer to ASCII format" ascii)
  711. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  712. (const :tag " html Export buffer to HTML format" html)
  713. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  714. (const :tag " latex Export buffer to LaTeX format" latex)
  715. (const :tag " man Export buffer to MAN format" man)
  716. (const :tag " md Export buffer to Markdown format" md)
  717. (const :tag " odt Export buffer to ODT format" odt)
  718. (const :tag " org Export buffer to Org format" org)
  719. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  720. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  721. (const :tag "C deck Export buffer to deck.js presentations" deck)
  722. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  723. (const :tag "C groff Export buffer to Groff format" groff)
  724. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  725. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  726. (const :tag "C s5 Export buffer to s5 presentations" s5)
  727. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  728. (eval-after-load 'ox
  729. '(dolist (backend org-export-backends)
  730. (condition-case nil (require (intern (format "ox-%s" backend)))
  731. (error (message "Problems while trying to load export back-end `%s'"
  732. backend)))))
  733. (defcustom org-support-shift-select nil
  734. "Non-nil means make shift-cursor commands select text when possible.
  735. \\<org-mode-map>
  736. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  737. start selecting a region, or enlarge regions started in this way.
  738. In Org mode, in special contexts, these same keys are used for
  739. other purposes, important enough to compete with shift selection.
  740. Org tries to balance these needs by supporting `shift-select-mode'
  741. outside these special contexts, under control of this variable.
  742. The default of this variable is nil, to avoid confusing behavior. Shifted
  743. cursor keys will then execute Org commands in the following contexts:
  744. - on a headline, changing TODO state (left/right) and priority (up/down)
  745. - on a time stamp, changing the time
  746. - in a plain list item, changing the bullet type
  747. - in a property definition line, switching between allowed values
  748. - in the BEGIN line of a clock table (changing the time block).
  749. Outside these contexts, the commands will throw an error.
  750. When this variable is t and the cursor is not in a special
  751. context, Org mode will support shift-selection for making and
  752. enlarging regions. To make this more effective, the bullet
  753. cycling will no longer happen anywhere in an item line, but only
  754. if the cursor is exactly on the bullet.
  755. If you set this variable to the symbol `always', then the keys
  756. will not be special in headlines, property lines, and item lines,
  757. to make shift selection work there as well. If this is what you
  758. want, you can use the following alternative commands:
  759. `\\[org-todo]' and `\\[org-priority]' \
  760. to change TODO state and priority,
  761. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  762. can be used to switch TODO sets,
  763. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  764. and properties can be edited by hand or in column view.
  765. However, when the cursor is on a timestamp, shift-cursor commands
  766. will still edit the time stamp - this is just too good to give up."
  767. :group 'org
  768. :type '(choice
  769. (const :tag "Never" nil)
  770. (const :tag "When outside special context" t)
  771. (const :tag "Everywhere except timestamps" always)))
  772. (defcustom org-loop-over-headlines-in-active-region nil
  773. "Shall some commands act upon headlines in the active region?
  774. When set to t, some commands will be performed in all headlines
  775. within the active region.
  776. When set to `start-level', some commands will be performed in all
  777. headlines within the active region, provided that these headlines
  778. are of the same level than the first one.
  779. When set to a string, those commands will be performed on the
  780. matching headlines within the active region. Such string must be
  781. a tags/property/todo match as it is used in the agenda tags view.
  782. The list of commands is: `org-schedule', `org-deadline',
  783. `org-todo', `org-set-tags-command', `org-archive-subtree',
  784. `org-archive-set-tag', `org-toggle-archive-tag' and
  785. `org-archive-to-archive-sibling'. The archiving commands skip
  786. already archived entries."
  787. :type '(choice (const :tag "Don't loop" nil)
  788. (const :tag "All headlines in active region" t)
  789. (const :tag "In active region, headlines at the same level than the first one" start-level)
  790. (string :tag "Tags/Property/Todo matcher"))
  791. :version "24.1"
  792. :group 'org-todo
  793. :group 'org-archive)
  794. (defcustom org-startup-folded t
  795. "Non-nil means entering Org mode will switch to OVERVIEW.
  796. This can also be configured on a per-file basis by adding one of
  797. the following lines anywhere in the buffer:
  798. #+STARTUP: fold (or `overview', this is equivalent)
  799. #+STARTUP: nofold (or `showall', this is equivalent)
  800. #+STARTUP: content
  801. #+STARTUP: showeverything
  802. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  803. to ignore this option when Org opens agenda files for the first
  804. time."
  805. :group 'org-startup
  806. :type '(choice
  807. (const :tag "nofold: show all" nil)
  808. (const :tag "fold: overview" t)
  809. (const :tag "content: all headlines" content)
  810. (const :tag "show everything, even drawers" showeverything)))
  811. (defcustom org-startup-truncated t
  812. "Non-nil means entering Org mode will set `truncate-lines'.
  813. This is useful since some lines containing links can be very long and
  814. uninteresting. Also tables look terrible when wrapped.
  815. The variable `org-startup-truncated' allows to configure
  816. truncation for Org mode different to the other modes that use the
  817. variable `truncate-lines' and as a shortcut instead of putting
  818. the variable `truncate-lines' into the `org-mode-hook'. If one
  819. wants to configure truncation for Org mode not statically but
  820. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  821. the variable `truncate-lines' has to be used because in such a
  822. case it is too late to set the variable `org-startup-truncated'."
  823. :group 'org-startup
  824. :type 'boolean)
  825. (defcustom org-startup-indented nil
  826. "Non-nil means turn on `org-indent-mode' on startup.
  827. This can also be configured on a per-file basis by adding one of
  828. the following lines anywhere in the buffer:
  829. #+STARTUP: indent
  830. #+STARTUP: noindent"
  831. :group 'org-structure
  832. :type '(choice
  833. (const :tag "Not" nil)
  834. (const :tag "Globally (slow on startup in large files)" t)))
  835. (defcustom org-use-sub-superscripts t
  836. "Non-nil means interpret \"_\" and \"^\" for display.
  837. If you want to control how Org exports those characters, see
  838. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  839. used to be an alias for `org-export-with-sub-superscripts' in
  840. Org <8.0, it is not anymore.
  841. When this option is turned on, you can use TeX-like syntax for
  842. sub- and superscripts within the buffer. Several characters after
  843. \"_\" or \"^\" will be considered as a single item - so grouping
  844. with {} is normally not needed. For example, the following things
  845. will be parsed as single sub- or superscripts:
  846. 10^24 or 10^tau several digits will be considered 1 item.
  847. 10^-12 or 10^-tau a leading sign with digits or a word
  848. x^2-y^3 will be read as x^2 - y^3, because items are
  849. terminated by almost any nonword/nondigit char.
  850. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  851. Still, ambiguity is possible. So when in doubt, use {} to enclose
  852. the sub/superscript. If you set this variable to the symbol `{}',
  853. the braces are *required* in order to trigger interpretations as
  854. sub/superscript. This can be helpful in documents that need \"_\"
  855. frequently in plain text."
  856. :group 'org-startup
  857. :version "24.4"
  858. :package-version '(Org . "8.0")
  859. :type '(choice
  860. (const :tag "Always interpret" t)
  861. (const :tag "Only with braces" {})
  862. (const :tag "Never interpret" nil)))
  863. (defcustom org-startup-with-beamer-mode nil
  864. "Non-nil means turn on `org-beamer-mode' on startup.
  865. This can also be configured on a per-file basis by adding one of
  866. the following lines anywhere in the buffer:
  867. #+STARTUP: beamer"
  868. :group 'org-startup
  869. :version "24.1"
  870. :type 'boolean)
  871. (defcustom org-startup-align-all-tables nil
  872. "Non-nil means align all tables when visiting a file.
  873. This can also be configured on a per-file basis by adding one of
  874. the following lines anywhere in the buffer:
  875. #+STARTUP: align
  876. #+STARTUP: noalign"
  877. :group 'org-startup
  878. :type 'boolean)
  879. (defcustom org-startup-shrink-all-tables nil
  880. "Non-nil means shrink all table columns with a width cookie.
  881. This can also be configured on a per-file basis by adding one of
  882. the following lines anywhere in the buffer:
  883. #+STARTUP: shrink"
  884. :group 'org-startup
  885. :type 'boolean
  886. :version "27.1"
  887. :package-version '(Org . "9.2")
  888. :safe #'booleanp)
  889. (defcustom org-startup-with-inline-images nil
  890. "Non-nil means show inline images when loading a new Org file.
  891. This can also be configured on a per-file basis by adding one of
  892. the following lines anywhere in the buffer:
  893. #+STARTUP: inlineimages
  894. #+STARTUP: noinlineimages"
  895. :group 'org-startup
  896. :version "24.1"
  897. :type 'boolean)
  898. (defcustom org-startup-with-latex-preview nil
  899. "Non-nil means preview LaTeX fragments when loading a new Org file.
  900. This can also be configured on a per-file basis by adding one of
  901. the following lines anywhere in the buffer:
  902. #+STARTUP: latexpreview
  903. #+STARTUP: nolatexpreview"
  904. :group 'org-startup
  905. :version "24.4"
  906. :package-version '(Org . "8.0")
  907. :type 'boolean)
  908. (defcustom org-insert-mode-line-in-empty-file nil
  909. "Non-nil means insert the first line setting Org mode in empty files.
  910. When the function `org-mode' is called interactively in an empty file, this
  911. normally means that the file name does not automatically trigger Org mode.
  912. To ensure that the file will always be in Org mode in the future, a
  913. line enforcing Org mode will be inserted into the buffer, if this option
  914. has been set."
  915. :group 'org-startup
  916. :type 'boolean)
  917. (defcustom org-ellipsis nil
  918. "The ellipsis to use in the Org mode outline.
  919. When nil, just use the standard three dots. When a non-empty string,
  920. use that string instead.
  921. The change affects only Org mode (which will then use its own display table).
  922. Changing this requires executing `\\[org-mode]' in a buffer to become
  923. effective."
  924. :group 'org-startup
  925. :type '(choice (const :tag "Default" nil)
  926. (string :tag "String" :value "...#"))
  927. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  928. (defvar org-display-table nil
  929. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  930. (defgroup org-keywords nil
  931. "Keywords in Org mode."
  932. :tag "Org Keywords"
  933. :group 'org)
  934. (defcustom org-closed-keep-when-no-todo nil
  935. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  936. :group 'org-todo
  937. :group 'org-keywords
  938. :version "24.4"
  939. :package-version '(Org . "8.0")
  940. :type 'boolean)
  941. (defgroup org-structure nil
  942. "Options concerning the general structure of Org files."
  943. :tag "Org Structure"
  944. :group 'org)
  945. (defgroup org-reveal-location nil
  946. "Options about how to make context of a location visible."
  947. :tag "Org Reveal Location"
  948. :group 'org-structure)
  949. (defcustom org-show-context-detail '((agenda . local)
  950. (bookmark-jump . lineage)
  951. (isearch . lineage)
  952. (default . ancestors))
  953. "Alist between context and visibility span when revealing a location.
  954. \\<org-mode-map>Some actions may move point into invisible
  955. locations. As a consequence, Org always expose a neighborhood
  956. around point. How much is shown depends on the initial action,
  957. or context. Valid contexts are
  958. agenda when exposing an entry from the agenda
  959. org-goto when using the command `org-goto' (`\\[org-goto]')
  960. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  961. tags-tree when constructing a sparse tree based on tags matches
  962. link-search when exposing search matches associated with a link
  963. mark-goto when exposing the jump goal of a mark
  964. bookmark-jump when exposing a bookmark location
  965. isearch when exiting from an incremental search
  966. default default for all contexts not set explicitly
  967. Allowed visibility spans are
  968. minimal show current headline; if point is not on headline,
  969. also show entry
  970. local show current headline, entry and next headline
  971. ancestors show current headline and its direct ancestors; if
  972. point is not on headline, also show entry
  973. lineage show current headline, its direct ancestors and all
  974. their children; if point is not on headline, also show
  975. entry and first child
  976. tree show current headline, its direct ancestors and all
  977. their children; if point is not on headline, also show
  978. entry and all children
  979. canonical show current headline, its direct ancestors along with
  980. their entries and children; if point is not located on
  981. the headline, also show current entry and all children
  982. As special cases, a nil or t value means show all contexts in
  983. `minimal' or `canonical' view, respectively.
  984. Some views can make displayed information very compact, but also
  985. make it harder to edit the location of the match. In such
  986. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  987. more context."
  988. :group 'org-reveal-location
  989. :version "26.1"
  990. :package-version '(Org . "9.0")
  991. :type '(choice
  992. (const :tag "Canonical" t)
  993. (const :tag "Minimal" nil)
  994. (repeat :greedy t :tag "Individual contexts"
  995. (cons
  996. (choice :tag "Context"
  997. (const agenda)
  998. (const org-goto)
  999. (const occur-tree)
  1000. (const tags-tree)
  1001. (const link-search)
  1002. (const mark-goto)
  1003. (const bookmark-jump)
  1004. (const isearch)
  1005. (const default))
  1006. (choice :tag "Detail level"
  1007. (const minimal)
  1008. (const local)
  1009. (const ancestors)
  1010. (const lineage)
  1011. (const tree)
  1012. (const canonical))))))
  1013. (defcustom org-indirect-buffer-display 'other-window
  1014. "How should indirect tree buffers be displayed?
  1015. This applies to indirect buffers created with the commands
  1016. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1017. Valid values are:
  1018. current-window Display in the current window
  1019. other-window Just display in another window.
  1020. dedicated-frame Create one new frame, and re-use it each time.
  1021. new-frame Make a new frame each time. Note that in this case
  1022. previously-made indirect buffers are kept, and you need to
  1023. kill these buffers yourself."
  1024. :group 'org-structure
  1025. :group 'org-agenda-windows
  1026. :type '(choice
  1027. (const :tag "In current window" current-window)
  1028. (const :tag "In current frame, other window" other-window)
  1029. (const :tag "Each time a new frame" new-frame)
  1030. (const :tag "One dedicated frame" dedicated-frame)))
  1031. (defconst org-file-apps-gnu
  1032. '((remote . emacs)
  1033. (system . mailcap)
  1034. (t . mailcap))
  1035. "Default file applications on a UNIX or GNU/Linux system.
  1036. See `org-file-apps'.")
  1037. (defconst org-file-apps-macos
  1038. '((remote . emacs)
  1039. (system . "open %s")
  1040. ("ps.gz" . "gv %s")
  1041. ("eps.gz" . "gv %s")
  1042. ("dvi" . "xdvi %s")
  1043. ("fig" . "xfig %s")
  1044. (t . "open %s"))
  1045. "Default file applications on a macOS system.
  1046. The system \"open\" is known as a default, but we use X11 applications
  1047. for some files for which the OS does not have a good default.
  1048. See `org-file-apps'.")
  1049. (defconst org-file-apps-windowsnt
  1050. (list '(remote . emacs)
  1051. (cons 'system (lambda (file _path)
  1052. (with-no-warnings (w32-shell-execute "open" file))))
  1053. (cons t (lambda (file _path)
  1054. (with-no-warnings (w32-shell-execute "open" file)))))
  1055. "Default file applications on a Windows NT system.
  1056. The system \"open\" is used for most files.
  1057. See `org-file-apps'.")
  1058. (defcustom org-file-apps
  1059. '((auto-mode . emacs)
  1060. (directory . emacs)
  1061. ("\\.mm\\'" . default)
  1062. ("\\.x?html?\\'" . default)
  1063. ("\\.pdf\\'" . default))
  1064. "Applications for opening `file:path' items in a document.
  1065. \\<org-mode-map>
  1066. Org mode uses system defaults for different file types, but you
  1067. can use this variable to set the application for a given file
  1068. extension. The entries in this list are cons cells where the car
  1069. identifies files and the cdr the corresponding command.
  1070. Possible values for the file identifier are:
  1071. \"string\" A string as a file identifier can be interpreted in different
  1072. ways, depending on its contents:
  1073. - Alphanumeric characters only:
  1074. Match links with this file extension.
  1075. Example: (\"pdf\" . \"evince %s\")
  1076. to open PDFs with evince.
  1077. - Regular expression: Match links where the
  1078. filename matches the regexp. If you want to
  1079. use groups here, use shy groups.
  1080. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1081. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1082. to open *.html and *.xhtml with firefox.
  1083. - Regular expression which contains (non-shy) groups:
  1084. Match links where the whole link, including \"::\", and
  1085. anything after that, matches the regexp.
  1086. In a custom command string, %1, %2, etc. are replaced with
  1087. the parts of the link that were matched by the groups.
  1088. For backwards compatibility, if a command string is given
  1089. that does not use any of the group matches, this case is
  1090. handled identically to the second one (i.e. match against
  1091. file name only).
  1092. In a custom function, you can access the group matches with
  1093. (match-string n link).
  1094. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1095. \"evince -p %1 %s\")
  1096. to open [[file:document.pdf::5]] with evince at page 5.
  1097. `directory' Matches a directory
  1098. `remote' Matches a remote file, accessible through tramp or efs.
  1099. Remote files most likely should be visited through Emacs
  1100. because external applications cannot handle such paths.
  1101. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1102. so all files Emacs knows how to handle. Using this with
  1103. command `emacs' will open most files in Emacs. Beware that this
  1104. will also open html files inside Emacs, unless you add
  1105. (\"html\" . default) to the list as well.
  1106. `system' The system command to open files, like `open' on Windows
  1107. and macOS, and mailcap under GNU/Linux. This is the command
  1108. that will be selected if you call `org-open-at-point' with a
  1109. double prefix argument (`\\[universal-argument] \
  1110. \\[universal-argument] \\[org-open-at-point]').
  1111. t Default for files not matched by any of the other options.
  1112. Possible values for the command are:
  1113. `emacs' The file will be visited by the current Emacs process.
  1114. `default' Use the default application for this file type, which is the
  1115. association for t in the list, most likely in the system-specific
  1116. part. This can be used to overrule an unwanted setting in the
  1117. system-specific variable.
  1118. `system' Use the system command for opening files, like \"open\".
  1119. This command is specified by the entry whose car is `system'.
  1120. Most likely, the system-specific version of this variable
  1121. does define this command, but you can overrule/replace it
  1122. here.
  1123. `mailcap' Use command specified in the mailcaps.
  1124. string A command to be executed by a shell; %s will be replaced
  1125. by the path to the file.
  1126. function A Lisp function, which will be called with two arguments:
  1127. the file path and the original link string, without the
  1128. \"file:\" prefix.
  1129. For more examples, see the system specific constants
  1130. `org-file-apps-macos'
  1131. `org-file-apps-windowsnt'
  1132. `org-file-apps-gnu'."
  1133. :group 'org
  1134. :package-version '(Org . "9.4")
  1135. :type '(repeat
  1136. (cons (choice :value ""
  1137. (string :tag "Extension")
  1138. (const :tag "System command to open files" system)
  1139. (const :tag "Default for unrecognized files" t)
  1140. (const :tag "Remote file" remote)
  1141. (const :tag "Links to a directory" directory)
  1142. (const :tag "Any files that have Emacs modes"
  1143. auto-mode))
  1144. (choice :value ""
  1145. (const :tag "Visit with Emacs" emacs)
  1146. (const :tag "Use default" default)
  1147. (const :tag "Use the system command" system)
  1148. (string :tag "Command")
  1149. (function :tag "Function")))))
  1150. (defcustom org-open-non-existing-files nil
  1151. "Non-nil means `org-open-file' opens non-existing files.
  1152. When nil, an error is thrown.
  1153. This variable applies only to external applications because they
  1154. might choke on non-existing files. If the link is to a file that
  1155. will be opened in Emacs, the variable is ignored."
  1156. :group 'org
  1157. :type 'boolean
  1158. :safe #'booleanp)
  1159. (defcustom org-open-directory-means-index-dot-org nil
  1160. "When non-nil a link to a directory really means to \"index.org\".
  1161. When nil, following a directory link runs Dired or opens
  1162. a finder/explorer window on that directory."
  1163. :group 'org
  1164. :type 'boolean
  1165. :safe #'booleanp)
  1166. (defcustom org-bookmark-names-plist
  1167. '(:last-capture "org-capture-last-stored"
  1168. :last-refile "org-refile-last-stored"
  1169. :last-capture-marker "org-capture-last-stored-marker")
  1170. "Names for bookmarks automatically set by some Org commands.
  1171. This can provide strings as names for a number of bookmarks Org sets
  1172. automatically. The following keys are currently implemented:
  1173. :last-capture
  1174. :last-capture-marker
  1175. :last-refile
  1176. When a key does not show up in the property list, the corresponding bookmark
  1177. is not set."
  1178. :group 'org-structure
  1179. :type 'plist)
  1180. (defgroup org-cycle nil
  1181. "Options concerning visibility cycling in Org mode."
  1182. :tag "Org Cycle"
  1183. :group 'org-structure)
  1184. (defcustom org-cycle-skip-children-state-if-no-children t
  1185. "Non-nil means skip CHILDREN state in entries that don't have any."
  1186. :group 'org-cycle
  1187. :type 'boolean)
  1188. (defcustom org-cycle-max-level nil
  1189. "Maximum level which should still be subject to visibility cycling.
  1190. Levels higher than this will, for cycling, be treated as text, not a headline.
  1191. When `org-odd-levels-only' is set, a value of N in this variable actually
  1192. means 2N-1 stars as the limiting headline.
  1193. When nil, cycle all levels.
  1194. Note that the limiting level of cycling is also influenced by
  1195. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1196. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1197. than its value."
  1198. :group 'org-cycle
  1199. :type '(choice
  1200. (const :tag "No limit" nil)
  1201. (integer :tag "Maximum level")))
  1202. (defcustom org-hide-block-startup nil
  1203. "Non-nil means entering Org mode will fold all blocks.
  1204. This can also be set in on a per-file basis with
  1205. #+STARTUP: hideblocks
  1206. #+STARTUP: showblocks"
  1207. :group 'org-startup
  1208. :group 'org-cycle
  1209. :type 'boolean)
  1210. (defcustom org-cycle-global-at-bob nil
  1211. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1212. This makes it possible to do global cycling without having to use `S-TAB'
  1213. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1214. line of the buffer
  1215. must not be a headline -- it may be empty or some other text.
  1216. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1217. sure the cursor stays at the beginning of the buffer.
  1218. When this option is nil, don't do anything special at the beginning of
  1219. the buffer."
  1220. :group 'org-cycle
  1221. :type 'boolean)
  1222. (defcustom org-cycle-level-after-item/entry-creation t
  1223. "Non-nil means cycle entry level or item indentation in new empty entries.
  1224. When the cursor is at the end of an empty headline, i.e., with only stars
  1225. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1226. and then all possible ancestor states, before returning to the original state.
  1227. This makes data entry extremely fast: M-RET to create a new headline,
  1228. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1229. When the cursor is at the end of an empty plain list item, one TAB will
  1230. make it a subitem, two or more tabs will back up to make this an item
  1231. higher up in the item hierarchy."
  1232. :group 'org-cycle
  1233. :type 'boolean)
  1234. (defcustom org-cycle-emulate-tab t
  1235. "Where should `org-cycle' emulate TAB.
  1236. nil Never
  1237. white Only in completely white lines
  1238. whitestart Only at the beginning of lines, before the first non-white char
  1239. t Everywhere except in headlines
  1240. exc-hl-bol Everywhere except at the start of a headline
  1241. If TAB is used in a place where it does not emulate TAB, the current subtree
  1242. visibility is cycled."
  1243. :group 'org-cycle
  1244. :type '(choice (const :tag "Never" nil)
  1245. (const :tag "Only in completely white lines" white)
  1246. (const :tag "Before first char in a line" whitestart)
  1247. (const :tag "Everywhere except in headlines" t)
  1248. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1249. (defcustom org-cycle-separator-lines 2
  1250. "Number of empty lines needed to keep an empty line between collapsed trees.
  1251. If you leave an empty line between the end of a subtree and the following
  1252. headline, this empty line is hidden when the subtree is folded.
  1253. Org mode will leave (exactly) one empty line visible if the number of
  1254. empty lines is equal or larger to the number given in this variable.
  1255. So the default 2 means at least 2 empty lines after the end of a subtree
  1256. are needed to produce free space between a collapsed subtree and the
  1257. following headline.
  1258. If the number is negative, and the number of empty lines is at least -N,
  1259. all empty lines are shown.
  1260. Special case: when 0, never leave empty lines in collapsed view."
  1261. :group 'org-cycle
  1262. :type 'integer)
  1263. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1264. (defcustom org-pre-cycle-hook nil
  1265. "Hook that is run before visibility cycling is happening.
  1266. The function(s) in this hook must accept a single argument which indicates
  1267. the new state that will be set right after running this hook. The
  1268. argument is a symbol. Before a global state change, it can have the values
  1269. `overview', `content', or `all'. Before a local state change, it can have
  1270. the values `folded', `children', or `subtree'."
  1271. :group 'org-cycle
  1272. :type 'hook)
  1273. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1274. org-cycle-show-empty-lines
  1275. org-optimize-window-after-visibility-change)
  1276. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1277. The function(s) in this hook must accept a single argument which indicates
  1278. the new state that was set by the most recent `org-cycle' command. The
  1279. argument is a symbol. After a global state change, it can have the values
  1280. `overview', `contents', or `all'. After a local state change, it can have
  1281. the values `folded', `children', or `subtree'."
  1282. :group 'org-cycle
  1283. :type 'hook
  1284. :version "26.1"
  1285. :package-version '(Org . "8.3"))
  1286. (defgroup org-edit-structure nil
  1287. "Options concerning structure editing in Org mode."
  1288. :tag "Org Edit Structure"
  1289. :group 'org-structure)
  1290. (defcustom org-odd-levels-only nil
  1291. "Non-nil means skip even levels and only use odd levels for the outline.
  1292. This has the effect that two stars are being added/taken away in
  1293. promotion/demotion commands. It also influences how levels are
  1294. handled by the exporters.
  1295. Changing it requires restart of `font-lock-mode' to become effective
  1296. for fontification also in regions already fontified.
  1297. You may also set this on a per-file basis by adding one of the following
  1298. lines to the buffer:
  1299. #+STARTUP: odd
  1300. #+STARTUP: oddeven"
  1301. :group 'org-edit-structure
  1302. :group 'org-appearance
  1303. :type 'boolean)
  1304. (defcustom org-adapt-indentation t
  1305. "Non-nil means adapt indentation to outline node level.
  1306. When this variable is set, Org assumes that you write outlines by
  1307. indenting text in each node to align with the headline (after the
  1308. stars). The following issues are influenced by this variable:
  1309. - The indentation is increased by one space in a demotion
  1310. command, and decreased by one in a promotion command. However,
  1311. in the latter case, if shifting some line in the entry body
  1312. would alter document structure (e.g., insert a new headline),
  1313. indentation is not changed at all.
  1314. - Property drawers and planning information is inserted indented
  1315. when this variable is set. When nil, they will not be indented.
  1316. - TAB indents a line relative to current level. The lines below
  1317. a headline will be indented when this variable is set.
  1318. Note that this is all about true indentation, by adding and
  1319. removing space characters. See also \"org-indent.el\" which does
  1320. level-dependent indentation in a virtual way, i.e. at display
  1321. time in Emacs."
  1322. :group 'org-edit-structure
  1323. :type 'boolean
  1324. :safe #'booleanp)
  1325. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1326. (defcustom org-special-ctrl-a/e nil
  1327. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1328. When t, `C-a' will bring back the cursor to the beginning of the
  1329. headline text, i.e. after the stars and after a possible TODO
  1330. keyword. In an item, this will be the position after bullet and
  1331. check-box, if any. When the cursor is already at that position,
  1332. another `C-a' will bring it to the beginning of the line.
  1333. `C-e' will jump to the end of the headline, ignoring the presence
  1334. of tags in the headline. A second `C-e' will then jump to the
  1335. true end of the line, after any tags. This also means that, when
  1336. this variable is non-nil, `C-e' also will never jump beyond the
  1337. end of the heading of a folded section, i.e. not after the
  1338. ellipses.
  1339. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1340. normally, going to the true line boundary first. Only a directly
  1341. following, identical keypress will bring the cursor to the
  1342. special positions.
  1343. This may also be a cons cell where the behavior for `C-a' and
  1344. `C-e' is set separately."
  1345. :group 'org-edit-structure
  1346. :type '(choice
  1347. (const :tag "off" nil)
  1348. (const :tag "on: after stars/bullet and before tags first" t)
  1349. (const :tag "reversed: true line boundary first" reversed)
  1350. (cons :tag "Set C-a and C-e separately"
  1351. (choice :tag "Special C-a"
  1352. (const :tag "off" nil)
  1353. (const :tag "on: after stars/bullet first" t)
  1354. (const :tag "reversed: before stars/bullet first" reversed))
  1355. (choice :tag "Special C-e"
  1356. (const :tag "off" nil)
  1357. (const :tag "on: before tags first" t)
  1358. (const :tag "reversed: after tags first" reversed)))))
  1359. (defcustom org-special-ctrl-k nil
  1360. "Non-nil means `C-k' will behave specially in headlines.
  1361. When nil, `C-k' will call the default `kill-line' command.
  1362. When t, the following will happen while the cursor is in the headline:
  1363. - When the cursor is at the beginning of a headline, kill the entire
  1364. line and possible the folded subtree below the line.
  1365. - When in the middle of the headline text, kill the headline up to the tags.
  1366. - When after the headline text, kill the tags."
  1367. :group 'org-edit-structure
  1368. :type 'boolean)
  1369. (defcustom org-ctrl-k-protect-subtree nil
  1370. "Non-nil means, do not delete a hidden subtree with C-k.
  1371. When set to the symbol `error', simply throw an error when C-k is
  1372. used to kill (part-of) a headline that has hidden text behind it.
  1373. Any other non-nil value will result in a query to the user, if it is
  1374. OK to kill that hidden subtree. When nil, kill without remorse."
  1375. :group 'org-edit-structure
  1376. :version "24.1"
  1377. :type '(choice
  1378. (const :tag "Do not protect hidden subtrees" nil)
  1379. (const :tag "Protect hidden subtrees with a security query" t)
  1380. (const :tag "Never kill a hidden subtree with C-k" error)))
  1381. (defcustom org-special-ctrl-o t
  1382. "Non-nil means, make `C-o' insert a row in tables."
  1383. :group 'org-edit-structure
  1384. :type 'boolean)
  1385. (defcustom org-catch-invisible-edits nil
  1386. "Check if in invisible region before inserting or deleting a character.
  1387. Valid values are:
  1388. nil Do not check, so just do invisible edits.
  1389. error Throw an error and do nothing.
  1390. show Make point visible, and do the requested edit.
  1391. show-and-error Make point visible, then throw an error and abort the edit.
  1392. smart Make point visible, and do insertion/deletion if it is
  1393. adjacent to visible text and the change feels predictable.
  1394. Never delete a previously invisible character or add in the
  1395. middle or right after an invisible region. Basically, this
  1396. allows insertion and backward-delete right before ellipses.
  1397. FIXME: maybe in this case we should not even show?"
  1398. :group 'org-edit-structure
  1399. :version "24.1"
  1400. :type '(choice
  1401. (const :tag "Do not check" nil)
  1402. (const :tag "Throw error when trying to edit" error)
  1403. (const :tag "Unhide, but do not do the edit" show-and-error)
  1404. (const :tag "Show invisible part and do the edit" show)
  1405. (const :tag "Be smart and do the right thing" smart)))
  1406. (defcustom org-yank-folded-subtrees t
  1407. "Non-nil means when yanking subtrees, fold them.
  1408. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1409. it starts with a heading and all other headings in it are either children
  1410. or siblings, then fold all the subtrees. However, do this only if no
  1411. text after the yank would be swallowed into a folded tree by this action."
  1412. :group 'org-edit-structure
  1413. :type 'boolean)
  1414. (defcustom org-yank-adjusted-subtrees nil
  1415. "Non-nil means when yanking subtrees, adjust the level.
  1416. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1417. this function for details."
  1418. :group 'org-edit-structure
  1419. :type 'boolean)
  1420. (defcustom org-M-RET-may-split-line '((default . t))
  1421. "Non-nil means M-RET will split the line at the cursor position.
  1422. When nil, it will go to the end of the line before making a
  1423. new line.
  1424. You may also set this option in a different way for different
  1425. contexts. Valid contexts are:
  1426. headline when creating a new headline
  1427. item when creating a new item
  1428. table in a table field
  1429. default the value to be used for all contexts not explicitly
  1430. customized"
  1431. :group 'org-structure
  1432. :group 'org-table
  1433. :type '(choice
  1434. (const :tag "Always" t)
  1435. (const :tag "Never" nil)
  1436. (repeat :greedy t :tag "Individual contexts"
  1437. (cons
  1438. (choice :tag "Context"
  1439. (const headline)
  1440. (const item)
  1441. (const table)
  1442. (const default))
  1443. (boolean)))))
  1444. (defcustom org-insert-heading-respect-content nil
  1445. "Non-nil means insert new headings after the current subtree.
  1446. \\<org-mode-map>
  1447. When nil, the new heading is created directly after the current line.
  1448. The commands `\\[org-insert-heading-respect-content]' and \
  1449. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1450. for the duration of the command."
  1451. :group 'org-structure
  1452. :type 'boolean)
  1453. (defcustom org-blank-before-new-entry '((heading . auto)
  1454. (plain-list-item . auto))
  1455. "Should `org-insert-heading' leave a blank line before new heading/item?
  1456. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1457. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1458. which case Org will look at the surrounding headings/items and try to
  1459. make an intelligent decision whether to insert a blank line or not."
  1460. :group 'org-edit-structure
  1461. :type '(list
  1462. (cons (const heading)
  1463. (choice (const :tag "Never" nil)
  1464. (const :tag "Always" t)
  1465. (const :tag "Auto" auto)))
  1466. (cons (const plain-list-item)
  1467. (choice (const :tag "Never" nil)
  1468. (const :tag "Always" t)
  1469. (const :tag "Auto" auto)))))
  1470. (defcustom org-insert-heading-hook nil
  1471. "Hook being run after inserting a new heading."
  1472. :group 'org-edit-structure
  1473. :type 'hook)
  1474. (defgroup org-sparse-trees nil
  1475. "Options concerning sparse trees in Org mode."
  1476. :tag "Org Sparse Trees"
  1477. :group 'org-structure)
  1478. (defcustom org-highlight-sparse-tree-matches t
  1479. "Non-nil means highlight all matches that define a sparse tree.
  1480. The highlights will automatically disappear the next time the buffer is
  1481. changed by an edit command."
  1482. :group 'org-sparse-trees
  1483. :type 'boolean)
  1484. (defcustom org-remove-highlights-with-change t
  1485. "Non-nil means any change to the buffer will remove temporary highlights.
  1486. \\<org-mode-map>\
  1487. Such highlights are created by `org-occur' and `org-clock-display'.
  1488. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1489. to get rid of the highlights.
  1490. The highlights created by `org-latex-preview' always need
  1491. `\\[org-latex-preview]' to be removed."
  1492. :group 'org-sparse-trees
  1493. :group 'org-time
  1494. :type 'boolean)
  1495. (defcustom org-occur-case-fold-search t
  1496. "Non-nil means `org-occur' should be case-insensitive.
  1497. If set to `smart' the search will be case-insensitive only if it
  1498. doesn't specify any upper case character."
  1499. :group 'org-sparse-trees
  1500. :version "26.1"
  1501. :type '(choice
  1502. (const :tag "Case-sensitive" nil)
  1503. (const :tag "Case-insensitive" t)
  1504. (const :tag "Case-insensitive for lower case searches only" smart)))
  1505. (defcustom org-occur-hook '(org-first-headline-recenter)
  1506. "Hook that is run after `org-occur' has constructed a sparse tree.
  1507. This can be used to recenter the window to show as much of the structure
  1508. as possible."
  1509. :group 'org-sparse-trees
  1510. :type 'hook)
  1511. (defcustom org-self-insert-cluster-for-undo nil
  1512. "Non-nil means cluster self-insert commands for undo when possible.
  1513. If this is set, then, like in the Emacs command loop, 20 consecutive
  1514. characters will be undone together.
  1515. This is configurable, because there is some impact on typing performance."
  1516. :group 'org-table
  1517. :type 'boolean)
  1518. (defvaralias 'org-activate-links 'org-highlight-links)
  1519. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1520. "Types of links that should be highlighted in Org files.
  1521. This is a list of symbols, each one of them leading to the
  1522. highlighting of a certain link type.
  1523. You can still open links that are not highlighted.
  1524. In principle, it does not hurt to turn on highlighting for all
  1525. link types. There may be a small gain when turning off unused
  1526. link types. The types are:
  1527. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1528. angle Links in angular brackets that may contain whitespace like
  1529. <bbdb:Carsten Dominik>.
  1530. plain Plain links in normal text, no whitespace, like http://google.com.
  1531. radio Text that is matched by a radio target, see manual for details.
  1532. tag Tag settings in a headline (link to tag search).
  1533. date Time stamps (link to calendar).
  1534. footnote Footnote labels.
  1535. If you set this variable during an Emacs session, use `org-mode-restart'
  1536. in the Org buffer so that the change takes effect."
  1537. :group 'org-appearance
  1538. :type '(set :greedy t
  1539. (const :tag "Double bracket links" bracket)
  1540. (const :tag "Angular bracket links" angle)
  1541. (const :tag "Plain text links" plain)
  1542. (const :tag "Radio target matches" radio)
  1543. (const :tag "Tags" tag)
  1544. (const :tag "Timestamps" date)
  1545. (const :tag "Footnotes" footnote)))
  1546. (defcustom org-mark-ring-length 4
  1547. "Number of different positions to be recorded in the ring.
  1548. Changing this requires a restart of Emacs to work correctly."
  1549. :group 'org-link-follow
  1550. :type 'integer)
  1551. (defgroup org-refile nil
  1552. "Options concerning refiling entries in Org mode."
  1553. :tag "Org Refile"
  1554. :group 'org)
  1555. (defcustom org-directory "~/org"
  1556. "Directory with Org files.
  1557. This is just a default location to look for Org files. There is no need
  1558. at all to put your files into this directory. It is used in the
  1559. following situations:
  1560. 1. When a capture template specifies a target file that is not an
  1561. absolute path. The path will then be interpreted relative to
  1562. `org-directory'
  1563. 2. When the value of variable `org-agenda-files' is a single file, any
  1564. relative paths in this file will be taken as relative to
  1565. `org-directory'."
  1566. :group 'org-refile
  1567. :group 'org-capture
  1568. :type 'directory)
  1569. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  1570. "Default target for storing notes.
  1571. Used as a fall back file for org-capture.el, for templates that
  1572. do not specify a target file."
  1573. :group 'org-refile
  1574. :group 'org-capture
  1575. :type 'file)
  1576. (defcustom org-reverse-note-order nil
  1577. "Non-nil means store new notes at the beginning of a file or entry.
  1578. When nil, new notes will be filed to the end of a file or entry.
  1579. This can also be a list with cons cells of regular expressions that
  1580. are matched against file names, and values."
  1581. :group 'org-capture
  1582. :group 'org-refile
  1583. :type '(choice
  1584. (const :tag "Reverse always" t)
  1585. (const :tag "Reverse never" nil)
  1586. (repeat :tag "By file name regexp"
  1587. (cons regexp boolean))))
  1588. (defcustom org-log-refile nil
  1589. "Information to record when a task is refiled.
  1590. Possible values are:
  1591. nil Don't add anything
  1592. time Add a time stamp to the task
  1593. note Prompt for a note and add it with template `org-log-note-headings'
  1594. This option can also be set with on a per-file-basis with
  1595. #+STARTUP: nologrefile
  1596. #+STARTUP: logrefile
  1597. #+STARTUP: lognoterefile
  1598. You can have local logging settings for a subtree by setting the LOGGING
  1599. property to one or more of these keywords.
  1600. When bulk-refiling, e.g., from the agenda, the value `note' is
  1601. forbidden and will temporarily be changed to `time'."
  1602. :group 'org-refile
  1603. :group 'org-progress
  1604. :version "24.1"
  1605. :type '(choice
  1606. (const :tag "No logging" nil)
  1607. (const :tag "Record timestamp" time)
  1608. (const :tag "Record timestamp with note." note)))
  1609. (defcustom org-refile-targets nil
  1610. "Targets for refiling entries with `\\[org-refile]'.
  1611. This is a list of cons cells. Each cell contains:
  1612. - a specification of the files to be considered, either a list of files,
  1613. or a symbol whose function or variable value will be used to retrieve
  1614. a file name or a list of file names. If you use `org-agenda-files' for
  1615. that, all agenda files will be scanned for targets. Nil means consider
  1616. headings in the current buffer.
  1617. - A specification of how to find candidate refile targets. This may be
  1618. any of:
  1619. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  1620. This tag has to be present in all target headlines, inheritance will
  1621. not be considered.
  1622. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  1623. todo keyword.
  1624. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  1625. headlines that are refiling targets.
  1626. - a cons cell (:level . N). Any headline of level N is considered a target.
  1627. Note that, when `org-odd-levels-only' is set, level corresponds to
  1628. order in hierarchy, not to the number of stars.
  1629. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  1630. Note that, when `org-odd-levels-only' is set, level corresponds to
  1631. order in hierarchy, not to the number of stars.
  1632. Each element of this list generates a set of possible targets.
  1633. The union of these sets is presented (with completion) to
  1634. the user by `org-refile'.
  1635. You can set the variable `org-refile-target-verify-function' to a function
  1636. to verify each headline found by the simple criteria above.
  1637. When this variable is nil, all top-level headlines in the current buffer
  1638. are used, equivalent to the value `((nil . (:level . 1))'."
  1639. :group 'org-refile
  1640. :type '(repeat
  1641. (cons
  1642. (choice :value org-agenda-files
  1643. (const :tag "All agenda files" org-agenda-files)
  1644. (const :tag "Current buffer" nil)
  1645. (function) (variable) (file))
  1646. (choice :tag "Identify target headline by"
  1647. (cons :tag "Specific tag" (const :value :tag) (string))
  1648. (cons :tag "TODO keyword" (const :value :todo) (string))
  1649. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  1650. (cons :tag "Level number" (const :value :level) (integer))
  1651. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  1652. (defcustom org-refile-target-verify-function nil
  1653. "Function to verify if the headline at point should be a refile target.
  1654. The function will be called without arguments, with point at the
  1655. beginning of the headline. It should return t and leave point
  1656. where it is if the headline is a valid target for refiling.
  1657. If the target should not be selected, the function must return nil.
  1658. In addition to this, it may move point to a place from where the search
  1659. should be continued. For example, the function may decide that the entire
  1660. subtree of the current entry should be excluded and move point to the end
  1661. of the subtree."
  1662. :group 'org-refile
  1663. :type '(choice
  1664. (const nil)
  1665. (function)))
  1666. (defcustom org-refile-use-cache nil
  1667. "Non-nil means cache refile targets to speed up the process.
  1668. \\<org-mode-map>\
  1669. The cache for a particular file will be updated automatically when
  1670. the buffer has been killed, or when any of the marker used for flagging
  1671. refile targets no longer points at a live buffer.
  1672. If you have added new entries to a buffer that might themselves be targets,
  1673. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  1674. if you find that easier, \
  1675. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  1676. \\[org-refile]'."
  1677. :group 'org-refile
  1678. :version "24.1"
  1679. :type 'boolean)
  1680. (defcustom org-refile-use-outline-path nil
  1681. "Non-nil means provide refile targets as paths.
  1682. So a level 3 headline will be available as level1/level2/level3.
  1683. When the value is `file', also include the file name (without directory)
  1684. into the path. In this case, you can also stop the completion after
  1685. the file name, to get entries inserted as top level in the file.
  1686. When `full-file-path', include the full file path.
  1687. When `buffer-name', use the buffer name."
  1688. :group 'org-refile
  1689. :type '(choice
  1690. (const :tag "Not" nil)
  1691. (const :tag "Yes" t)
  1692. (const :tag "Start with file name" file)
  1693. (const :tag "Start with full file path" full-file-path)
  1694. (const :tag "Start with buffer name" buffer-name)))
  1695. (defcustom org-outline-path-complete-in-steps t
  1696. "Non-nil means complete the outline path in hierarchical steps.
  1697. When Org uses the refile interface to select an outline path (see
  1698. `org-refile-use-outline-path'), the completion of the path can be
  1699. done in a single go, or it can be done in steps down the headline
  1700. hierarchy. Going in steps is probably the best if you do not use
  1701. a special completion package like `ido' or `icicles'. However,
  1702. when using these packages, going in one step can be very fast,
  1703. while still showing the whole path to the entry."
  1704. :group 'org-refile
  1705. :type 'boolean)
  1706. (defcustom org-refile-allow-creating-parent-nodes nil
  1707. "Non-nil means allow the creation of new nodes as refile targets.
  1708. New nodes are then created by adding \"/new node name\" to the completion
  1709. of an existing node. When the value of this variable is `confirm',
  1710. new node creation must be confirmed by the user (recommended).
  1711. When nil, the completion must match an existing entry.
  1712. Note that, if the new heading is not seen by the criteria
  1713. listed in `org-refile-targets', multiple instances of the same
  1714. heading would be created by trying again to file under the new
  1715. heading."
  1716. :group 'org-refile
  1717. :type '(choice
  1718. (const :tag "Never" nil)
  1719. (const :tag "Always" t)
  1720. (const :tag "Prompt for confirmation" confirm)))
  1721. (defcustom org-refile-active-region-within-subtree nil
  1722. "Non-nil means also refile active region within a subtree.
  1723. By default `org-refile' doesn't allow refiling regions if they
  1724. don't contain a set of subtrees, but it might be convenient to
  1725. do so sometimes: in that case, the first line of the region is
  1726. converted to a headline before refiling."
  1727. :group 'org-refile
  1728. :version "24.1"
  1729. :type 'boolean)
  1730. (defgroup org-todo nil
  1731. "Options concerning TODO items in Org mode."
  1732. :tag "Org TODO"
  1733. :group 'org)
  1734. (defgroup org-progress nil
  1735. "Options concerning Progress logging in Org mode."
  1736. :tag "Org Progress"
  1737. :group 'org-time)
  1738. (defvar org-todo-interpretation-widgets
  1739. '((:tag "Sequence (cycling hits every state)" sequence)
  1740. (:tag "Type (cycling directly to DONE)" type))
  1741. "The available interpretation symbols for customizing `org-todo-keywords'.
  1742. Interested libraries should add to this list.")
  1743. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1744. "List of TODO entry keyword sequences and their interpretation.
  1745. \\<org-mode-map>This is a list of sequences.
  1746. Each sequence starts with a symbol, either `sequence' or `type',
  1747. indicating if the keywords should be interpreted as a sequence of
  1748. action steps, or as different types of TODO items. The first
  1749. keywords are states requiring action - these states will select a headline
  1750. for inclusion into the global TODO list Org produces. If one of the
  1751. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1752. signify that no further action is necessary. If \"|\" is not found,
  1753. the last keyword is treated as the only DONE state of the sequence.
  1754. The command `\\[org-todo]' cycles an entry through these states, and one
  1755. additional state where no keyword is present. For details about this
  1756. cycling, see the manual.
  1757. TODO keywords and interpretation can also be set on a per-file basis with
  1758. the special #+SEQ_TODO and #+TYP_TODO lines.
  1759. Each keyword can optionally specify a character for fast state selection
  1760. \(in combination with the variable `org-use-fast-todo-selection')
  1761. and specifiers for state change logging, using the same syntax that
  1762. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1763. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1764. indicates to record a time stamp each time this state is selected.
  1765. Each keyword may also specify if a timestamp or a note should be
  1766. recorded when entering or leaving the state, by adding additional
  1767. characters in the parenthesis after the keyword. This looks like this:
  1768. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1769. record only the time of the state change. With X and Y being either
  1770. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1771. Y when leaving the state if and only if the *target* state does not
  1772. define X. You may omit any of the fast-selection key or X or /Y,
  1773. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1774. For backward compatibility, this variable may also be just a list
  1775. of keywords. In this case the interpretation (sequence or type) will be
  1776. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1777. :group 'org-todo
  1778. :group 'org-keywords
  1779. :type '(choice
  1780. (repeat :tag "Old syntax, just keywords"
  1781. (string :tag "Keyword"))
  1782. (repeat :tag "New syntax"
  1783. (cons
  1784. (choice
  1785. :tag "Interpretation"
  1786. ;;Quick and dirty way to see
  1787. ;;`org-todo-interpretations'. This takes the
  1788. ;;place of item arguments
  1789. :convert-widget
  1790. (lambda (widget)
  1791. (widget-put widget
  1792. :args (mapcar
  1793. (lambda (x)
  1794. (widget-convert
  1795. (cons 'const x)))
  1796. org-todo-interpretation-widgets))
  1797. widget))
  1798. (repeat
  1799. (string :tag "Keyword"))))))
  1800. (defvar-local org-todo-keywords-1 nil
  1801. "All TODO and DONE keywords active in a buffer.")
  1802. (defvar org-todo-keywords-for-agenda nil)
  1803. (defvar org-done-keywords-for-agenda nil)
  1804. (defvar org-todo-keyword-alist-for-agenda nil)
  1805. (defvar org-tag-alist-for-agenda nil
  1806. "Alist of all tags from all agenda files.")
  1807. (defvar org-tag-groups-alist-for-agenda nil
  1808. "Alist of all groups tags from all current agenda files.")
  1809. (defvar-local org-tag-groups-alist nil)
  1810. (defvar org-agenda-contributing-files nil)
  1811. (defvar-local org-current-tag-alist nil
  1812. "Alist of all tag groups in current buffer.
  1813. This variable takes into consideration `org-tag-alist',
  1814. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1815. (defvar-local org-not-done-keywords nil)
  1816. (defvar-local org-done-keywords nil)
  1817. (defvar-local org-todo-heads nil)
  1818. (defvar-local org-todo-sets nil)
  1819. (defvar-local org-todo-log-states nil)
  1820. (defvar-local org-todo-kwd-alist nil)
  1821. (defvar-local org-todo-key-alist nil)
  1822. (defvar-local org-todo-key-trigger nil)
  1823. (defcustom org-todo-interpretation 'sequence
  1824. "Controls how TODO keywords are interpreted.
  1825. This variable is in principle obsolete and is only used for
  1826. backward compatibility, if the interpretation of todo keywords is
  1827. not given already in `org-todo-keywords'. See that variable for
  1828. more information."
  1829. :group 'org-todo
  1830. :group 'org-keywords
  1831. :type '(choice (const sequence)
  1832. (const type)))
  1833. (defcustom org-use-fast-todo-selection 'auto
  1834. "\\<org-mode-map>\
  1835. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1836. This variable describes if and under what circumstances the cycling
  1837. mechanism for TODO keywords will be replaced by a single-key, direct
  1838. selection scheme, where the choices are displayed in a little window.
  1839. When nil, fast selection is never used. This means that the command
  1840. will always switch to the next state.
  1841. When it is the symbol `auto', fast selection is whenever selection
  1842. keys have been defined.
  1843. `expert' is like `auto', but no special window with the keyword
  1844. will be shown, choices will only be listed in the prompt.
  1845. In all cases, the special interface is only used if access keys have
  1846. actually been assigned by the user, i.e. if keywords in the configuration
  1847. are followed by a letter in parenthesis, like TODO(t)."
  1848. :group 'org-todo
  1849. :set (lambda (var val)
  1850. (cond
  1851. ((eq var t) (set var 'auto))
  1852. ((eq var 'prefix) (set var nil))
  1853. (t (set var val))))
  1854. :type '(choice
  1855. (const :tag "Never" nil)
  1856. (const :tag "Automatically, when key letter have been defined" auto)
  1857. (const :tag "Automatically, but don't show the selection window" expert)))
  1858. (defcustom org-provide-todo-statistics t
  1859. "Non-nil means update todo statistics after insert and toggle.
  1860. ALL-HEADLINES means update todo statistics by including headlines
  1861. with no TODO keyword as well, counting them as not done.
  1862. A list of TODO keywords means the same, but skip keywords that are
  1863. not in this list.
  1864. When set to a list of two lists, the first list contains keywords
  1865. to consider as TODO keywords, the second list contains keywords
  1866. to consider as DONE keywords.
  1867. When this is set, todo statistics is updated in the parent of the
  1868. current entry each time a todo state is changed."
  1869. :group 'org-todo
  1870. :type '(choice
  1871. (const :tag "Yes, only for TODO entries" t)
  1872. (const :tag "Yes, including all entries" all-headlines)
  1873. (repeat :tag "Yes, for TODOs in this list"
  1874. (string :tag "TODO keyword"))
  1875. (list :tag "Yes, for TODOs and DONEs in these lists"
  1876. (repeat (string :tag "TODO keyword"))
  1877. (repeat (string :tag "DONE keyword")))
  1878. (other :tag "No TODO statistics" nil)))
  1879. (defcustom org-hierarchical-todo-statistics t
  1880. "Non-nil means TODO statistics covers just direct children.
  1881. When nil, all entries in the subtree are considered.
  1882. This has only an effect if `org-provide-todo-statistics' is set.
  1883. To set this to nil for only a single subtree, use a COOKIE_DATA
  1884. property and include the word \"recursive\" into the value."
  1885. :group 'org-todo
  1886. :type 'boolean)
  1887. (defcustom org-after-todo-state-change-hook nil
  1888. "Hook which is run after the state of a TODO item was changed.
  1889. The new state (a string with a TODO keyword, or nil) is available in the
  1890. Lisp variable `org-state'."
  1891. :group 'org-todo
  1892. :type 'hook)
  1893. (defvar org-blocker-hook nil
  1894. "Hook for functions that are allowed to block a state change.
  1895. Functions in this hook should not modify the buffer.
  1896. Each function gets as its single argument a property list,
  1897. see `org-trigger-hook' for more information about this list.
  1898. If any of the functions in this hook returns nil, the state change
  1899. is blocked.")
  1900. (defvar org-trigger-hook nil
  1901. "Hook for functions that are triggered by a state change.
  1902. Each function gets as its single argument a property list with at
  1903. least the following elements:
  1904. (:type type-of-change :position pos-at-entry-start
  1905. :from old-state :to new-state)
  1906. Depending on the type, more properties may be present.
  1907. This mechanism is currently implemented for:
  1908. TODO state changes
  1909. ------------------
  1910. :type todo-state-change
  1911. :from previous state (keyword as a string), or nil, or a symbol
  1912. `todo' or `done', to indicate the general type of state.
  1913. :to new state, like in :from")
  1914. (defcustom org-enforce-todo-dependencies nil
  1915. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1916. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1917. be blocked if any prior sibling is not yet done.
  1918. Finally, if the parent is blocked because of ordered siblings of its own,
  1919. the child will also be blocked."
  1920. :set (lambda (var val)
  1921. (set var val)
  1922. (if val
  1923. (add-hook 'org-blocker-hook
  1924. 'org-block-todo-from-children-or-siblings-or-parent)
  1925. (remove-hook 'org-blocker-hook
  1926. 'org-block-todo-from-children-or-siblings-or-parent)))
  1927. :group 'org-todo
  1928. :type 'boolean)
  1929. (defcustom org-enforce-todo-checkbox-dependencies nil
  1930. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1931. When this is nil, checkboxes have no influence on switching TODO states.
  1932. When non-nil, you first need to check off all check boxes before the TODO
  1933. entry can be switched to DONE.
  1934. This variable needs to be set before org.el is loaded, and you need to
  1935. restart Emacs after a change to make the change effective. The only way
  1936. to change it while Emacs is running is through the customize interface."
  1937. :set (lambda (var val)
  1938. (set var val)
  1939. (if val
  1940. (add-hook 'org-blocker-hook
  1941. 'org-block-todo-from-checkboxes)
  1942. (remove-hook 'org-blocker-hook
  1943. 'org-block-todo-from-checkboxes)))
  1944. :group 'org-todo
  1945. :type 'boolean)
  1946. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1947. "Non-nil means inserting a TODO heading is treated as state change.
  1948. So when the command `\\[org-insert-todo-heading]' is used, state change
  1949. logging will apply if appropriate. When nil, the new TODO item will
  1950. be inserted directly, and no logging will take place."
  1951. :group 'org-todo
  1952. :type 'boolean)
  1953. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1954. "Non-nil means switching TODO states with S-cursor counts as state change.
  1955. This is the default behavior. However, setting this to nil allows a
  1956. convenient way to select a TODO state and bypass any logging associated
  1957. with that."
  1958. :group 'org-todo
  1959. :type 'boolean)
  1960. (defcustom org-todo-state-tags-triggers nil
  1961. "Tag changes that should be triggered by TODO state changes.
  1962. This is a list. Each entry is
  1963. (state-change (tag . flag) .......)
  1964. State-change can be a string with a state, and empty string to indicate the
  1965. state that has no TODO keyword, or it can be one of the symbols `todo'
  1966. or `done', meaning any not-done or done state, respectively."
  1967. :group 'org-todo
  1968. :group 'org-tags
  1969. :type '(repeat
  1970. (cons (choice :tag "When changing to"
  1971. (const :tag "Not-done state" todo)
  1972. (const :tag "Done state" done)
  1973. (string :tag "State"))
  1974. (repeat
  1975. (cons :tag "Tag action"
  1976. (string :tag "Tag")
  1977. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1978. (defcustom org-log-done nil
  1979. "Information to record when a task moves to the DONE state.
  1980. Possible values are:
  1981. nil Don't add anything, just change the keyword
  1982. time Add a time stamp to the task
  1983. note Prompt for a note and add it with template `org-log-note-headings'
  1984. This option can also be set with on a per-file-basis with
  1985. #+STARTUP: nologdone
  1986. #+STARTUP: logdone
  1987. #+STARTUP: lognotedone
  1988. You can have local logging settings for a subtree by setting the LOGGING
  1989. property to one or more of these keywords."
  1990. :group 'org-todo
  1991. :group 'org-progress
  1992. :type '(choice
  1993. (const :tag "No logging" nil)
  1994. (const :tag "Record CLOSED timestamp" time)
  1995. (const :tag "Record CLOSED timestamp with note." note)))
  1996. ;; Normalize old uses of org-log-done.
  1997. (cond
  1998. ((eq org-log-done t) (setq org-log-done 'time))
  1999. ((and (listp org-log-done) (memq 'done org-log-done))
  2000. (setq org-log-done 'note)))
  2001. (defcustom org-log-reschedule nil
  2002. "Information to record when the scheduling date of a task is modified.
  2003. Possible values are:
  2004. nil Don't add anything, just change the date
  2005. time Add a time stamp to the task
  2006. note Prompt for a note and add it with template `org-log-note-headings'
  2007. This option can also be set with on a per-file-basis with
  2008. #+STARTUP: nologreschedule
  2009. #+STARTUP: logreschedule
  2010. #+STARTUP: lognotereschedule
  2011. You can have local logging settings for a subtree by setting the LOGGING
  2012. property to one or more of these keywords.
  2013. This variable has an effect when calling `org-schedule' or
  2014. `org-agenda-schedule' only."
  2015. :group 'org-todo
  2016. :group 'org-progress
  2017. :type '(choice
  2018. (const :tag "No logging" nil)
  2019. (const :tag "Record timestamp" time)
  2020. (const :tag "Record timestamp with note" note)))
  2021. (defcustom org-log-redeadline nil
  2022. "Information to record when the deadline date of a task is modified.
  2023. Possible values are:
  2024. nil Don't add anything, just change the date
  2025. time Add a time stamp to the task
  2026. note Prompt for a note and add it with template `org-log-note-headings'
  2027. This option can also be set with on a per-file-basis with
  2028. #+STARTUP: nologredeadline
  2029. #+STARTUP: logredeadline
  2030. #+STARTUP: lognoteredeadline
  2031. You can have local logging settings for a subtree by setting the LOGGING
  2032. property to one or more of these keywords.
  2033. This variable has an effect when calling `org-deadline' or
  2034. `org-agenda-deadline' only."
  2035. :group 'org-todo
  2036. :group 'org-progress
  2037. :type '(choice
  2038. (const :tag "No logging" nil)
  2039. (const :tag "Record timestamp" time)
  2040. (const :tag "Record timestamp with note." note)))
  2041. (defcustom org-log-note-clock-out nil
  2042. "Non-nil means record a note when clocking out of an item.
  2043. This can also be configured on a per-file basis by adding one of
  2044. the following lines anywhere in the buffer:
  2045. #+STARTUP: lognoteclock-out
  2046. #+STARTUP: nolognoteclock-out"
  2047. :group 'org-todo
  2048. :group 'org-progress
  2049. :type 'boolean)
  2050. (defcustom org-log-done-with-time t
  2051. "Non-nil means the CLOSED time stamp will contain date and time.
  2052. When nil, only the date will be recorded."
  2053. :group 'org-progress
  2054. :type 'boolean)
  2055. (defcustom org-log-note-headings
  2056. '((done . "CLOSING NOTE %t")
  2057. (state . "State %-12s from %-12S %t")
  2058. (note . "Note taken on %t")
  2059. (reschedule . "Rescheduled from %S on %t")
  2060. (delschedule . "Not scheduled, was %S on %t")
  2061. (redeadline . "New deadline from %S on %t")
  2062. (deldeadline . "Removed deadline, was %S on %t")
  2063. (refile . "Refiled on %t")
  2064. (clock-out . ""))
  2065. "Headings for notes added to entries.
  2066. The value is an alist, with the car being a symbol indicating the
  2067. note context, and the cdr is the heading to be used. The heading
  2068. may also be the empty string. The following placeholders can be
  2069. used:
  2070. %t a time stamp.
  2071. %T an active time stamp instead the default inactive one
  2072. %d a short-format time stamp.
  2073. %D an active short-format time stamp.
  2074. %s the new TODO state or time stamp (inactive), in double quotes.
  2075. %S the old TODO state or time stamp (inactive), in double quotes.
  2076. %u the user name.
  2077. %U full user name.
  2078. In fact, it is not a good idea to change the `state' entry,
  2079. because Agenda Log mode depends on the format of these entries."
  2080. :group 'org-todo
  2081. :group 'org-progress
  2082. :type '(list :greedy t
  2083. (cons (const :tag "Heading when closing an item" done) string)
  2084. (cons (const :tag
  2085. "Heading when changing todo state (todo sequence only)"
  2086. state) string)
  2087. (cons (const :tag "Heading when just taking a note" note) string)
  2088. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2089. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2090. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2091. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2092. (cons (const :tag "Heading when refiling" refile) string)
  2093. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2094. (unless (assq 'note org-log-note-headings)
  2095. (push '(note . "%t") org-log-note-headings))
  2096. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2097. (defcustom org-log-into-drawer nil
  2098. "Non-nil means insert state change notes and time stamps into a drawer.
  2099. When nil, state changes notes will be inserted after the headline and
  2100. any scheduling and clock lines, but not inside a drawer.
  2101. The value of this variable should be the name of the drawer to use.
  2102. LOGBOOK is proposed as the default drawer for this purpose, you can
  2103. also set this to a string to define the drawer of your choice.
  2104. A value of t is also allowed, representing \"LOGBOOK\".
  2105. A value of t or nil can also be set with on a per-file-basis with
  2106. #+STARTUP: logdrawer
  2107. #+STARTUP: nologdrawer
  2108. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2109. will be ignored.
  2110. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2111. a subtree.
  2112. Do not check directly this variable in a Lisp program. Call
  2113. function `org-log-into-drawer' instead."
  2114. :group 'org-todo
  2115. :group 'org-progress
  2116. :type '(choice
  2117. (const :tag "Not into a drawer" nil)
  2118. (const :tag "LOGBOOK" t)
  2119. (string :tag "Other")))
  2120. (defun org-log-into-drawer ()
  2121. "Name of the log drawer, as a string, or nil.
  2122. This is the value of `org-log-into-drawer'. However, if the
  2123. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2124. be used instead of the default value."
  2125. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2126. (cond ((equal p "nil") nil)
  2127. ((equal p "t") "LOGBOOK")
  2128. ((stringp p) p)
  2129. (p "LOGBOOK")
  2130. ((stringp org-log-into-drawer) org-log-into-drawer)
  2131. (org-log-into-drawer "LOGBOOK"))))
  2132. (defcustom org-log-state-notes-insert-after-drawers nil
  2133. "Non-nil means insert state change notes after any drawers in entry.
  2134. Only the drawers that *immediately* follow the headline and the
  2135. deadline/scheduled line are skipped.
  2136. When nil, insert notes right after the heading and perhaps the line
  2137. with deadline/scheduling if present.
  2138. This variable will have no effect if `org-log-into-drawer' is
  2139. set."
  2140. :group 'org-todo
  2141. :group 'org-progress
  2142. :type 'boolean)
  2143. (defcustom org-log-states-order-reversed t
  2144. "Non-nil means the latest state note will be directly after heading.
  2145. When nil, the state change notes will be ordered according to time.
  2146. This option can also be set with on a per-file-basis with
  2147. #+STARTUP: logstatesreversed
  2148. #+STARTUP: nologstatesreversed"
  2149. :group 'org-todo
  2150. :group 'org-progress
  2151. :type 'boolean)
  2152. (defcustom org-todo-repeat-to-state nil
  2153. "The TODO state to which a repeater should return the repeating task.
  2154. By default this is the first task of a TODO sequence or the
  2155. previous state of a TYPE_TODO set. But you can specify to use
  2156. the previous state in a TODO sequence or a string.
  2157. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2158. entry, which has precedence over this option."
  2159. :group 'org-todo
  2160. :version "24.1"
  2161. :type '(choice (const :tag "Use the previous TODO state" t)
  2162. (const :tag "Use the head of the TODO sequence" nil)
  2163. (string :tag "Use a specific TODO state")))
  2164. (defcustom org-log-repeat 'time
  2165. "Non-nil means record moving through the DONE state when triggering repeat.
  2166. An auto-repeating task is immediately switched back to TODO when
  2167. marked DONE. If you are not logging state changes (by adding \"@\"
  2168. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2169. record a closing note, there will be no record of the task moving
  2170. through DONE. This variable forces taking a note anyway.
  2171. nil Don't force a record
  2172. time Record a time stamp
  2173. note Prompt for a note and add it with template `org-log-note-headings'
  2174. This option can also be set with on a per-file-basis with
  2175. #+STARTUP: nologrepeat
  2176. #+STARTUP: logrepeat
  2177. #+STARTUP: lognoterepeat
  2178. You can have local logging settings for a subtree by setting the LOGGING
  2179. property to one or more of these keywords."
  2180. :group 'org-todo
  2181. :group 'org-progress
  2182. :type '(choice
  2183. (const :tag "Don't force a record" nil)
  2184. (const :tag "Force recording the DONE state" time)
  2185. (const :tag "Force recording a note with the DONE state" note)))
  2186. (defcustom org-todo-repeat-hook nil
  2187. "Hook that is run after a task has been repeated."
  2188. :package-version '(Org . "9.2")
  2189. :group 'org-todo
  2190. :type 'hook)
  2191. (defgroup org-priorities nil
  2192. "Priorities in Org mode."
  2193. :tag "Org Priorities"
  2194. :group 'org-todo)
  2195. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  2196. (defcustom org-priority-enable-commands t
  2197. "Non-nil means priority commands are active.
  2198. When nil, these commands will be disabled, so that you never accidentally
  2199. set a priority."
  2200. :group 'org-priorities
  2201. :type 'boolean)
  2202. (defvaralias 'org-highest-priority 'org-priority-highest)
  2203. (defcustom org-priority-highest ?A
  2204. "The highest priority of TODO items. A character like ?A, ?B etc.
  2205. Must have a smaller ASCII number than `org-priority-lowest'."
  2206. :group 'org-priorities
  2207. :type 'character)
  2208. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  2209. (defcustom org-priority-lowest ?C
  2210. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2211. Must have a larger ASCII number than `org-priority-highest'."
  2212. :group 'org-priorities
  2213. :type 'character)
  2214. (defvaralias 'org-default-priority 'org-priority-default)
  2215. (defcustom org-priority-default ?B
  2216. "The default priority of TODO items.
  2217. This is the priority an item gets if no explicit priority is given.
  2218. When starting to cycle on an empty priority the first step in the cycle
  2219. depends on `org-priority-start-cycle-with-default'. The resulting first
  2220. step priority must not exceed the range from `org-priority-highest' to
  2221. `org-priority-lowest' which means that `org-priority-default' has to be
  2222. in this range exclusive or inclusive the range boundaries. Else the
  2223. first step refuses to set the default and the second will fall back
  2224. to (depending on the command used) the highest or lowest priority."
  2225. :group 'org-priorities
  2226. :type 'character)
  2227. (defcustom org-priority-start-cycle-with-default t
  2228. "Non-nil means start with default priority when starting to cycle.
  2229. When this is nil, the first step in the cycle will be (depending on the
  2230. command used) one higher or lower than the default priority.
  2231. See also `org-priority-default'."
  2232. :group 'org-priorities
  2233. :type 'boolean)
  2234. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2235. (defcustom org-priority-get-priority-function nil
  2236. "Function to extract the priority from a string.
  2237. The string is normally the headline. If this is nil Org computes the
  2238. priority from the priority cookie like [#A] in the headline. It returns
  2239. an integer, increasing by 1000 for each priority level.
  2240. The user can set a different function here, which should take a string
  2241. as an argument and return the numeric priority."
  2242. :group 'org-priorities
  2243. :version "24.1"
  2244. :type '(choice
  2245. (const nil)
  2246. (function)))
  2247. (defgroup org-time nil
  2248. "Options concerning time stamps and deadlines in Org mode."
  2249. :tag "Org Time"
  2250. :group 'org)
  2251. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2252. "Number of minutes to round time stamps to.
  2253. \\<org-mode-map>\
  2254. These are two values, the first applies when first creating a time stamp.
  2255. The second applies when changing it with the commands `S-up' and `S-down'.
  2256. When changing the time stamp, this means that it will change in steps
  2257. of N minutes, as given by the second value.
  2258. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2259. numbers should be factors of 60, so for example 5, 10, 15.
  2260. When this is larger than 1, you can still force an exact time stamp by using
  2261. a double prefix argument to a time stamp command like \
  2262. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2263. and by using a prefix arg to `S-up/down' to specify the exact number
  2264. of minutes to shift."
  2265. :group 'org-time
  2266. :get (lambda (var) ; Make sure both elements are there
  2267. (if (integerp (default-value var))
  2268. (list (default-value var) 5)
  2269. (default-value var)))
  2270. :type '(list
  2271. (integer :tag "when inserting times")
  2272. (integer :tag "when modifying times")))
  2273. ;; Normalize old customizations of this variable.
  2274. (when (integerp org-time-stamp-rounding-minutes)
  2275. (setq org-time-stamp-rounding-minutes
  2276. (list org-time-stamp-rounding-minutes
  2277. org-time-stamp-rounding-minutes)))
  2278. (defcustom org-display-custom-times nil
  2279. "Non-nil means overlay custom formats over all time stamps.
  2280. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2281. To turn this on on a per-file basis, insert anywhere in the file:
  2282. #+STARTUP: customtime"
  2283. :group 'org-time
  2284. :set 'set-default
  2285. :type 'sexp)
  2286. (make-variable-buffer-local 'org-display-custom-times)
  2287. (defcustom org-time-stamp-custom-formats
  2288. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2289. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2290. These are overlaid over the default ISO format if the variable
  2291. `org-display-custom-times' is set. Time like %H:%M should be at the
  2292. end of the second format. The custom formats are also honored by export
  2293. commands, if custom time display is turned on at the time of export."
  2294. :group 'org-time
  2295. :type 'sexp)
  2296. (defun org-time-stamp-format (&optional long inactive)
  2297. "Get the right format for a time string."
  2298. (let ((f (if long (cdr org-time-stamp-formats)
  2299. (car org-time-stamp-formats))))
  2300. (if inactive
  2301. (concat "[" (substring f 1 -1) "]")
  2302. f)))
  2303. (defcustom org-deadline-warning-days 14
  2304. "Number of days before expiration during which a deadline becomes active.
  2305. This variable governs the display in sparse trees and in the agenda.
  2306. When 0 or negative, it means use this number (the absolute value of it)
  2307. even if a deadline has a different individual lead time specified.
  2308. Custom commands can set this variable in the options section."
  2309. :group 'org-time
  2310. :group 'org-agenda-daily/weekly
  2311. :type 'integer)
  2312. (defcustom org-scheduled-delay-days 0
  2313. "Number of days before a scheduled item becomes active.
  2314. This variable governs the display in sparse trees and in the agenda.
  2315. The default value (i.e. 0) means: don't delay scheduled item.
  2316. When negative, it means use this number (the absolute value of it)
  2317. even if a scheduled item has a different individual delay time
  2318. specified.
  2319. Custom commands can set this variable in the options section."
  2320. :group 'org-time
  2321. :group 'org-agenda-daily/weekly
  2322. :version "24.4"
  2323. :package-version '(Org . "8.0")
  2324. :type 'integer)
  2325. (defcustom org-read-date-prefer-future t
  2326. "Non-nil means assume future for incomplete date input from user.
  2327. This affects the following situations:
  2328. 1. The user gives a month but not a year.
  2329. For example, if it is April and you enter \"feb 2\", this will be read
  2330. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2331. 2. The user gives a day, but no month.
  2332. For example, if today is the 15th, and you enter \"3\", Org will read
  2333. this as the third of *next* month. However, if you enter \"17\",
  2334. it will be considered as *this* month.
  2335. If you set this variable to the symbol `time', then also the following
  2336. will work:
  2337. 3. If the user gives a time.
  2338. If the time is before now, it will be interpreted as tomorrow.
  2339. Currently none of this works for ISO week specifications.
  2340. When this option is nil, the current day, month and year will always be
  2341. used as defaults.
  2342. See also `org-agenda-jump-prefer-future'."
  2343. :group 'org-time
  2344. :type '(choice
  2345. (const :tag "Never" nil)
  2346. (const :tag "Check month and day" t)
  2347. (const :tag "Check month, day, and time" time)))
  2348. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2349. "Should the agenda jump command prefer the future for incomplete dates?
  2350. The default is to do the same as configured in `org-read-date-prefer-future'.
  2351. But you can also set a deviating value here.
  2352. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2353. :group 'org-agenda
  2354. :group 'org-time
  2355. :version "24.1"
  2356. :type '(choice
  2357. (const :tag "Use org-read-date-prefer-future"
  2358. org-read-date-prefer-future)
  2359. (const :tag "Never" nil)
  2360. (const :tag "Always" t)))
  2361. (defcustom org-read-date-force-compatible-dates t
  2362. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2363. Depending on the system Emacs is running on, certain dates cannot
  2364. be represented with the type used internally to represent time.
  2365. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2366. correctly. Some systems allow for earlier dates, some for later,
  2367. some for both. One way to find out is to insert any date into an
  2368. Org buffer, putting the cursor on the year and hitting S-up and
  2369. S-down to test the range.
  2370. When this variable is set to t, the date/time prompt will not let
  2371. you specify dates outside the 1970-2037 range, so it is certain that
  2372. these dates will work in whatever version of Emacs you are
  2373. running, and also that you can move a file from one Emacs implementation
  2374. to another. Whenever Org is forcing the year for you, it will display
  2375. a message and beep.
  2376. When this variable is nil, Org will check if the date is
  2377. representable in the specific Emacs implementation you are using.
  2378. If not, it will force a year, usually the current year, and beep
  2379. to remind you. Currently this setting is not recommended because
  2380. the likelihood that you will open your Org files in an Emacs that
  2381. has limited date range is not negligible.
  2382. A workaround for this problem is to use diary sexp dates for time
  2383. stamps outside of this range."
  2384. :group 'org-time
  2385. :version "24.1"
  2386. :type 'boolean)
  2387. (defcustom org-read-date-display-live t
  2388. "Non-nil means display current interpretation of date prompt live.
  2389. This display will be in an overlay, in the minibuffer."
  2390. :group 'org-time
  2391. :type 'boolean)
  2392. (defvaralias 'org-popup-calendar-for-date-prompt
  2393. 'org-read-date-popup-calendar)
  2394. (defcustom org-read-date-popup-calendar t
  2395. "Non-nil means pop up a calendar when prompting for a date.
  2396. In the calendar, the date can be selected with mouse-1. However, the
  2397. minibuffer will also be active, and you can simply enter the date as well.
  2398. When nil, only the minibuffer will be available."
  2399. :group 'org-time
  2400. :type 'boolean)
  2401. (defcustom org-extend-today-until 0
  2402. "The hour when your day really ends. Must be an integer.
  2403. This has influence for the following applications:
  2404. - When switching the agenda to \"today\". If it is still earlier than
  2405. the time given here, the day recognized as TODAY is actually yesterday.
  2406. - When a date is read from the user and it is still before the time given
  2407. here, the current date and time will be assumed to be yesterday, 23:59.
  2408. Also, timestamps inserted in capture templates follow this rule.
  2409. IMPORTANT: This is a feature whose implementation is and likely will
  2410. remain incomplete. Really, it is only here because past midnight seems to
  2411. be the favorite working time of John Wiegley :-)"
  2412. :group 'org-time
  2413. :type 'integer)
  2414. (defcustom org-use-effective-time nil
  2415. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2416. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2417. \"effective time\" of any timestamps between midnight and 8am will be
  2418. 23:59 of the previous day."
  2419. :group 'org-time
  2420. :version "24.1"
  2421. :type 'boolean)
  2422. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2423. "When non-nil, use the last clock out time for `org-todo'.
  2424. Note that this option has precedence over the combined use of
  2425. `org-use-effective-time' and `org-extend-today-until'."
  2426. :group 'org-time
  2427. :version "24.4"
  2428. :package-version '(Org . "8.0")
  2429. :type 'boolean)
  2430. (defcustom org-edit-timestamp-down-means-later nil
  2431. "Non-nil means S-down will increase the time in a time stamp.
  2432. When nil, S-up will increase."
  2433. :group 'org-time
  2434. :type 'boolean)
  2435. (defcustom org-calendar-follow-timestamp-change t
  2436. "Non-nil means make the calendar window follow timestamp changes.
  2437. When a timestamp is modified and the calendar window is visible, it will be
  2438. moved to the new date."
  2439. :group 'org-time
  2440. :type 'boolean)
  2441. (defgroup org-tags nil
  2442. "Options concerning tags in Org mode."
  2443. :tag "Org Tags"
  2444. :group 'org)
  2445. (defcustom org-tag-alist nil
  2446. "Default tags available in Org files.
  2447. The value of this variable is an alist. Associations either:
  2448. (TAG)
  2449. (TAG . SELECT)
  2450. (SPECIAL)
  2451. where TAG is a tag as a string, SELECT is character, used to
  2452. select that tag through the fast tag selection interface, and
  2453. SPECIAL is one of the following keywords: `:startgroup',
  2454. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2455. `:newline'. These keywords are used to define a hierarchy of
  2456. tags. See manual for details.
  2457. When this variable is nil, Org mode bases tag input on what is
  2458. already in the buffer. The value can be overridden locally by
  2459. using a TAGS keyword, e.g.,
  2460. #+TAGS: tag1 tag2
  2461. See also `org-tag-persistent-alist' to sidestep this behavior."
  2462. :group 'org-tags
  2463. :type '(repeat
  2464. (choice
  2465. (cons :tag "Tag with key"
  2466. (string :tag "Tag name")
  2467. (character :tag "Access char"))
  2468. (list :tag "Tag" (string :tag "Tag name"))
  2469. (const :tag "Start radio group" (:startgroup))
  2470. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2471. (const :tag "Group tags delimiter" (:grouptags))
  2472. (const :tag "End radio group" (:endgroup))
  2473. (const :tag "End tag group, non distinct" (:endgrouptag))
  2474. (const :tag "New line" (:newline)))))
  2475. (defcustom org-tag-persistent-alist nil
  2476. "Tags always available in Org files.
  2477. The value of this variable is an alist. Associations either:
  2478. (TAG)
  2479. (TAG . SELECT)
  2480. (SPECIAL)
  2481. where TAG is a tag as a string, SELECT is a character, used to
  2482. select that tag through the fast tag selection interface, and
  2483. SPECIAL is one of the following keywords: `:startgroup',
  2484. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2485. `:newline'. These keywords are used to define a hierarchy of
  2486. tags. See manual for details.
  2487. Unlike to `org-tag-alist', tags defined in this variable do not
  2488. depend on a local TAGS keyword. Instead, to disable these tags
  2489. on a per-file basis, insert anywhere in the file:
  2490. #+STARTUP: noptag"
  2491. :group 'org-tags
  2492. :type '(repeat
  2493. (choice
  2494. (cons :tag "Tag with key"
  2495. (string :tag "Tag name")
  2496. (character :tag "Access char"))
  2497. (list :tag "Tag" (string :tag "Tag name"))
  2498. (const :tag "Start radio group" (:startgroup))
  2499. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2500. (const :tag "Group tags delimiter" (:grouptags))
  2501. (const :tag "End radio group" (:endgroup))
  2502. (const :tag "End tag group, non distinct" (:endgrouptag))
  2503. (const :tag "New line" (:newline)))))
  2504. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2505. "If non-nil, always offer completion for all tags of all agenda files.
  2506. Setting this variable locally allows for dynamic generation of tag
  2507. completions in capture buffers.
  2508. (add-hook \\='org-capture-mode-hook
  2509. (lambda ()
  2510. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2511. :group 'org-tags
  2512. :version "24.1"
  2513. :type 'boolean)
  2514. (defvar org-file-tags nil
  2515. "List of tags that can be inherited by all entries in the file.
  2516. The tags will be inherited if the variable `org-use-tag-inheritance'
  2517. says they should be.
  2518. This variable is populated from #+FILETAGS lines.")
  2519. (defcustom org-use-fast-tag-selection 'auto
  2520. "Non-nil means use fast tag selection scheme.
  2521. This is a special interface to select and deselect tags with single keys.
  2522. When nil, fast selection is never used.
  2523. When the symbol `auto', fast selection is used if and only if selection
  2524. characters for tags have been configured, either through the variable
  2525. `org-tag-alist' or through a #+TAGS line in the buffer.
  2526. When t, fast selection is always used and selection keys are assigned
  2527. automatically if necessary."
  2528. :group 'org-tags
  2529. :type '(choice
  2530. (const :tag "Always" t)
  2531. (const :tag "Never" nil)
  2532. (const :tag "When selection characters are configured" auto)))
  2533. (defcustom org-fast-tag-selection-single-key nil
  2534. "Non-nil means fast tag selection exits after first change.
  2535. When nil, you have to press RET to exit it.
  2536. During fast tag selection, you can toggle this flag with `C-c'.
  2537. This variable can also have the value `expert'. In this case, the window
  2538. displaying the tags menu is not even shown, until you press C-c again."
  2539. :group 'org-tags
  2540. :type '(choice
  2541. (const :tag "No" nil)
  2542. (const :tag "Yes" t)
  2543. (const :tag "Expert" expert)))
  2544. (defvar org-fast-tag-selection-include-todo nil
  2545. "Non-nil means fast tags selection interface will also offer TODO states.
  2546. This is an undocumented feature, you should not rely on it.")
  2547. (defcustom org-tags-column -77
  2548. "The column to which tags should be indented in a headline.
  2549. If this number is positive, it specifies the column. If it is negative,
  2550. it means that the tags should be flushright to that column. For example,
  2551. -80 works well for a normal 80 character screen.
  2552. When 0, place tags directly after headline text, with only one space in
  2553. between."
  2554. :group 'org-tags
  2555. :type 'integer)
  2556. (defcustom org-auto-align-tags t
  2557. "Non-nil keeps tags aligned when modifying headlines.
  2558. Some operations (i.e. demoting) change the length of a headline and
  2559. therefore shift the tags around. With this option turned on, after
  2560. each such operation the tags are again aligned to `org-tags-column'."
  2561. :group 'org-tags
  2562. :type 'boolean)
  2563. (defcustom org-use-tag-inheritance t
  2564. "Non-nil means tags in levels apply also for sublevels.
  2565. When nil, only the tags directly given in a specific line apply there.
  2566. This may also be a list of tags that should be inherited, or a regexp that
  2567. matches tags that should be inherited. Additional control is possible
  2568. with the variable `org-tags-exclude-from-inheritance' which gives an
  2569. explicit list of tags to be excluded from inheritance, even if the value of
  2570. `org-use-tag-inheritance' would select it for inheritance.
  2571. If this option is t, a match early-on in a tree can lead to a large
  2572. number of matches in the subtree when constructing the agenda or creating
  2573. a sparse tree. If you only want to see the first match in a tree during
  2574. a search, check out the variable `org-tags-match-list-sublevels'."
  2575. :group 'org-tags
  2576. :type '(choice
  2577. (const :tag "Not" nil)
  2578. (const :tag "Always" t)
  2579. (repeat :tag "Specific tags" (string :tag "Tag"))
  2580. (regexp :tag "Tags matched by regexp")))
  2581. (defcustom org-tags-exclude-from-inheritance nil
  2582. "List of tags that should never be inherited.
  2583. This is a way to exclude a few tags from inheritance. For way to do
  2584. the opposite, to actively allow inheritance for selected tags,
  2585. see the variable `org-use-tag-inheritance'."
  2586. :group 'org-tags
  2587. :type '(repeat (string :tag "Tag")))
  2588. (defun org-tag-inherit-p (tag)
  2589. "Check if TAG is one that should be inherited."
  2590. (cond
  2591. ((member tag org-tags-exclude-from-inheritance) nil)
  2592. ((eq org-use-tag-inheritance t) t)
  2593. ((not org-use-tag-inheritance) nil)
  2594. ((stringp org-use-tag-inheritance)
  2595. (string-match org-use-tag-inheritance tag))
  2596. ((listp org-use-tag-inheritance)
  2597. (member tag org-use-tag-inheritance))
  2598. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2599. (defcustom org-tags-match-list-sublevels t
  2600. "Non-nil means list also sublevels of headlines matching a search.
  2601. This variable applies to tags/property searches, and also to stuck
  2602. projects because this search is based on a tags match as well.
  2603. When set to the symbol `indented', sublevels are indented with
  2604. leading dots.
  2605. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2606. the sublevels of a headline matching a tag search often also match
  2607. the same search. Listing all of them can create very long lists.
  2608. Setting this variable to nil causes subtrees of a match to be skipped.
  2609. This variable is semi-obsolete and probably should always be true. It
  2610. is better to limit inheritance to certain tags using the variables
  2611. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2612. :group 'org-tags
  2613. :type '(choice
  2614. (const :tag "No, don't list them" nil)
  2615. (const :tag "Yes, do list them" t)
  2616. (const :tag "List them, indented with leading dots" indented)))
  2617. (defcustom org-tags-sort-function nil
  2618. "When set, tags are sorted using this function as a comparator."
  2619. :group 'org-tags
  2620. :type '(choice
  2621. (const :tag "No sorting" nil)
  2622. (const :tag "Alphabetical" org-string-collate-lessp)
  2623. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2624. (function :tag "Custom function" nil)))
  2625. (defvar org-tags-history nil
  2626. "History of minibuffer reads for tags.")
  2627. (defvar org-last-tags-completion-table nil
  2628. "The last used completion table for tags.")
  2629. (defvar org-after-tags-change-hook nil
  2630. "Hook that is run after the tags in a line have changed.")
  2631. (defgroup org-properties nil
  2632. "Options concerning properties in Org mode."
  2633. :tag "Org Properties"
  2634. :group 'org)
  2635. (defcustom org-property-format "%-10s %s"
  2636. "How property key/value pairs should be formatted by `indent-line'.
  2637. When `indent-line' hits a property definition, it will format the line
  2638. according to this format, mainly to make sure that the values are
  2639. lined-up with respect to each other."
  2640. :group 'org-properties
  2641. :type 'string)
  2642. (defcustom org-properties-postprocess-alist nil
  2643. "Alist of properties and functions to adjust inserted values.
  2644. Elements of this alist must be of the form
  2645. ([string] [function])
  2646. where [string] must be a property name and [function] must be a
  2647. lambda expression: this lambda expression must take one argument,
  2648. the value to adjust, and return the new value as a string.
  2649. For example, this element will allow the property \"Remaining\"
  2650. to be updated wrt the relation between the \"Effort\" property
  2651. and the clock summary:
  2652. ((\"Remaining\" (lambda(value)
  2653. (let ((clocksum (org-clock-sum-current-item))
  2654. (effort (org-duration-to-minutes
  2655. (org-entry-get (point) \"Effort\"))))
  2656. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2657. :group 'org-properties
  2658. :version "24.1"
  2659. :type '(alist :key-type (string :tag "Property")
  2660. :value-type (function :tag "Function")))
  2661. (defcustom org-use-property-inheritance nil
  2662. "Non-nil means properties apply also for sublevels.
  2663. This setting is chiefly used during property searches. Turning it on can
  2664. cause significant overhead when doing a search, which is why it is not
  2665. on by default.
  2666. When nil, only the properties directly given in the current entry count.
  2667. When t, every property is inherited. The value may also be a list of
  2668. properties that should have inheritance, or a regular expression matching
  2669. properties that should be inherited.
  2670. However, note that some special properties use inheritance under special
  2671. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2672. and the properties ending in \"_ALL\" when they are used as descriptor
  2673. for valid values of a property.
  2674. Note for programmers:
  2675. When querying an entry with `org-entry-get', you can control if inheritance
  2676. should be used. By default, `org-entry-get' looks only at the local
  2677. properties. You can request inheritance by setting the inherit argument
  2678. to t (to force inheritance) or to `selective' (to respect the setting
  2679. in this variable)."
  2680. :group 'org-properties
  2681. :type '(choice
  2682. (const :tag "Not" nil)
  2683. (const :tag "Always" t)
  2684. (repeat :tag "Specific properties" (string :tag "Property"))
  2685. (regexp :tag "Properties matched by regexp")))
  2686. (defun org-property-inherit-p (property)
  2687. "Return a non-nil value if PROPERTY should be inherited."
  2688. (cond
  2689. ((eq org-use-property-inheritance t) t)
  2690. ((not org-use-property-inheritance) nil)
  2691. ((stringp org-use-property-inheritance)
  2692. (string-match org-use-property-inheritance property))
  2693. ((listp org-use-property-inheritance)
  2694. (member-ignore-case property org-use-property-inheritance))
  2695. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2696. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2697. "The default column format, if no other format has been defined.
  2698. This variable can be set on the per-file basis by inserting a line
  2699. #+COLUMNS: %25ITEM ....."
  2700. :group 'org-properties
  2701. :type 'string)
  2702. (defcustom org-columns-default-format-for-agenda nil
  2703. "The default column format in an agenda buffer.
  2704. This will be used for column view in the agenda unless a format has
  2705. been set by adding `org-overriding-columns-format' to the local
  2706. settings list of a custom agenda view. When nil, the columns format
  2707. for the first item in the agenda list will be used, or as a fall-back,
  2708. `org-columns-default-format'."
  2709. :group 'org-properties
  2710. :type '(choice
  2711. (const :tag "No default" nil)
  2712. (string :tag "Format string")))
  2713. (defcustom org-columns-ellipses ".."
  2714. "The ellipses to be used when a field in column view is truncated.
  2715. When this is the empty string, as many characters as possible are shown,
  2716. but then there will be no visual indication that the field has been truncated.
  2717. When this is a string of length N, the last N characters of a truncated
  2718. field are replaced by this string. If the column is narrower than the
  2719. ellipses string, only part of the ellipses string will be shown."
  2720. :group 'org-properties
  2721. :type 'string)
  2722. (defconst org-global-properties-fixed
  2723. '(("VISIBILITY_ALL" . "folded children content all")
  2724. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2725. "List of property/value pairs that can be inherited by any entry.
  2726. These are fixed values, for the preset properties. The user variable
  2727. that can be used to add to this list is `org-global-properties'.
  2728. The entries in this list are cons cells where the car is a property
  2729. name and cdr is a string with the value. If the value represents
  2730. multiple items like an \"_ALL\" property, separate the items by
  2731. spaces.")
  2732. (defcustom org-global-properties nil
  2733. "List of property/value pairs that can be inherited by any entry.
  2734. This list will be combined with the constant `org-global-properties-fixed'.
  2735. The entries in this list are cons cells where the car is a property
  2736. name and cdr is a string with the value.
  2737. Buffer local properties are added either by a document property drawer
  2738. :PROPERTIES:
  2739. :NAME: VALUE
  2740. :END:
  2741. or by adding lines like
  2742. #+PROPERTY: NAME VALUE"
  2743. :group 'org-properties
  2744. :type '(repeat
  2745. (cons (string :tag "Property")
  2746. (string :tag "Value"))))
  2747. (defvar-local org-keyword-properties nil
  2748. "List of property/value pairs inherited by any entry.
  2749. Valid for the current buffer. This variable is populated from
  2750. PROPERTY keywords.
  2751. Note that properties are defined also in property drawers.
  2752. Properties defined there take precedence over properties defined
  2753. as keywords.")
  2754. (defgroup org-agenda nil
  2755. "Options concerning agenda views in Org mode."
  2756. :tag "Org Agenda"
  2757. :group 'org)
  2758. (defvar-local org-category nil
  2759. "Variable used by Org files to set a category for agenda display.
  2760. There are multiple ways to set the category. One way is to set
  2761. it in the document property drawer. For example:
  2762. :PROPERTIES:
  2763. :CATEGORY: ELisp
  2764. :END:
  2765. Other ways to define it is as an emacs file variable, for example
  2766. # -*- mode: org; org-category: \"ELisp\"
  2767. or for the file to contain a special line:
  2768. #+CATEGORY: ELisp
  2769. If the file does not specify a category, then file's base name
  2770. is used instead.")
  2771. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2772. (defcustom org-agenda-files nil
  2773. "The files to be used for agenda display.
  2774. If an entry is a directory, all files in that directory that are matched
  2775. by `org-agenda-file-regexp' will be part of the file list.
  2776. If the value of the variable is not a list but a single file name, then
  2777. the list of agenda files is actually stored and maintained in that file,
  2778. one agenda file per line. In this file paths can be given relative to
  2779. `org-directory'. Tilde expansion and environment variable substitution
  2780. are also made.
  2781. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2782. and removed with `\\[org-remove-file]'."
  2783. :group 'org-agenda
  2784. :type '(choice
  2785. (repeat :tag "List of files and directories" file)
  2786. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2787. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2788. "Regular expression to match files for `org-agenda-files'.
  2789. If any element in the list in that variable contains a directory instead
  2790. of a normal file, all files in that directory that are matched by this
  2791. regular expression will be included."
  2792. :group 'org-agenda
  2793. :type 'regexp)
  2794. (defvaralias 'org-agenda-multi-occur-extra-files
  2795. 'org-agenda-text-search-extra-files)
  2796. (defcustom org-agenda-text-search-extra-files nil
  2797. "List of extra files to be searched by text search commands.
  2798. These files will be searched in addition to the agenda files by the
  2799. commands `org-search-view' (`\\[org-agenda] s') \
  2800. and `org-occur-in-agenda-files'.
  2801. Note that these files will only be searched for text search commands,
  2802. not for the other agenda views like todo lists, tag searches or the weekly
  2803. agenda. This variable is intended to list notes and possibly archive files
  2804. that should also be searched by these two commands.
  2805. In fact, if the first element in the list is the symbol `agenda-archives',
  2806. then all archive files of all agenda files will be added to the search
  2807. scope."
  2808. :group 'org-agenda
  2809. :type '(set :greedy t
  2810. (const :tag "Agenda Archives" agenda-archives)
  2811. (repeat :inline t (file))))
  2812. (defcustom org-agenda-skip-unavailable-files nil
  2813. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2814. A nil value means to remove them, after a query, from the list."
  2815. :group 'org-agenda
  2816. :type 'boolean)
  2817. (defcustom org-agenda-diary-file 'diary-file
  2818. "File to which to add new entries with the `i' key in agenda and calendar.
  2819. When this is the symbol `diary-file', the functionality in the Emacs
  2820. calendar will be used to add entries to the `diary-file'. But when this
  2821. points to a file, `org-agenda-diary-entry' will be used instead."
  2822. :group 'org-agenda
  2823. :type '(choice
  2824. (const :tag "The standard Emacs diary file" diary-file)
  2825. (file :tag "Special Org file diary entries")))
  2826. (defgroup org-latex nil
  2827. "Options for embedding LaTeX code into Org mode."
  2828. :tag "Org LaTeX"
  2829. :group 'org)
  2830. (defcustom org-format-latex-options
  2831. '(:foreground default :background default :scale 1.0
  2832. :html-foreground "Black" :html-background "Transparent"
  2833. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2834. "Options for creating images from LaTeX fragments.
  2835. This is a property list with the following properties:
  2836. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2837. `default' means use the foreground of the default face.
  2838. `auto' means use the foreground from the text face.
  2839. :background the background color, or \"Transparent\".
  2840. `default' means use the background of the default face.
  2841. `auto' means use the background from the text face.
  2842. :scale a scaling factor for the size of the images, to get more pixels
  2843. :html-foreground, :html-background, :html-scale
  2844. the same numbers for HTML export.
  2845. :matchers a list indicating which matchers should be used to
  2846. find LaTeX fragments. Valid members of this list are:
  2847. \"begin\" find environments
  2848. \"$1\" find single characters surrounded by $.$
  2849. \"$\" find math expressions surrounded by $...$
  2850. \"$$\" find math expressions surrounded by $$....$$
  2851. \"\\(\" find math expressions surrounded by \\(...\\)
  2852. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2853. :group 'org-latex
  2854. :type 'plist)
  2855. (defcustom org-format-latex-signal-error t
  2856. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2857. When nil, just push out a message."
  2858. :group 'org-latex
  2859. :version "24.1"
  2860. :type 'boolean)
  2861. (defcustom org-latex-to-mathml-jar-file nil
  2862. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2863. Use this to specify additional executable file say a jar file.
  2864. When using MathToWeb as the converter, specify the full-path to
  2865. your mathtoweb.jar file."
  2866. :group 'org-latex
  2867. :version "24.1"
  2868. :type '(choice
  2869. (const :tag "None" nil)
  2870. (file :tag "JAR file" :must-match t)))
  2871. (defcustom org-latex-to-mathml-convert-command nil
  2872. "Command to convert LaTeX fragments to MathML.
  2873. Replace format-specifiers in the command as noted below and use
  2874. `shell-command' to convert LaTeX to MathML.
  2875. %j: Executable file in fully expanded form as specified by
  2876. `org-latex-to-mathml-jar-file'.
  2877. %I: Input LaTeX file in fully expanded form.
  2878. %i: The latex fragment to be converted.
  2879. %o: Output MathML file.
  2880. This command is used by `org-create-math-formula'.
  2881. When using MathToWeb as the converter, set this option to
  2882. \"java -jar %j -unicode -force -df %o %I\".
  2883. When using LaTeXML set this option to
  2884. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2885. :group 'org-latex
  2886. :version "24.1"
  2887. :type '(choice
  2888. (const :tag "None" nil)
  2889. (string :tag "\nShell command")))
  2890. (defcustom org-preview-latex-default-process 'dvipng
  2891. "The default process to convert LaTeX fragments to image files.
  2892. All available processes and theirs documents can be found in
  2893. `org-preview-latex-process-alist', which see."
  2894. :group 'org-latex
  2895. :version "26.1"
  2896. :package-version '(Org . "9.0")
  2897. :type 'symbol)
  2898. (defcustom org-preview-latex-process-alist
  2899. '((dvipng
  2900. :programs ("latex" "dvipng")
  2901. :description "dvi > png"
  2902. :message "you need to install the programs: latex and dvipng."
  2903. :image-input-type "dvi"
  2904. :image-output-type "png"
  2905. :image-size-adjust (1.0 . 1.0)
  2906. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2907. :image-converter ("dvipng -D %D -T tight -o %O %f"))
  2908. (dvisvgm
  2909. :programs ("latex" "dvisvgm")
  2910. :description "dvi > svg"
  2911. :message "you need to install the programs: latex and dvisvgm."
  2912. :image-input-type "dvi"
  2913. :image-output-type "svg"
  2914. :image-size-adjust (1.7 . 1.5)
  2915. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2916. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2917. (imagemagick
  2918. :programs ("latex" "convert")
  2919. :description "pdf > png"
  2920. :message "you need to install the programs: latex and imagemagick."
  2921. :image-input-type "pdf"
  2922. :image-output-type "png"
  2923. :image-size-adjust (1.0 . 1.0)
  2924. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2925. :image-converter
  2926. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2927. "Definitions of external processes for LaTeX previewing.
  2928. Org mode can use some external commands to generate TeX snippet's images for
  2929. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2930. `org-create-formula-image' how to call them.
  2931. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2932. PROPERTIES accepts the following attributes:
  2933. :programs list of strings, required programs.
  2934. :description string, describe the process.
  2935. :message string, message it when required programs cannot be found.
  2936. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2937. :image-output-type string, output file type of image converter (e.g., \"png\").
  2938. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2939. image size showed in buffer and the cdr element is for
  2940. HTML file. This option is only useful for process
  2941. developers, users should use variable
  2942. `org-format-latex-options' instead.
  2943. :post-clean list of strings, files matched are to be cleaned up once
  2944. the image is generated. When nil, the files with \".dvi\",
  2945. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2946. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2947. be cleaned up.
  2948. :latex-header list of strings, the LaTeX header of the snippet file.
  2949. When nil, the fallback value is used instead, which is
  2950. controlled by `org-format-latex-header',
  2951. `org-latex-default-packages-alist' and
  2952. `org-latex-packages-alist', which see.
  2953. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2954. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2955. replaced with values defined below.
  2956. :image-converter list of image converter commands strings. Each of them is
  2957. given to the shell and supports any of the following
  2958. place-holders defined below.
  2959. Place-holders used by `:image-converter' and `:latex-compiler':
  2960. %f input file name
  2961. %b base name of input file
  2962. %o base directory of input file
  2963. %O absolute output file name
  2964. Place-holders only used by `:image-converter':
  2965. %D dpi, which is used to adjust image size by some processing commands.
  2966. %S the image size scale ratio, which is used to adjust image size by some
  2967. processing commands."
  2968. :group 'org-latex
  2969. :version "26.1"
  2970. :package-version '(Org . "9.0")
  2971. :type '(alist :tag "LaTeX to image backends"
  2972. :value-type (plist)))
  2973. (defcustom org-preview-latex-image-directory "ltximg/"
  2974. "Path to store latex preview images.
  2975. A relative path here creates many directories relative to the
  2976. processed Org files paths. An absolute path puts all preview
  2977. images at the same place."
  2978. :group 'org-latex
  2979. :version "26.1"
  2980. :package-version '(Org . "9.0")
  2981. :type 'string)
  2982. (defun org-format-latex-mathml-available-p ()
  2983. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2984. (save-match-data
  2985. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2986. org-latex-to-mathml-convert-command)
  2987. (let ((executable (car (split-string
  2988. org-latex-to-mathml-convert-command))))
  2989. (when (executable-find executable)
  2990. (if (string-match
  2991. "%j" org-latex-to-mathml-convert-command)
  2992. (file-readable-p org-latex-to-mathml-jar-file)
  2993. t))))))
  2994. (defcustom org-format-latex-header "\\documentclass{article}
  2995. \\usepackage[usenames]{color}
  2996. \[PACKAGES]
  2997. \[DEFAULT-PACKAGES]
  2998. \\pagestyle{empty} % do not remove
  2999. % The settings below are copied from fullpage.sty
  3000. \\setlength{\\textwidth}{\\paperwidth}
  3001. \\addtolength{\\textwidth}{-3cm}
  3002. \\setlength{\\oddsidemargin}{1.5cm}
  3003. \\addtolength{\\oddsidemargin}{-2.54cm}
  3004. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3005. \\setlength{\\textheight}{\\paperheight}
  3006. \\addtolength{\\textheight}{-\\headheight}
  3007. \\addtolength{\\textheight}{-\\headsep}
  3008. \\addtolength{\\textheight}{-\\footskip}
  3009. \\addtolength{\\textheight}{-3cm}
  3010. \\setlength{\\topmargin}{1.5cm}
  3011. \\addtolength{\\topmargin}{-2.54cm}"
  3012. "The document header used for processing LaTeX fragments.
  3013. It is imperative that this header make sure that no page number
  3014. appears on the page. The package defined in the variables
  3015. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3016. will either replace the placeholder \"[PACKAGES]\" in this
  3017. header, or they will be appended."
  3018. :group 'org-latex
  3019. :type 'string)
  3020. (defun org-set-packages-alist (var val)
  3021. "Set the packages alist and make sure it has 3 elements per entry."
  3022. (set var (mapcar (lambda (x)
  3023. (if (and (consp x) (= (length x) 2))
  3024. (list (car x) (nth 1 x) t)
  3025. x))
  3026. val)))
  3027. (defun org-get-packages-alist (var)
  3028. "Get the packages alist and make sure it has 3 elements per entry."
  3029. (mapcar (lambda (x)
  3030. (if (and (consp x) (= (length x) 2))
  3031. (list (car x) (nth 1 x) t)
  3032. x))
  3033. (default-value var)))
  3034. (defcustom org-latex-default-packages-alist
  3035. '(("AUTO" "inputenc" t ("pdflatex"))
  3036. ("T1" "fontenc" t ("pdflatex"))
  3037. ("" "graphicx" t)
  3038. ("" "grffile" t)
  3039. ("" "longtable" nil)
  3040. ("" "wrapfig" nil)
  3041. ("" "rotating" nil)
  3042. ("normalem" "ulem" t)
  3043. ("" "amsmath" t)
  3044. ("" "textcomp" t)
  3045. ("" "amssymb" t)
  3046. ("" "capt-of" nil)
  3047. ("" "hyperref" nil))
  3048. "Alist of default packages to be inserted in the header.
  3049. Change this only if one of the packages here causes an
  3050. incompatibility with another package you are using.
  3051. The packages in this list are needed by one part or another of
  3052. Org mode to function properly:
  3053. - inputenc, fontenc: for basic font and character selection
  3054. - graphicx: for including images
  3055. - grffile: allow periods and spaces in graphics file names
  3056. - longtable: For multipage tables
  3057. - wrapfig: for figure placement
  3058. - rotating: for sideways figures and tables
  3059. - ulem: for underline and strike-through
  3060. - amsmath: for subscript and superscript and math environments
  3061. - textcomp, amssymb: for various symbols used
  3062. for interpreting the entities in `org-entities'. You can skip
  3063. some of these packages if you don't use any of their symbols.
  3064. - capt-of: for captions outside of floats
  3065. - hyperref: for cross references
  3066. Therefore you should not modify this variable unless you know
  3067. what you are doing. The one reason to change it anyway is that
  3068. you might be loading some other package that conflicts with one
  3069. of the default packages. Each element is either a cell or
  3070. a string.
  3071. A cell is of the format
  3072. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3073. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3074. when compiling LaTeX snippets into images for inclusion into
  3075. non-LaTeX output.
  3076. COMPILERS is a list of compilers that should include the package,
  3077. see `org-latex-compiler'. If the document compiler is not in the
  3078. list, and the list is non-nil, the package will not be inserted
  3079. in the final document.
  3080. A string will be inserted as-is in the header of the document."
  3081. :group 'org-latex
  3082. :group 'org-export-latex
  3083. :set 'org-set-packages-alist
  3084. :get 'org-get-packages-alist
  3085. :version "26.1"
  3086. :package-version '(Org . "8.3")
  3087. :type '(repeat
  3088. (choice
  3089. (list :tag "options/package pair"
  3090. (string :tag "options")
  3091. (string :tag "package")
  3092. (boolean :tag "Snippet")
  3093. (choice
  3094. (const :tag "For all compilers" nil)
  3095. (repeat :tag "Allowed compiler" string)))
  3096. (string :tag "A line of LaTeX"))))
  3097. (defcustom org-latex-packages-alist nil
  3098. "Alist of packages to be inserted in every LaTeX header.
  3099. These will be inserted after `org-latex-default-packages-alist'.
  3100. Each element is either a cell or a string.
  3101. A cell is of the format:
  3102. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3103. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3104. needed when turning LaTeX snippets into images for inclusion into
  3105. non-LaTeX output.
  3106. COMPILERS is a list of compilers that should include the package,
  3107. see `org-latex-compiler'. If the document compiler is not in the
  3108. list, and the list is non-nil, the package will not be inserted
  3109. in the final document.
  3110. A string will be inserted as-is in the header of the document.
  3111. Make sure that you only list packages here which:
  3112. - you want in every file;
  3113. - do not conflict with the setup in `org-format-latex-header';
  3114. - do not conflict with the default packages in
  3115. `org-latex-default-packages-alist'."
  3116. :group 'org-latex
  3117. :group 'org-export-latex
  3118. :set 'org-set-packages-alist
  3119. :get 'org-get-packages-alist
  3120. :type '(repeat
  3121. (choice
  3122. (list :tag "options/package pair"
  3123. (string :tag "options")
  3124. (string :tag "package")
  3125. (boolean :tag "Snippet"))
  3126. (string :tag "A line of LaTeX"))))
  3127. (defgroup org-appearance nil
  3128. "Settings for Org mode appearance."
  3129. :tag "Org Appearance"
  3130. :group 'org)
  3131. (defcustom org-level-color-stars-only nil
  3132. "Non-nil means fontify only the stars in each headline.
  3133. When nil, the entire headline is fontified.
  3134. Changing it requires restart of `font-lock-mode' to become effective
  3135. also in regions already fontified."
  3136. :group 'org-appearance
  3137. :type 'boolean)
  3138. (defcustom org-hide-leading-stars nil
  3139. "Non-nil means hide the first N-1 stars in a headline.
  3140. This works by using the face `org-hide' for these stars. This
  3141. face is white for a light background, and black for a dark
  3142. background. You may have to customize the face `org-hide' to
  3143. make this work.
  3144. Changing it requires restart of `font-lock-mode' to become effective
  3145. also in regions already fontified.
  3146. You may also set this on a per-file basis by adding one of the following
  3147. lines to the buffer:
  3148. #+STARTUP: hidestars
  3149. #+STARTUP: showstars"
  3150. :group 'org-appearance
  3151. :type 'boolean)
  3152. (defcustom org-hidden-keywords nil
  3153. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3154. For example, a value \\='(title) for this list makes the document's title
  3155. appear in the buffer without the initial \"#+TITLE:\" part."
  3156. :group 'org-appearance
  3157. :version "24.1"
  3158. :type '(set (const :tag "#+AUTHOR" author)
  3159. (const :tag "#+DATE" date)
  3160. (const :tag "#+EMAIL" email)
  3161. (const :tag "#+TITLE" title)))
  3162. (defcustom org-custom-properties nil
  3163. "List of properties (as strings) with a special meaning.
  3164. The default use of these custom properties is to let the user
  3165. hide them with `org-toggle-custom-properties-visibility'."
  3166. :group 'org-properties
  3167. :group 'org-appearance
  3168. :version "24.3"
  3169. :type '(repeat (string :tag "Property Name")))
  3170. (defcustom org-fontify-todo-headline nil
  3171. "Non-nil means change the face of a headline if it is marked as TODO.
  3172. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3173. When this is non-nil, the headline after the keyword is set to the
  3174. `org-headline-todo' as an additional indication."
  3175. :group 'org-appearance
  3176. :package-version '(Org . "9.4")
  3177. :type 'boolean
  3178. :safe t)
  3179. (defcustom org-fontify-done-headline nil
  3180. "Non-nil means change the face of a headline if it is marked DONE.
  3181. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3182. When this is non-nil, the headline after the keyword is set to the
  3183. `org-headline-done' as an additional indication."
  3184. :group 'org-appearance
  3185. :type 'boolean)
  3186. (defcustom org-fontify-emphasized-text t
  3187. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3188. Changing this variable requires a restart of Emacs to take effect."
  3189. :group 'org-appearance
  3190. :type 'boolean)
  3191. (defcustom org-fontify-whole-heading-line nil
  3192. "Non-nil means fontify the whole line for headings.
  3193. This is useful when setting a background color for the
  3194. org-level-* faces."
  3195. :group 'org-appearance
  3196. :type 'boolean)
  3197. (defcustom org-fontify-whole-block-delimiter-line t
  3198. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3199. This is useful when setting a background color for the
  3200. org-block-begin-line and org-block-end-line faces."
  3201. :group 'org-appearance
  3202. :type 'boolean)
  3203. (defcustom org-highlight-latex-and-related nil
  3204. "Non-nil means highlight LaTeX related syntax in the buffer.
  3205. When non-nil, the value should be a list containing any of the
  3206. following symbols:
  3207. `native' Highlight LaTeX snippets and environments natively.
  3208. `latex' Highlight LaTeX snippets and environments.
  3209. `script' Highlight subscript and superscript.
  3210. `entities' Highlight entities."
  3211. :group 'org-appearance
  3212. :version "24.4"
  3213. :package-version '(Org . "8.0")
  3214. :type '(choice
  3215. (const :tag "No highlighting" nil)
  3216. (set :greedy t :tag "Highlight"
  3217. (const :tag "LaTeX snippets and environments (native)" native)
  3218. (const :tag "LaTeX snippets and environments" latex)
  3219. (const :tag "Subscript and superscript" script)
  3220. (const :tag "Entities" entities))))
  3221. (defcustom org-hide-emphasis-markers nil
  3222. "Non-nil mean font-lock should hide the emphasis marker characters."
  3223. :group 'org-appearance
  3224. :type 'boolean
  3225. :safe #'booleanp)
  3226. (defcustom org-hide-macro-markers nil
  3227. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3228. :group 'org-appearance
  3229. :type 'boolean)
  3230. (defcustom org-pretty-entities nil
  3231. "Non-nil means show entities as UTF8 characters.
  3232. When nil, the \\name form remains in the buffer."
  3233. :group 'org-appearance
  3234. :version "24.1"
  3235. :type 'boolean)
  3236. (defcustom org-pretty-entities-include-sub-superscripts t
  3237. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3238. :group 'org-appearance
  3239. :version "24.1"
  3240. :type 'boolean)
  3241. (defvar org-emph-re nil
  3242. "Regular expression for matching emphasis.
  3243. After a match, the match groups contain these elements:
  3244. 0 The match of the full regular expression, including the characters
  3245. before and after the proper match
  3246. 1 The character before the proper match, or empty at beginning of line
  3247. 2 The proper match, including the leading and trailing markers
  3248. 3 The leading marker like * or /, indicating the type of highlighting
  3249. 4 The text between the emphasis markers, not including the markers
  3250. 5 The character after the match, empty at the end of a line")
  3251. (defvar org-verbatim-re nil
  3252. "Regular expression for matching verbatim text.")
  3253. (defvar org-emphasis-regexp-components) ; defined just below
  3254. (defvar org-emphasis-alist) ; defined just below
  3255. (defun org-set-emph-re (var val)
  3256. "Set variable and compute the emphasis regular expression."
  3257. (set var val)
  3258. (when (and (boundp 'org-emphasis-alist)
  3259. (boundp 'org-emphasis-regexp-components)
  3260. org-emphasis-alist org-emphasis-regexp-components)
  3261. (pcase-let*
  3262. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3263. (body (if (<= nl 0) body
  3264. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3265. (template
  3266. (format (concat "\\([%s]\\|^\\)" ;before markers
  3267. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3268. "\\([%s]\\|$\\)") ;after markers
  3269. pre border border body border post)))
  3270. (setq org-emph-re (format template "*/_+"))
  3271. (setq org-verbatim-re (format template "=~")))))
  3272. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3273. ;; set this option proved cumbersome. See this message/thread:
  3274. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3275. (defvar org-emphasis-regexp-components
  3276. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3277. "Components used to build the regular expression for emphasis.
  3278. This is a list with five entries. Terminology: In an emphasis string
  3279. like \" *strong word* \", we call the initial space PREMATCH, the final
  3280. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3281. and \"trong wor\" is the body. The different components in this variable
  3282. specify what is allowed/forbidden in each part:
  3283. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3284. post Chars allowed as postmatch. End of line will be allowed too.
  3285. border The chars *forbidden* as border characters.
  3286. body-regexp A regexp like \".\" to match a body character. Don't use
  3287. non-shy groups here, and don't allow newline here.
  3288. newline The maximum number of newlines allowed in an emphasis exp.
  3289. You need to reload Org or to restart Emacs after setting this.")
  3290. (defcustom org-emphasis-alist
  3291. '(("*" bold)
  3292. ("/" italic)
  3293. ("_" underline)
  3294. ("=" org-verbatim verbatim)
  3295. ("~" org-code verbatim)
  3296. ("+" (:strike-through t)))
  3297. "Alist of characters and faces to emphasize text.
  3298. Text starting and ending with a special character will be emphasized,
  3299. for example *bold*, _underlined_ and /italic/. This variable sets the
  3300. marker characters and the face to be used by font-lock for highlighting
  3301. in Org buffers.
  3302. You need to reload Org or to restart Emacs after customizing this."
  3303. :group 'org-appearance
  3304. :set 'org-set-emph-re
  3305. :version "24.4"
  3306. :package-version '(Org . "8.0")
  3307. :type '(repeat
  3308. (list
  3309. (string :tag "Marker character")
  3310. (choice
  3311. (face :tag "Font-lock-face")
  3312. (plist :tag "Face property list"))
  3313. (option (const verbatim)))))
  3314. (defvar org-protecting-blocks '("src" "example" "export")
  3315. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3316. This is needed for font-lock setup.")
  3317. ;;; Functions and variables from their packages
  3318. ;; Declared here to avoid compiler warnings
  3319. (defvar mark-active)
  3320. ;; Various packages
  3321. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3322. (declare-function calendar-forward-day "cal-move" (arg))
  3323. (declare-function calendar-goto-date "cal-move" (date))
  3324. (declare-function calendar-goto-today "cal-move" ())
  3325. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3326. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3327. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3328. (declare-function cdlatex-tab "ext:cdlatex" ())
  3329. (declare-function dired-get-filename
  3330. "dired"
  3331. (&optional localp no-error-if-not-filep))
  3332. (declare-function iswitchb-read-buffer
  3333. "iswitchb"
  3334. (prompt &optional
  3335. default require-match _predicate start matches-set))
  3336. (declare-function org-agenda-change-all-lines
  3337. "org-agenda"
  3338. (newhead hdmarker &optional fixface just-this))
  3339. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3340. "org-agenda"
  3341. (&optional end))
  3342. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3343. (declare-function org-agenda-format-item
  3344. "org-agenda"
  3345. (extra txt &optional level category tags dotime
  3346. remove-re habitp))
  3347. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3348. (declare-function org-agenda-save-markers-for-cut-and-paste
  3349. "org-agenda"
  3350. (beg end))
  3351. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3352. (declare-function org-agenda-skip "org-agenda" ())
  3353. (declare-function org-attach-expand "org-attach" (file))
  3354. (declare-function org-attach-reveal "org-attach" ())
  3355. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3356. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3357. (declare-function org-indent-mode "org-indent" (&optional arg))
  3358. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3359. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3360. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3361. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3362. (declare-function parse-time-string "parse-time" (string))
  3363. (defvar align-mode-rules-list)
  3364. (defvar calc-embedded-close-formula)
  3365. (defvar calc-embedded-open-formula)
  3366. (defvar calc-embedded-open-mode)
  3367. (defvar font-lock-unfontify-region-function)
  3368. (defvar iswitchb-temp-buflist)
  3369. (defvar org-agenda-tags-todo-honor-ignore-options)
  3370. (defvar remember-data-file)
  3371. (defvar texmathp-why)
  3372. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3373. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3374. (declare-function org-resolve-clocks "org-clock"
  3375. (&optional also-non-dangling-p prompt last-valid))
  3376. (defvar org-clock-start-time)
  3377. (defvar org-clock-marker (make-marker)
  3378. "Marker recording the last clock-in.")
  3379. (defvar org-clock-hd-marker (make-marker)
  3380. "Marker recording the last clock-in, but the headline position.")
  3381. (defvar org-clock-heading ""
  3382. "The heading of the current clock entry.")
  3383. (defun org-clock-is-active ()
  3384. "Return the buffer where the clock is currently running.
  3385. Return nil if no clock is running."
  3386. (marker-buffer org-clock-marker))
  3387. (defun org-check-running-clock ()
  3388. "Check if the current buffer contains the running clock.
  3389. If yes, offer to stop it and to save the buffer with the changes."
  3390. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3391. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3392. (buffer-name))))
  3393. (org-clock-out)
  3394. (when (y-or-n-p "Save changed buffer?")
  3395. (save-buffer))))
  3396. (defun org-clocktable-try-shift (dir n)
  3397. "Check if this line starts a clock table, if yes, shift the time block."
  3398. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3399. (org-clocktable-shift dir n)))
  3400. ;;;###autoload
  3401. (defun org-clock-persistence-insinuate ()
  3402. "Set up hooks for clock persistence."
  3403. (require 'org-clock)
  3404. (add-hook 'org-mode-hook 'org-clock-load)
  3405. (add-hook 'kill-emacs-hook 'org-clock-save))
  3406. (defgroup org-archive nil
  3407. "Options concerning archiving in Org mode."
  3408. :tag "Org Archive"
  3409. :group 'org-structure)
  3410. (defcustom org-archive-location "%s_archive::"
  3411. "The location where subtrees should be archived.
  3412. The value of this variable is a string, consisting of two parts,
  3413. separated by a double-colon. The first part is a filename and
  3414. the second part is a headline.
  3415. When the filename is omitted, archiving happens in the same file.
  3416. %s in the filename will be replaced by the current file
  3417. name (without the directory part). Archiving to a different file
  3418. is useful to keep archived entries from contributing to the
  3419. Org Agenda.
  3420. The archived entries will be filed as subtrees of the specified
  3421. headline. When the headline is omitted, the subtrees are simply
  3422. filed away at the end of the file, as top-level entries. Also in
  3423. the heading you can use %s to represent the file name, this can be
  3424. useful when using the same archive for a number of different files.
  3425. Here are a few examples:
  3426. \"%s_archive::\"
  3427. If the current file is Projects.org, archive in file
  3428. Projects.org_archive, as top-level trees. This is the default.
  3429. \"::* Archived Tasks\"
  3430. Archive in the current file, under the top-level headline
  3431. \"* Archived Tasks\".
  3432. \"~/org/archive.org::\"
  3433. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3434. \"~/org/archive.org::* From %s\"
  3435. Archive in file ~/org/archive.org (absolute path), under headlines
  3436. \"From FILENAME\" where file name is the current file name.
  3437. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3438. The \"datetree/\" string is special, signifying to archive
  3439. items to the datetree. Items are placed in either the CLOSED
  3440. date of the item, or the current date if there is no CLOSED date.
  3441. The heading will be a subentry to the current date. There doesn't
  3442. need to be a heading, but there always needs to be a slash after
  3443. datetree. For example, to store archived items directly in the
  3444. datetree, use \"~/org/datetree.org::datetree/\".
  3445. \"basement::** Finished Tasks\"
  3446. Archive in file ./basement (relative path), as level 3 trees
  3447. below the level 2 heading \"** Finished Tasks\".
  3448. You may define it locally by setting an ARCHIVE property. If
  3449. such a property is found in the file or in an entry, and anywhere
  3450. up the hierarchy, it will be used.
  3451. You can also set it for the whole file using the keyword-syntax:
  3452. #+ARCHIVE: basement::** Finished Tasks"
  3453. :group 'org-archive
  3454. :type 'string)
  3455. (defcustom org-agenda-skip-archived-trees t
  3456. "Non-nil means the agenda will skip any items located in archived trees.
  3457. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3458. variable is no longer recommended, you should leave it at the value t.
  3459. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3460. :group 'org-archive
  3461. :group 'org-agenda-skip
  3462. :type 'boolean)
  3463. (defcustom org-columns-skip-archived-trees t
  3464. "Non-nil means ignore archived trees when creating column view."
  3465. :group 'org-archive
  3466. :group 'org-properties
  3467. :type 'boolean)
  3468. (defcustom org-cycle-open-archived-trees nil
  3469. "Non-nil means `org-cycle' will open archived trees.
  3470. An archived tree is a tree marked with the tag ARCHIVE.
  3471. When nil, archived trees will stay folded. You can still open them with
  3472. normal outline commands like `show-all', but not with the cycling commands."
  3473. :group 'org-archive
  3474. :group 'org-cycle
  3475. :type 'boolean)
  3476. (defcustom org-sparse-tree-open-archived-trees nil
  3477. "Non-nil means sparse tree construction shows matches in archived trees.
  3478. When nil, matches in these trees are highlighted, but the trees are kept in
  3479. collapsed state."
  3480. :group 'org-archive
  3481. :group 'org-sparse-trees
  3482. :type 'boolean)
  3483. (defcustom org-sparse-tree-default-date-type nil
  3484. "The default date type when building a sparse tree.
  3485. When this is nil, a date is a scheduled or a deadline timestamp.
  3486. Otherwise, these types are allowed:
  3487. all: all timestamps
  3488. active: only active timestamps (<...>)
  3489. inactive: only inactive timestamps ([...])
  3490. scheduled: only scheduled timestamps
  3491. deadline: only deadline timestamps"
  3492. :type '(choice (const :tag "Scheduled or deadline" nil)
  3493. (const :tag "All timestamps" all)
  3494. (const :tag "Only active timestamps" active)
  3495. (const :tag "Only inactive timestamps" inactive)
  3496. (const :tag "Only scheduled timestamps" scheduled)
  3497. (const :tag "Only deadline timestamps" deadline)
  3498. (const :tag "Only closed timestamps" closed))
  3499. :version "26.1"
  3500. :package-version '(Org . "8.3")
  3501. :group 'org-sparse-trees)
  3502. (defun org-cycle-hide-archived-subtrees (state)
  3503. "Re-hide all archived subtrees after a visibility state change.
  3504. STATE should be one of the symbols listed in the docstring of
  3505. `org-cycle-hook'."
  3506. (when (and (not org-cycle-open-archived-trees)
  3507. (not (memq state '(overview folded))))
  3508. (save-excursion
  3509. (let* ((globalp (memq state '(contents all)))
  3510. (beg (if globalp (point-min) (point)))
  3511. (end (if globalp (point-max) (org-end-of-subtree t))))
  3512. (org-hide-archived-subtrees beg end)
  3513. (goto-char beg)
  3514. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3515. (message "%s" (substitute-command-keys
  3516. "Subtree is archived and stays closed. Use \
  3517. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3518. (defun org-force-cycle-archived ()
  3519. "Cycle subtree even if it is archived."
  3520. (interactive)
  3521. (setq this-command 'org-cycle)
  3522. (let ((org-cycle-open-archived-trees t))
  3523. (call-interactively 'org-cycle)))
  3524. (defun org-hide-archived-subtrees (beg end)
  3525. "Re-hide all archived subtrees after a visibility state change."
  3526. (org-with-wide-buffer
  3527. (let ((case-fold-search nil)
  3528. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3529. (goto-char beg)
  3530. ;; Include headline point is currently on.
  3531. (beginning-of-line)
  3532. (while (and (< (point) end) (re-search-forward re end t))
  3533. (when (member org-archive-tag (org-get-tags nil t))
  3534. (org-flag-subtree t)
  3535. (org-end-of-subtree t))))))
  3536. (defun org-flag-subtree (flag)
  3537. (save-excursion
  3538. (org-back-to-heading t)
  3539. (org-flag-region (line-end-position)
  3540. (progn (org-end-of-subtree t) (point))
  3541. flag
  3542. 'outline)))
  3543. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3544. ;; Declare Column View Code
  3545. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3546. (declare-function org-columns-compute "org-colview" (property))
  3547. ;; Declare ID code
  3548. (declare-function org-id-store-link "org-id")
  3549. (declare-function org-id-locations-load "org-id")
  3550. (declare-function org-id-locations-save "org-id")
  3551. (defvar org-id-track-globally)
  3552. ;;; Variables for pre-computed regular expressions, all buffer local
  3553. (defvar-local org-todo-regexp nil
  3554. "Matches any of the TODO state keywords.
  3555. Since TODO keywords are case-sensitive, `case-fold-search' is
  3556. expected to be bound to nil when matching against this regexp.")
  3557. (defvar-local org-not-done-regexp nil
  3558. "Matches any of the TODO state keywords except the last one.
  3559. Since TODO keywords are case-sensitive, `case-fold-search' is
  3560. expected to be bound to nil when matching against this regexp.")
  3561. (defvar-local org-not-done-heading-regexp nil
  3562. "Matches a TODO headline that is not done.
  3563. Since TODO keywords are case-sensitive, `case-fold-search' is
  3564. expected to be bound to nil when matching against this regexp.")
  3565. (defvar-local org-todo-line-regexp nil
  3566. "Matches a headline and puts TODO state into group 2 if present.
  3567. Since TODO keywords are case-sensitive, `case-fold-search' is
  3568. expected to be bound to nil when matching against this regexp.")
  3569. (defvar-local org-complex-heading-regexp nil
  3570. "Matches a headline and puts everything into groups:
  3571. group 1: Stars
  3572. group 2: The TODO keyword, maybe
  3573. group 3: Priority cookie
  3574. group 4: True headline
  3575. group 5: Tags
  3576. Since TODO keywords are case-sensitive, `case-fold-search' is
  3577. expected to be bound to nil when matching against this regexp.")
  3578. (defvar-local org-complex-heading-regexp-format nil
  3579. "Printf format to make regexp to match an exact headline.
  3580. This regexp will match the headline of any node which has the
  3581. exact headline text that is put into the format, but may have any
  3582. TODO state, priority and tags.")
  3583. (defvar-local org-todo-line-tags-regexp nil
  3584. "Matches a headline and puts TODO state into group 2 if present.
  3585. Also put tags into group 4 if tags are present.")
  3586. (defconst org-plain-time-of-day-regexp
  3587. (concat
  3588. "\\(\\<[012]?[0-9]"
  3589. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3590. "\\(--?"
  3591. "\\(\\<[012]?[0-9]"
  3592. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3593. "\\)?")
  3594. "Regular expression to match a plain time or time range.
  3595. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3596. groups carry important information:
  3597. 0 the full match
  3598. 1 the first time, range or not
  3599. 8 the second time, if it is a range.")
  3600. (defconst org-plain-time-extension-regexp
  3601. (concat
  3602. "\\(\\<[012]?[0-9]"
  3603. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3604. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3605. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3606. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3607. groups carry important information:
  3608. 0 the full match
  3609. 7 hours of duration
  3610. 9 minutes of duration")
  3611. (defconst org-stamp-time-of-day-regexp
  3612. (concat
  3613. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3614. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  3615. "\\(--?"
  3616. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3617. "Regular expression to match a timestamp time or time range.
  3618. After a match, the following groups carry important information:
  3619. 0 the full match
  3620. 1 date plus weekday, for back referencing to make sure both times are on the same day
  3621. 2 the first time, range or not
  3622. 4 the second time, if it is a range.")
  3623. (defconst org-startup-options
  3624. '(("fold" org-startup-folded t)
  3625. ("overview" org-startup-folded t)
  3626. ("nofold" org-startup-folded nil)
  3627. ("showall" org-startup-folded nil)
  3628. ("showeverything" org-startup-folded showeverything)
  3629. ("content" org-startup-folded content)
  3630. ("indent" org-startup-indented t)
  3631. ("noindent" org-startup-indented nil)
  3632. ("hidestars" org-hide-leading-stars t)
  3633. ("showstars" org-hide-leading-stars nil)
  3634. ("odd" org-odd-levels-only t)
  3635. ("oddeven" org-odd-levels-only nil)
  3636. ("align" org-startup-align-all-tables t)
  3637. ("noalign" org-startup-align-all-tables nil)
  3638. ("shrink" org-startup-shrink-all-tables t)
  3639. ("inlineimages" org-startup-with-inline-images t)
  3640. ("noinlineimages" org-startup-with-inline-images nil)
  3641. ("latexpreview" org-startup-with-latex-preview t)
  3642. ("nolatexpreview" org-startup-with-latex-preview nil)
  3643. ("customtime" org-display-custom-times t)
  3644. ("logdone" org-log-done time)
  3645. ("lognotedone" org-log-done note)
  3646. ("nologdone" org-log-done nil)
  3647. ("lognoteclock-out" org-log-note-clock-out t)
  3648. ("nolognoteclock-out" org-log-note-clock-out nil)
  3649. ("logrepeat" org-log-repeat state)
  3650. ("lognoterepeat" org-log-repeat note)
  3651. ("logdrawer" org-log-into-drawer t)
  3652. ("nologdrawer" org-log-into-drawer nil)
  3653. ("logstatesreversed" org-log-states-order-reversed t)
  3654. ("nologstatesreversed" org-log-states-order-reversed nil)
  3655. ("nologrepeat" org-log-repeat nil)
  3656. ("logreschedule" org-log-reschedule time)
  3657. ("lognotereschedule" org-log-reschedule note)
  3658. ("nologreschedule" org-log-reschedule nil)
  3659. ("logredeadline" org-log-redeadline time)
  3660. ("lognoteredeadline" org-log-redeadline note)
  3661. ("nologredeadline" org-log-redeadline nil)
  3662. ("logrefile" org-log-refile time)
  3663. ("lognoterefile" org-log-refile note)
  3664. ("nologrefile" org-log-refile nil)
  3665. ("fninline" org-footnote-define-inline t)
  3666. ("nofninline" org-footnote-define-inline nil)
  3667. ("fnlocal" org-footnote-section nil)
  3668. ("fnauto" org-footnote-auto-label t)
  3669. ("fnprompt" org-footnote-auto-label nil)
  3670. ("fnconfirm" org-footnote-auto-label confirm)
  3671. ("fnplain" org-footnote-auto-label plain)
  3672. ("fnadjust" org-footnote-auto-adjust t)
  3673. ("nofnadjust" org-footnote-auto-adjust nil)
  3674. ("constcgs" constants-unit-system cgs)
  3675. ("constSI" constants-unit-system SI)
  3676. ("noptag" org-tag-persistent-alist nil)
  3677. ("hideblocks" org-hide-block-startup t)
  3678. ("nohideblocks" org-hide-block-startup nil)
  3679. ("beamer" org-startup-with-beamer-mode t)
  3680. ("entitiespretty" org-pretty-entities t)
  3681. ("entitiesplain" org-pretty-entities nil))
  3682. "Variable associated with STARTUP options for Org.
  3683. Each element is a list of three items: the startup options (as written
  3684. in the #+STARTUP line), the corresponding variable, and the value to set
  3685. this variable to if the option is found. An optional forth element PUSH
  3686. means to push this value onto the list in the variable.")
  3687. (defcustom org-group-tags t
  3688. "When non-nil (the default), use group tags.
  3689. This can be turned on/off through `org-toggle-tags-groups'."
  3690. :group 'org-tags
  3691. :group 'org-startup
  3692. :type 'boolean)
  3693. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3694. (defun org-toggle-tags-groups ()
  3695. "Toggle support for group tags.
  3696. Support for group tags is controlled by the option
  3697. `org-group-tags', which is non-nil by default."
  3698. (interactive)
  3699. (setq org-group-tags (not org-group-tags))
  3700. (cond ((and (derived-mode-p 'org-agenda-mode)
  3701. org-group-tags)
  3702. (org-agenda-redo))
  3703. ((derived-mode-p 'org-mode)
  3704. (let ((org-inhibit-startup t)) (org-mode))))
  3705. (message "Groups tags support has been turned %s"
  3706. (if org-group-tags "on" "off")))
  3707. (defun org--tag-add-to-alist (alist1 alist2)
  3708. "Merge tags from ALIST1 into ALIST2.
  3709. Duplicates tags outside a group are removed. Keywords and order
  3710. are preserved.
  3711. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3712. See `org-tag-alist' for their structure."
  3713. (cond
  3714. ((null alist2) alist1)
  3715. ((null alist1) alist2)
  3716. (t
  3717. (let ((to-add nil)
  3718. (group-flag nil))
  3719. (dolist (tag-pair alist1)
  3720. (pcase tag-pair
  3721. (`(,(or :startgrouptag :startgroup))
  3722. (setq group-flag t)
  3723. (push tag-pair to-add))
  3724. (`(,(or :endgrouptag :endgroup))
  3725. (setq group-flag nil)
  3726. (push tag-pair to-add))
  3727. (`(,(or :grouptags :newline))
  3728. (push tag-pair to-add))
  3729. (`(,tag . ,_)
  3730. ;; Remove duplicates from ALIST1, unless they are in
  3731. ;; a group. Indeed, it makes sense to have a tag appear in
  3732. ;; multiple groups.
  3733. (when (or group-flag (not (assoc tag alist2)))
  3734. (push tag-pair to-add)))
  3735. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3736. ;; Preserve order of ALIST1.
  3737. (append (nreverse to-add) alist2)))))
  3738. (defun org-set-regexps-and-options (&optional tags-only)
  3739. "Precompute regular expressions used in the current buffer.
  3740. When optional argument TAGS-ONLY is non-nil, only compute tags
  3741. related expressions."
  3742. (when (derived-mode-p 'org-mode)
  3743. (let ((alist (org--setup-collect-keywords
  3744. (org-make-options-regexp
  3745. (append '("FILETAGS" "TAGS" "SETUPFILE")
  3746. (and (not tags-only)
  3747. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3748. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3749. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  3750. ;; Startup options. Get this early since it does change
  3751. ;; behavior for other options (e.g., tags).
  3752. (let ((startup (cdr (assq 'startup alist))))
  3753. (dolist (option startup)
  3754. (let ((entry (assoc-string option org-startup-options t)))
  3755. (when entry
  3756. (let ((var (nth 1 entry))
  3757. (val (nth 2 entry)))
  3758. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  3759. (unless (listp (symbol-value var))
  3760. (set (make-local-variable var) nil))
  3761. (add-to-list var val)))))))
  3762. (setq-local org-file-tags
  3763. (mapcar #'org-add-prop-inherited
  3764. (cdr (assq 'filetags alist))))
  3765. (setq org-current-tag-alist
  3766. (org--tag-add-to-alist
  3767. org-tag-persistent-alist
  3768. (let ((tags (cdr (assq 'tags alist))))
  3769. (if tags (org-tag-string-to-alist tags)
  3770. org-tag-alist))))
  3771. (setq org-tag-groups-alist
  3772. (org-tag-alist-to-groups org-current-tag-alist))
  3773. (unless tags-only
  3774. ;; Properties.
  3775. (setq-local org-keyword-properties (cdr (assq 'property alist)))
  3776. ;; Archive location.
  3777. (let ((archive (cdr (assq 'archive alist))))
  3778. (when archive (setq-local org-archive-location archive)))
  3779. ;; Category.
  3780. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  3781. (when cat
  3782. (setq-local org-category (intern cat))
  3783. (setq-local org-keyword-properties
  3784. (org--update-property-plist
  3785. "CATEGORY" cat org-keyword-properties))))
  3786. ;; Columns.
  3787. (let ((column (cdr (assq 'columns alist))))
  3788. (when column (setq-local org-columns-default-format column)))
  3789. ;; Constants.
  3790. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  3791. ;; Link abbreviations.
  3792. (let ((links (cdr (assq 'link alist))))
  3793. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3794. ;; Priorities.
  3795. (let ((priorities (cdr (assq 'priorities alist))))
  3796. (when priorities
  3797. (setq-local org-priority-highest (nth 0 priorities))
  3798. (setq-local org-priority-lowest (nth 1 priorities))
  3799. (setq-local org-priority-default (nth 2 priorities))))
  3800. ;; Scripts.
  3801. (let ((scripts (assq 'scripts alist)))
  3802. (when scripts
  3803. (setq-local org-use-sub-superscripts (cdr scripts))))
  3804. ;; TODO keywords.
  3805. (setq-local org-todo-kwd-alist nil)
  3806. (setq-local org-todo-key-alist nil)
  3807. (setq-local org-todo-key-trigger nil)
  3808. (setq-local org-todo-keywords-1 nil)
  3809. (setq-local org-done-keywords nil)
  3810. (setq-local org-todo-heads nil)
  3811. (setq-local org-todo-sets nil)
  3812. (setq-local org-todo-log-states nil)
  3813. (let ((todo-sequences
  3814. (or (nreverse (cdr (assq 'todo alist)))
  3815. (let ((d (default-value 'org-todo-keywords)))
  3816. (if (not (stringp (car d))) d
  3817. ;; XXX: Backward compatibility code.
  3818. (list (cons org-todo-interpretation d)))))))
  3819. (dolist (sequence todo-sequences)
  3820. (let* ((sequence (or (run-hook-with-args-until-success
  3821. 'org-todo-setup-filter-hook sequence)
  3822. sequence))
  3823. (sequence-type (car sequence))
  3824. (keywords (cdr sequence))
  3825. (sep (member "|" keywords))
  3826. names alist)
  3827. (dolist (k (remove "|" keywords))
  3828. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3829. k)
  3830. (error "Invalid TODO keyword %s" k))
  3831. (let ((name (match-string 1 k))
  3832. (key (match-string 2 k))
  3833. (log (org-extract-log-state-settings k)))
  3834. (push name names)
  3835. (push (cons name (and key (string-to-char key))) alist)
  3836. (when log (push log org-todo-log-states))))
  3837. (let* ((names (nreverse names))
  3838. (done (if sep (org-remove-keyword-keys (cdr sep))
  3839. (last names)))
  3840. (head (car names))
  3841. (tail (list sequence-type head (car done) (org-last done))))
  3842. (add-to-list 'org-todo-heads head 'append)
  3843. (push names org-todo-sets)
  3844. (setq org-done-keywords (append org-done-keywords done nil))
  3845. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3846. (setq org-todo-key-alist
  3847. (append org-todo-key-alist
  3848. (and alist
  3849. (append '((:startgroup))
  3850. (nreverse alist)
  3851. '((:endgroup))))))
  3852. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3853. (setq org-todo-sets (nreverse org-todo-sets)
  3854. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3855. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3856. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3857. ;; Compute the regular expressions and other local variables.
  3858. ;; Using `org-outline-regexp-bol' would complicate them much,
  3859. ;; because of the fixed white space at the end of that string.
  3860. (unless org-done-keywords
  3861. (setq org-done-keywords
  3862. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3863. (setq org-not-done-keywords
  3864. (org-delete-all org-done-keywords
  3865. (copy-sequence org-todo-keywords-1))
  3866. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3867. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3868. org-not-done-heading-regexp
  3869. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3870. org-todo-line-regexp
  3871. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3872. org-complex-heading-regexp
  3873. (concat "^\\(\\*+\\)"
  3874. "\\(?: +" org-todo-regexp "\\)?"
  3875. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3876. "\\(?: +\\(.*?\\)\\)??"
  3877. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3878. "[ \t]*$")
  3879. org-complex-heading-regexp-format
  3880. (concat "^\\(\\*+\\)"
  3881. "\\(?: +" org-todo-regexp "\\)?"
  3882. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3883. "\\(?: +"
  3884. ;; Stats cookies can be stuck to body.
  3885. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3886. "\\(%s\\)"
  3887. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3888. "\\)"
  3889. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3890. "[ \t]*$")
  3891. org-todo-line-tags-regexp
  3892. (concat "^\\(\\*+\\)"
  3893. "\\(?: +" org-todo-regexp "\\)?"
  3894. "\\(?: +\\(.*?\\)\\)??"
  3895. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3896. "[ \t]*$"))
  3897. (org-compute-latex-and-related-regexp)))))
  3898. (defun org--setup-collect-keywords (regexp &optional files alist)
  3899. "Return setup keywords values as an alist.
  3900. REGEXP matches a subset of setup keywords. FILES is a list of
  3901. file names already visited. It is used to avoid circular setup
  3902. files. ALIST, when non-nil, is the alist computed so far.
  3903. Return value contains the following keys: `archive', `category',
  3904. `columns', `constants', `filetags', `link', `priorities',
  3905. `property', `scripts', `startup', `tags' and `todo'."
  3906. (org-with-wide-buffer
  3907. (goto-char (point-min))
  3908. (let ((case-fold-search t))
  3909. (while (re-search-forward regexp nil t)
  3910. (let ((element (org-element-at-point)))
  3911. (when (eq (org-element-type element) 'keyword)
  3912. (let ((key (org-element-property :key element))
  3913. (value (org-element-property :value element)))
  3914. (cond
  3915. ((equal key "ARCHIVE")
  3916. (when (org-string-nw-p value)
  3917. (push (cons 'archive value) alist)))
  3918. ((equal key "CATEGORY") (push (cons 'category value) alist))
  3919. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  3920. ((equal key "CONSTANTS")
  3921. (let* ((constants (assq 'constants alist))
  3922. (store (cdr constants)))
  3923. (dolist (pair (split-string value))
  3924. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  3925. pair)
  3926. (let* ((name (match-string 1 pair))
  3927. (value (match-string 2 pair))
  3928. (old (assoc name store)))
  3929. (if old (setcdr old value)
  3930. (push (cons name value) store)))))
  3931. (if constants (setcdr constants store)
  3932. (push (cons 'constants store) alist))))
  3933. ((equal key "FILETAGS")
  3934. (when (org-string-nw-p value)
  3935. (let ((old (assq 'filetags alist))
  3936. (new (apply #'nconc
  3937. (mapcar (lambda (x) (org-split-string x ":"))
  3938. (split-string value)))))
  3939. (if old (setcdr old (append new (cdr old)))
  3940. (push (cons 'filetags new) alist)))))
  3941. ((equal key "LINK")
  3942. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3943. (let ((links (assq 'link alist))
  3944. (pair (cons (match-string-no-properties 1 value)
  3945. (match-string-no-properties 2 value))))
  3946. (if links (push pair (cdr links))
  3947. (push (list 'link pair) alist)))))
  3948. ((equal key "OPTIONS")
  3949. (when (and (org-string-nw-p value)
  3950. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  3951. (push (cons 'scripts (read (match-string 1 value))) alist)))
  3952. ((equal key "PRIORITIES")
  3953. (push (cons 'priorities
  3954. (let ((prio (split-string value)))
  3955. (if (< (length prio) 3) '(?A ?C ?B)
  3956. (mapcar #'string-to-char prio))))
  3957. alist))
  3958. ((equal key "PROPERTY")
  3959. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3960. (let* ((property (assq 'property alist))
  3961. (value (org--update-property-plist
  3962. (match-string-no-properties 1 value)
  3963. (match-string-no-properties 2 value)
  3964. (cdr property))))
  3965. (if property (setcdr property value)
  3966. (push (cons 'property value) alist)))))
  3967. ((equal key "STARTUP")
  3968. (let ((startup (assq 'startup alist)))
  3969. (if startup
  3970. (setcdr startup
  3971. (append (cdr startup) (split-string value)))
  3972. (push (cons 'startup (split-string value)) alist))))
  3973. ((equal key "TAGS")
  3974. (let ((tag-cell (assq 'tags alist)))
  3975. (if tag-cell
  3976. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  3977. (push (cons 'tags value) alist))))
  3978. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  3979. (let ((todo (assq 'todo alist))
  3980. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  3981. (split-string value))))
  3982. (if todo (push value (cdr todo))
  3983. (push (list 'todo value) alist))))
  3984. ((equal key "SETUPFILE")
  3985. (unless buffer-read-only ; Do not check in Gnus messages.
  3986. (let ((f (and (org-string-nw-p value)
  3987. (expand-file-name (org-strip-quotes value)))))
  3988. (when (and f (file-readable-p f) (not (member f files)))
  3989. (with-temp-buffer
  3990. (setq default-directory (file-name-directory f))
  3991. (insert-file-contents f)
  3992. (setq alist
  3993. ;; Fake Org mode to benefit from cache
  3994. ;; without recurring needlessly.
  3995. (let ((major-mode 'org-mode))
  3996. (org--setup-collect-keywords
  3997. regexp (cons f files) alist)))))))))))))))
  3998. alist)
  3999. (defun org-tag-string-to-alist (s)
  4000. "Return tag alist associated to string S.
  4001. S is a value for TAGS keyword or produced with
  4002. `org-tag-alist-to-string'. Return value is an alist suitable for
  4003. `org-tag-alist' or `org-tag-persistent-alist'."
  4004. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4005. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  4006. "\\(?:(\\(.\\))\\)?\\'"))
  4007. alist group-flag)
  4008. (dolist (tokens lines (cdr (nreverse alist)))
  4009. (push '(:newline) alist)
  4010. (while tokens
  4011. (let ((token (pop tokens)))
  4012. (pcase token
  4013. ("{"
  4014. (push '(:startgroup) alist)
  4015. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4016. ("}"
  4017. (push '(:endgroup) alist)
  4018. (setq group-flag nil))
  4019. ("["
  4020. (push '(:startgrouptag) alist)
  4021. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4022. ("]"
  4023. (push '(:endgrouptag) alist)
  4024. (setq group-flag nil))
  4025. (":"
  4026. (push '(:grouptags) alist))
  4027. ((guard (string-match tag-re token))
  4028. (let ((tag (match-string 1 token))
  4029. (key (and (match-beginning 2)
  4030. (string-to-char (match-string 2 token)))))
  4031. ;; Push all tags in groups, no matter if they already
  4032. ;; appear somewhere else in the list.
  4033. (when (or group-flag (not (assoc tag alist)))
  4034. (push (cons tag key) alist))))))))))
  4035. (defun org-tag-alist-to-string (alist &optional skip-key)
  4036. "Return tag string associated to ALIST.
  4037. ALIST is an alist, as defined in `org-tag-alist' or
  4038. `org-tag-persistent-alist', or produced with
  4039. `org-tag-string-to-alist'.
  4040. Return value is a string suitable as a value for \"TAGS\"
  4041. keyword.
  4042. When optional argument SKIP-KEY is non-nil, skip selection keys
  4043. next to tags."
  4044. (mapconcat (lambda (token)
  4045. (pcase token
  4046. (`(:startgroup) "{")
  4047. (`(:endgroup) "}")
  4048. (`(:startgrouptag) "[")
  4049. (`(:endgrouptag) "]")
  4050. (`(:grouptags) ":")
  4051. (`(:newline) "\\n")
  4052. ((and
  4053. (guard (not skip-key))
  4054. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4055. (format "%s(%c)" tag key))
  4056. (`(,(and tag (pred stringp)) . ,_) tag)
  4057. (_ (user-error "Invalid tag token: %S" token))))
  4058. alist
  4059. " "))
  4060. (defun org-tag-alist-to-groups (alist)
  4061. "Return group alist from tag ALIST.
  4062. ALIST is an alist, as defined in `org-tag-alist' or
  4063. `org-tag-persistent-alist', or produced with
  4064. `org-tag-string-to-alist'. Return value is an alist following
  4065. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4066. a string, summarizing TAGS, as a list of strings."
  4067. (let (groups group-status current-group)
  4068. (dolist (token alist (nreverse groups))
  4069. (pcase token
  4070. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4071. (`(,(or :endgroup :endgrouptag))
  4072. (when (eq group-status 'append)
  4073. (push (nreverse current-group) groups))
  4074. (setq group-status nil current-group nil))
  4075. (`(:grouptags) (setq group-status 'append))
  4076. ((and `(,tag . ,_) (guard group-status))
  4077. (if (eq group-status 'append) (push tag current-group)
  4078. (setq current-group (list tag))))
  4079. (_ nil)))))
  4080. (defvar org--file-cache (make-hash-table :test #'equal)
  4081. "Hash table to store contents of files referenced via a URL.
  4082. This is the cache of file URLs read using `org-file-contents'.")
  4083. (defun org-reset-file-cache ()
  4084. "Reset the cache of files downloaded by `org-file-contents'."
  4085. (clrhash org--file-cache))
  4086. (defun org-file-url-p (file)
  4087. "Non-nil if FILE is a URL."
  4088. (require 'ffap)
  4089. (string-match-p ffap-url-regexp file))
  4090. (defun org-file-contents (file &optional noerror nocache)
  4091. "Return the contents of FILE, as a string.
  4092. FILE can be a file name or URL.
  4093. If FILE is a URL, download the contents. If the URL contents are
  4094. already cached in the `org--file-cache' hash table, the download step
  4095. is skipped.
  4096. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4097. from file or URL.
  4098. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4099. is available. This option applies only if FILE is a URL."
  4100. (let* ((is-url (org-file-url-p file))
  4101. (cache (and is-url
  4102. (not nocache)
  4103. (gethash file org--file-cache))))
  4104. (cond
  4105. (cache)
  4106. (is-url
  4107. (with-current-buffer (url-retrieve-synchronously file)
  4108. (goto-char (point-min))
  4109. ;; Move point to after the url-retrieve header.
  4110. (search-forward "\n\n" nil :move)
  4111. ;; Search for the success code only in the url-retrieve header.
  4112. (if (save-excursion
  4113. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4114. ;; Update the cache `org--file-cache' and return contents.
  4115. (puthash file
  4116. (buffer-substring-no-properties (point) (point-max))
  4117. org--file-cache)
  4118. (funcall (if noerror #'message #'user-error)
  4119. "Unable to fetch file from %S"
  4120. file))))
  4121. (t
  4122. (with-temp-buffer
  4123. (condition-case nil
  4124. (progn
  4125. (insert-file-contents file)
  4126. (buffer-string))
  4127. (file-error
  4128. (funcall (if noerror #'message #'user-error)
  4129. "Unable to read file %S"
  4130. file))))))))
  4131. (defun org-extract-log-state-settings (x)
  4132. "Extract the log state setting from a TODO keyword string.
  4133. This will extract info from a string like \"WAIT(w@/!)\"."
  4134. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4135. (let ((kw (match-string 1 x))
  4136. (log1 (and (match-end 3) (match-string 3 x)))
  4137. (log2 (and (match-end 4) (match-string 4 x))))
  4138. (and (or log1 log2)
  4139. (list kw
  4140. (and log1 (if (equal log1 "!") 'time 'note))
  4141. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4142. (defun org-remove-keyword-keys (list)
  4143. "Remove a pair of parenthesis at the end of each string in LIST."
  4144. (mapcar (lambda (x)
  4145. (if (string-match "(.*)$" x)
  4146. (substring x 0 (match-beginning 0))
  4147. x))
  4148. list))
  4149. (defun org-assign-fast-keys (alist)
  4150. "Assign fast keys to a keyword-key alist.
  4151. Respect keys that are already there."
  4152. (let (new e (alt ?0))
  4153. (while (setq e (pop alist))
  4154. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4155. (cdr e)) ;; Key already assigned.
  4156. (push e new)
  4157. (let ((clist (string-to-list (downcase (car e))))
  4158. (used (append new alist)))
  4159. (when (= (car clist) ?@)
  4160. (pop clist))
  4161. (while (and clist (rassoc (car clist) used))
  4162. (pop clist))
  4163. (unless clist
  4164. (while (rassoc alt used)
  4165. (cl-incf alt)))
  4166. (push (cons (car e) (or (car clist) alt)) new))))
  4167. (nreverse new)))
  4168. ;;; Some variables used in various places
  4169. (defvar org-window-configuration nil
  4170. "Used in various places to store a window configuration.")
  4171. (defvar org-selected-window nil
  4172. "Used in various places to store a window configuration.")
  4173. (defvar org-finish-function nil
  4174. "Function to be called when `C-c C-c' is used.
  4175. This is for getting out of special buffers like capture.")
  4176. (defvar org-last-state)
  4177. ;; Defined somewhere in this file, but used before definition.
  4178. (defvar org-entities) ;; defined in org-entities.el
  4179. (defvar org-struct-menu)
  4180. (defvar org-org-menu)
  4181. (defvar org-tbl-menu)
  4182. ;;;; Define the Org mode
  4183. (defun org-before-change-function (_beg _end)
  4184. "Every change indicates that a table might need an update."
  4185. (setq org-table-may-need-update t))
  4186. (defvar org-mode-map)
  4187. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4188. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4189. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4190. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4191. (defvar bidi-paragraph-direction)
  4192. (defvar buffer-face-mode-face)
  4193. (require 'outline)
  4194. ;; Other stuff we need.
  4195. (require 'time-date)
  4196. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4197. (require 'easymenu)
  4198. (autoload 'easy-menu-add "easymenu")
  4199. (require 'overlay)
  4200. ;; (require 'org-macs) moved higher up in the file before it is first used
  4201. (require 'org-entities)
  4202. ;; (require 'org-compat) moved higher up in the file before it is first used
  4203. (require 'org-faces)
  4204. (require 'org-list)
  4205. (require 'org-pcomplete)
  4206. (require 'org-src)
  4207. (require 'org-footnote)
  4208. (require 'org-macro)
  4209. ;; babel
  4210. (require 'ob)
  4211. ;;;###autoload
  4212. (define-derived-mode org-mode outline-mode "Org"
  4213. "Outline-based notes management and organizer, alias
  4214. \"Carsten's outline-mode for keeping track of everything.\"
  4215. Org mode develops organizational tasks around a NOTES file which
  4216. contains information about projects as plain text. Org mode is
  4217. implemented on top of Outline mode, which is ideal to keep the content
  4218. of large files well structured. It supports ToDo items, deadlines and
  4219. time stamps, which magically appear in the diary listing of the Emacs
  4220. calendar. Tables are easily created with a built-in table editor.
  4221. Plain text URL-like links connect to websites, emails (VM), Usenet
  4222. messages (Gnus), BBDB entries, and any files related to the project.
  4223. For printing and sharing of notes, an Org file (or a part of it)
  4224. can be exported as a structured ASCII or HTML file.
  4225. The following commands are available:
  4226. \\{org-mode-map}"
  4227. (org-load-modules-maybe)
  4228. (org-install-agenda-files-menu)
  4229. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4230. (add-to-invisibility-spec '(org-hide-block . t))
  4231. (add-to-invisibility-spec '(org-hide-drawer . t))
  4232. (setq-local outline-regexp org-outline-regexp)
  4233. (setq-local outline-level 'org-outline-level)
  4234. (setq bidi-paragraph-direction 'left-to-right)
  4235. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4236. (unless org-display-table
  4237. (setq org-display-table (make-display-table)))
  4238. (set-display-table-slot
  4239. org-display-table 4
  4240. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4241. org-ellipsis)))
  4242. (setq buffer-display-table org-display-table))
  4243. (org-set-regexps-and-options)
  4244. (org-set-font-lock-defaults)
  4245. (when (and org-tag-faces (not org-tags-special-faces-re))
  4246. ;; tag faces set outside customize.... force initialization.
  4247. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4248. ;; Calc embedded
  4249. (setq-local calc-embedded-open-mode "# ")
  4250. ;; Modify a few syntax entries
  4251. (modify-syntax-entry ?\" "\"")
  4252. (modify-syntax-entry ?\\ "_")
  4253. (modify-syntax-entry ?~ "_")
  4254. (modify-syntax-entry ?< "(>")
  4255. (modify-syntax-entry ?> ")<")
  4256. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4257. ;; Activate before-change-function
  4258. (setq-local org-table-may-need-update t)
  4259. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4260. ;; Check for running clock before killing a buffer
  4261. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4262. ;; Initialize macros templates.
  4263. (org-macro-initialize-templates)
  4264. ;; Initialize radio targets.
  4265. (org-update-radio-target-regexp)
  4266. ;; Indentation.
  4267. (setq-local indent-line-function 'org-indent-line)
  4268. (setq-local indent-region-function 'org-indent-region)
  4269. ;; Filling and auto-filling.
  4270. (org-setup-filling)
  4271. ;; Comments.
  4272. (org-setup-comments-handling)
  4273. ;; Initialize cache.
  4274. (org-element-cache-reset)
  4275. ;; Beginning/end of defun
  4276. (setq-local beginning-of-defun-function 'org-backward-element)
  4277. (setq-local end-of-defun-function
  4278. (lambda ()
  4279. (if (not (org-at-heading-p))
  4280. (org-forward-element)
  4281. (org-forward-element)
  4282. (forward-char -1))))
  4283. ;; Next error for sparse trees
  4284. (setq-local next-error-function 'org-occur-next-match)
  4285. ;; Make commit log messages from Org documents easier.
  4286. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4287. ;; Make sure dependence stuff works reliably, even for users who set it
  4288. ;; too late :-(
  4289. (if org-enforce-todo-dependencies
  4290. (add-hook 'org-blocker-hook
  4291. 'org-block-todo-from-children-or-siblings-or-parent)
  4292. (remove-hook 'org-blocker-hook
  4293. 'org-block-todo-from-children-or-siblings-or-parent))
  4294. (if org-enforce-todo-checkbox-dependencies
  4295. (add-hook 'org-blocker-hook
  4296. 'org-block-todo-from-checkboxes)
  4297. (remove-hook 'org-blocker-hook
  4298. 'org-block-todo-from-checkboxes))
  4299. ;; Align options lines
  4300. (setq-local
  4301. align-mode-rules-list
  4302. '((org-in-buffer-settings
  4303. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4304. (modes . '(org-mode)))))
  4305. ;; Make isearch reveal context
  4306. (setq-local outline-isearch-open-invisible-function
  4307. (lambda (&rest _) (org-show-context 'isearch)))
  4308. ;; Setup the pcomplete hooks
  4309. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4310. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4311. (setq-local pcomplete-default-completion-function #'ignore)
  4312. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4313. (setq-local pcomplete-termination-string "")
  4314. (add-hook 'completion-at-point-functions
  4315. #'pcomplete-completions-at-point nil t)
  4316. (setq-local buffer-face-mode-face 'org-default)
  4317. ;; If empty file that did not turn on Org mode automatically, make
  4318. ;; it to.
  4319. (when (and org-insert-mode-line-in-empty-file
  4320. (called-interactively-p 'any)
  4321. (= (point-min) (point-max)))
  4322. (insert "# -*- mode: org -*-\n\n"))
  4323. (unless org-inhibit-startup
  4324. (org-unmodified
  4325. (when org-startup-with-beamer-mode (org-beamer-mode))
  4326. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4327. (org-table-map-tables
  4328. (cond ((and org-startup-align-all-tables
  4329. org-startup-shrink-all-tables)
  4330. (lambda () (org-table-align) (org-table-shrink)))
  4331. (org-startup-align-all-tables #'org-table-align)
  4332. (t #'org-table-shrink))
  4333. t))
  4334. (when org-startup-with-inline-images (org-display-inline-images))
  4335. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4336. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4337. (when org-startup-truncated (setq truncate-lines t))
  4338. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4339. ;; Try to set `org-hide' face correctly.
  4340. (let ((foreground (org-find-invisible-foreground)))
  4341. (when foreground
  4342. (set-face-foreground 'org-hide foreground))))
  4343. ;; Update `customize-package-emacs-version-alist'
  4344. (add-to-list 'customize-package-emacs-version-alist
  4345. '(Org ("8.0" . "24.4")
  4346. ("8.1" . "24.4")
  4347. ("8.2" . "24.4")
  4348. ("8.2.7" . "24.4")
  4349. ("8.3" . "26.1")
  4350. ("9.0" . "26.1")
  4351. ("9.1" . "26.1")
  4352. ("9.2" . "27.1")
  4353. ("9.3" . "27.1")))
  4354. (defvar org-mode-transpose-word-syntax-table
  4355. (let ((st (make-syntax-table text-mode-syntax-table)))
  4356. (dolist (c org-emphasis-alist st)
  4357. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4358. (when (fboundp 'abbrev-table-put)
  4359. (abbrev-table-put org-mode-abbrev-table
  4360. :parents (list text-mode-abbrev-table)))
  4361. (defun org-find-invisible-foreground ()
  4362. (let ((candidates (remove
  4363. "unspecified-bg"
  4364. (nconc
  4365. (list (face-background 'default)
  4366. (face-background 'org-default))
  4367. (mapcar
  4368. (lambda (alist)
  4369. (when (boundp alist)
  4370. (cdr (assq 'background-color (symbol-value alist)))))
  4371. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4372. (list (face-foreground 'org-hide))))))
  4373. (car (remove nil candidates))))
  4374. (defun org-current-time (&optional rounding-minutes past)
  4375. "Current time, possibly rounded to ROUNDING-MINUTES.
  4376. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4377. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4378. the rounding returns a past time."
  4379. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4380. (car org-time-stamp-rounding-minutes)))
  4381. (now (current-time)))
  4382. (if (< r 1)
  4383. now
  4384. (let* ((time (decode-time now))
  4385. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4386. (nthcdr 2 time))))
  4387. (if (or (not past) (org-time-less-p res now))
  4388. res
  4389. (org-time-subtract res (* r 60)))))))
  4390. (defun org-today ()
  4391. "Return today date, considering `org-extend-today-until'."
  4392. (time-to-days
  4393. (org-time-since (* 3600 org-extend-today-until))))
  4394. ;;;; Font-Lock stuff, including the activators
  4395. (require 'font-lock)
  4396. (defconst org-match-sexp-depth 3
  4397. "Number of stacked braces for sub/superscript matching.")
  4398. (defun org-create-multibrace-regexp (left right n)
  4399. "Create a regular expression which will match a balanced sexp.
  4400. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4401. as single character strings.
  4402. The regexp returned will match the entire expression including the
  4403. delimiters. It will also define a single group which contains the
  4404. match except for the outermost delimiters. The maximum depth of
  4405. stacked delimiters is N. Escaping delimiters is not possible."
  4406. (let* ((nothing (concat "[^" left right "]*?"))
  4407. (or "\\|")
  4408. (re nothing)
  4409. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4410. (while (> n 1)
  4411. (setq n (1- n)
  4412. re (concat re or next)
  4413. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4414. (concat left "\\(" re "\\)" right)))
  4415. (defconst org-match-substring-regexp
  4416. (concat
  4417. "\\(\\S-\\)\\([_^]\\)\\("
  4418. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4419. "\\|"
  4420. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4421. "\\|"
  4422. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4423. "The regular expression matching a sub- or superscript.")
  4424. (defconst org-match-substring-with-braces-regexp
  4425. (concat
  4426. "\\(\\S-\\)\\([_^]\\)"
  4427. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4428. "The regular expression matching a sub- or superscript, forcing braces.")
  4429. (defvar org-emph-face nil)
  4430. (defun org-do-emphasis-faces (limit)
  4431. "Run through the buffer and emphasize strings."
  4432. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4433. (car org-emphasis-regexp-components))))
  4434. (catch :exit
  4435. (while (re-search-forward quick-re limit t)
  4436. (let* ((marker (match-string 2))
  4437. (verbatim? (member marker '("~" "="))))
  4438. (when (save-excursion
  4439. (goto-char (match-beginning 0))
  4440. (and
  4441. ;; Do not match table hlines.
  4442. (not (and (equal marker "+")
  4443. (org-match-line
  4444. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4445. ;; Do not match headline stars. Do not consider
  4446. ;; stars of a headline as closing marker for bold
  4447. ;; markup either.
  4448. (not (and (equal marker "*")
  4449. (save-excursion
  4450. (forward-char)
  4451. (skip-chars-backward "*")
  4452. (looking-at-p org-outline-regexp-bol))))
  4453. ;; Match full emphasis markup regexp.
  4454. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4455. ;; Do not span over paragraph boundaries.
  4456. (not (string-match-p org-element-paragraph-separate
  4457. (match-string 2)))
  4458. ;; Do not span over cells in table rows.
  4459. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4460. (string-match-p "|" (match-string 4))))))
  4461. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  4462. (font-lock-prepend-text-property
  4463. (match-beginning 2) (match-end 2) 'face face)
  4464. (when verbatim?
  4465. (org-remove-flyspell-overlays-in
  4466. (match-beginning 0) (match-end 0))
  4467. (remove-text-properties (match-beginning 2) (match-end 2)
  4468. '(display t invisible t intangible t)))
  4469. (add-text-properties (match-beginning 2) (match-end 2)
  4470. '(font-lock-multiline t org-emphasis t))
  4471. (when org-hide-emphasis-markers
  4472. (add-text-properties (match-end 4) (match-beginning 5)
  4473. '(invisible org-link))
  4474. (add-text-properties (match-beginning 3) (match-end 3)
  4475. '(invisible org-link)))
  4476. (throw :exit t))))))))
  4477. (defun org-emphasize (&optional char)
  4478. "Insert or change an emphasis, i.e. a font like bold or italic.
  4479. If there is an active region, change that region to a new emphasis.
  4480. If there is no region, just insert the marker characters and position
  4481. the cursor between them.
  4482. CHAR should be the marker character. If it is a space, it means to
  4483. remove the emphasis of the selected region.
  4484. If CHAR is not given (for example in an interactive call) it will be
  4485. prompted for."
  4486. (interactive)
  4487. (let ((erc org-emphasis-regexp-components)
  4488. (string "") beg end move s)
  4489. (if (org-region-active-p)
  4490. (setq beg (region-beginning)
  4491. end (region-end)
  4492. string (buffer-substring beg end))
  4493. (setq move t))
  4494. (unless char
  4495. (message "Emphasis marker or tag: [%s]"
  4496. (mapconcat #'car org-emphasis-alist ""))
  4497. (setq char (read-char-exclusive)))
  4498. (if (equal char ?\s)
  4499. (setq s ""
  4500. move nil)
  4501. (unless (assoc (char-to-string char) org-emphasis-alist)
  4502. (user-error "No such emphasis marker: \"%c\"" char))
  4503. (setq s (char-to-string char)))
  4504. (while (and (> (length string) 1)
  4505. (equal (substring string 0 1) (substring string -1))
  4506. (assoc (substring string 0 1) org-emphasis-alist))
  4507. (setq string (substring string 1 -1)))
  4508. (setq string (concat s string s))
  4509. (when beg (delete-region beg end))
  4510. (unless (or (bolp)
  4511. (string-match (concat "[" (nth 0 erc) "\n]")
  4512. (char-to-string (char-before (point)))))
  4513. (insert " "))
  4514. (unless (or (eobp)
  4515. (string-match (concat "[" (nth 1 erc) "\n]")
  4516. (char-to-string (char-after (point)))))
  4517. (insert " ") (backward-char 1))
  4518. (insert string)
  4519. (and move (backward-char 1))))
  4520. (defconst org-nonsticky-props
  4521. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4522. (defsubst org-rear-nonsticky-at (pos)
  4523. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4524. (defun org-activate-links (limit)
  4525. "Add link properties to links.
  4526. This includes angle, plain, and bracket links."
  4527. (catch :exit
  4528. (while (re-search-forward org-link-any-re limit t)
  4529. (let* ((start (match-beginning 0))
  4530. (end (match-end 0))
  4531. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4532. (visible-end (or (match-end 3) (match-end 2)))
  4533. (style (cond ((eq ?< (char-after start)) 'angle)
  4534. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4535. (t 'plain))))
  4536. (when (and (memq style org-highlight-links)
  4537. ;; Do not span over paragraph boundaries.
  4538. (not (string-match-p org-element-paragraph-separate
  4539. (match-string 0)))
  4540. ;; Do not confuse plain links with tags.
  4541. (not (and (eq style 'plain)
  4542. (let ((face (get-text-property
  4543. (max (1- start) (point-min)) 'face)))
  4544. (if (consp face) (memq 'org-tag face)
  4545. (eq 'org-tag face))))))
  4546. (let* ((link-object (save-excursion
  4547. (goto-char start)
  4548. (save-match-data (org-element-link-parser))))
  4549. (link (org-element-property :raw-link link-object))
  4550. (type (org-element-property :type link-object))
  4551. (path (org-element-property :path link-object))
  4552. (properties ;for link's visible part
  4553. (list
  4554. 'face (pcase (org-link-get-parameter type :face)
  4555. ((and (pred functionp) face) (funcall face path))
  4556. ((and (pred facep) face) face)
  4557. ((and (pred consp) face) face) ;anonymous
  4558. (_ 'org-link))
  4559. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4560. 'highlight)
  4561. 'keymap (or (org-link-get-parameter type :keymap)
  4562. org-mouse-map)
  4563. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4564. ((and (pred stringp) echo) echo)
  4565. ((and (pred functionp) echo) echo)
  4566. (_ (concat "LINK: " link)))
  4567. 'htmlize-link (pcase (org-link-get-parameter type
  4568. :htmlize-link)
  4569. ((and (pred functionp) f) (funcall f))
  4570. (_ `(:uri ,link)))
  4571. 'font-lock-multiline t)))
  4572. (org-remove-flyspell-overlays-in start end)
  4573. (org-rear-nonsticky-at end)
  4574. (if (not (eq 'bracket style))
  4575. (add-text-properties start end properties)
  4576. ;; Handle invisible parts in bracket links.
  4577. (remove-text-properties start end '(invisible nil))
  4578. (let ((hidden
  4579. (append `(invisible
  4580. ,(or (org-link-get-parameter type :display)
  4581. 'org-link))
  4582. properties)))
  4583. (add-text-properties start visible-start hidden)
  4584. (add-text-properties visible-start visible-end properties)
  4585. (add-text-properties visible-end end hidden)
  4586. (org-rear-nonsticky-at visible-start)
  4587. (org-rear-nonsticky-at visible-end)))
  4588. (let ((f (org-link-get-parameter type :activate-func)))
  4589. (when (functionp f)
  4590. (funcall f start end path (eq style 'bracket))))
  4591. (throw :exit t))))) ;signal success
  4592. nil))
  4593. (defun org-activate-code (limit)
  4594. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4595. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4596. (remove-text-properties (match-beginning 0) (match-end 0)
  4597. '(display t invisible t intangible t))
  4598. t))
  4599. (defcustom org-src-fontify-natively t
  4600. "When non-nil, fontify code in code blocks.
  4601. See also the `org-block' face."
  4602. :type 'boolean
  4603. :version "26.1"
  4604. :package-version '(Org . "8.3")
  4605. :group 'org-appearance
  4606. :group 'org-babel)
  4607. (defcustom org-allow-promoting-top-level-subtree nil
  4608. "When non-nil, allow promoting a top level subtree.
  4609. The leading star of the top level headline will be replaced
  4610. by a #."
  4611. :type 'boolean
  4612. :version "24.1"
  4613. :group 'org-appearance)
  4614. (defun org-fontify-meta-lines-and-blocks (limit)
  4615. (condition-case nil
  4616. (org-fontify-meta-lines-and-blocks-1 limit)
  4617. (error (message "Org mode fontification error in %S at %d"
  4618. (current-buffer)
  4619. (line-number-at-pos)))))
  4620. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4621. "Fontify #+ lines and blocks."
  4622. (let ((case-fold-search t))
  4623. (when (re-search-forward
  4624. (rx bol (group (zero-or-more blank) "#"
  4625. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4626. space
  4627. eol))
  4628. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4629. (zero-or-more blank)
  4630. (group (group (zero-or-more (not (any " \t\n"))))
  4631. (zero-or-more blank)
  4632. (group (zero-or-more any)))))
  4633. limit t)
  4634. (let ((beg (match-beginning 0))
  4635. (end-of-beginline (match-end 0))
  4636. (block-start (match-end 0)) ; includes the \n at end of #+begin line
  4637. (block-end nil) ; will include \n after end of block content
  4638. (lang (match-string 7)) ; the language, if it is an src block
  4639. (bol-after-beginline (line-beginning-position 2))
  4640. (dc1 (downcase (match-string 2)))
  4641. (dc3 (downcase (match-string 3)))
  4642. (whole-blockline org-fontify-whole-block-delimiter-line)
  4643. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4644. (cond
  4645. ((and (match-end 4) (equal dc3 "+begin"))
  4646. ;; Truly a block
  4647. (setq block-type (downcase (match-string 5))
  4648. quoting (member block-type org-protecting-blocks)) ; src, example, export, maybe more
  4649. (when (re-search-forward
  4650. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4651. (seq (zero-or-more blank)
  4652. "#+end"
  4653. ,(match-string 4)
  4654. word-end
  4655. (zero-or-more any)))))
  4656. nil t) ;; on purpose, we look further than LIMIT
  4657. ;; We do have a matching #+end line
  4658. (setq beg-of-endline (match-beginning 0)
  4659. end-of-endline (match-end 0)
  4660. nl-before-endline (1- (match-beginning 0)))
  4661. (setq block-end (match-beginning 0)) ; includes the final newline.
  4662. (when quoting
  4663. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4664. (remove-text-properties beg end-of-endline
  4665. '(display t invisible t intangible t)))
  4666. (add-text-properties
  4667. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4668. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4669. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4670. (cond
  4671. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4672. (org-src-font-lock-fontify-block lang block-start block-end)
  4673. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4674. (quoting
  4675. (add-text-properties
  4676. bol-after-beginline beg-of-endline
  4677. (list 'face
  4678. (list :inherit
  4679. (let ((face-name
  4680. (intern (format "org-block-%s" lang))))
  4681. (append (and (facep face-name) (list face-name))
  4682. '(org-block)))))))
  4683. ((not org-fontify-quote-and-verse-blocks))
  4684. ((string= block-type "quote")
  4685. (add-face-text-property
  4686. bol-after-beginline beg-of-endline 'org-quote t))
  4687. ((string= block-type "verse")
  4688. (add-face-text-property
  4689. bol-after-beginline beg-of-endline 'org-verse t)))
  4690. ;; Fontify the #+begin and #+end lines of the blocks
  4691. (add-text-properties
  4692. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4693. '(face org-block-begin-line))
  4694. (unless (string-prefix-p "*" (match-string 1))
  4695. (add-text-properties
  4696. beg-of-endline
  4697. (if whole-blockline
  4698. (let ((beg-of-next-line (1+ end-of-endline)))
  4699. (min (point-max) beg-of-next-line))
  4700. (min (point-max) end-of-endline))
  4701. '(face org-block-end-line)))
  4702. t))
  4703. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  4704. (org-remove-flyspell-overlays-in
  4705. (match-beginning 0)
  4706. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4707. (add-text-properties
  4708. beg (match-end 3)
  4709. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4710. '(font-lock-fontified t invisible t)
  4711. '(font-lock-fontified t face org-document-info-keyword)))
  4712. (add-text-properties
  4713. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4714. (if (string-equal dc1 "+title:")
  4715. '(font-lock-fontified t face org-document-title)
  4716. '(font-lock-fontified t face org-document-info))))
  4717. ((string-prefix-p "+caption" dc1)
  4718. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4719. (remove-text-properties (match-beginning 0) (match-end 0)
  4720. '(display t invisible t intangible t))
  4721. ;; Handle short captions.
  4722. (save-excursion
  4723. (beginning-of-line)
  4724. (looking-at (rx (group (zero-or-more blank)
  4725. "#+caption"
  4726. (optional "[" (zero-or-more any) "]")
  4727. ":")
  4728. (zero-or-more blank))))
  4729. (add-text-properties (line-beginning-position) (match-end 1)
  4730. '(font-lock-fontified t face org-meta-line))
  4731. (add-text-properties (match-end 0) (line-end-position)
  4732. '(font-lock-fontified t face org-block))
  4733. t)
  4734. ((member dc3 '(" " ""))
  4735. ; Just a comment, the plus was not there
  4736. (org-remove-flyspell-overlays-in beg (match-end 0))
  4737. (add-text-properties
  4738. beg (match-end 0)
  4739. '(font-lock-fontified t face font-lock-comment-face)))
  4740. (t ;; just any other in-buffer setting, but not indented
  4741. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4742. (remove-text-properties (match-beginning 0) (match-end 0)
  4743. '(display t invisible t intangible t))
  4744. (add-text-properties beg (match-end 0)
  4745. '(font-lock-fontified t face org-meta-line))
  4746. t))))))
  4747. (defun org-fontify-drawers (limit)
  4748. "Fontify drawers."
  4749. (when (re-search-forward org-drawer-regexp limit t)
  4750. (add-text-properties
  4751. (line-beginning-position) (line-beginning-position 2)
  4752. '(font-lock-fontified t face org-drawer))
  4753. (org-remove-flyspell-overlays-in
  4754. (line-beginning-position) (line-beginning-position 2))
  4755. t))
  4756. (defun org-fontify-macros (limit)
  4757. "Fontify macros."
  4758. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4759. (let ((begin (match-beginning 0))
  4760. (opening-end (match-beginning 1)))
  4761. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4762. (match-string 1))
  4763. (let ((end (match-end 1))
  4764. (closing-start (match-beginning 1)))
  4765. (add-text-properties
  4766. begin end
  4767. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4768. (org-remove-flyspell-overlays-in begin end)
  4769. (when org-hide-macro-markers
  4770. (add-text-properties begin opening-end '(invisible t))
  4771. (add-text-properties closing-start end '(invisible t)))
  4772. t)))))
  4773. (defun org-fontify-extend-region (beg end _old-len)
  4774. (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4775. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4776. (extend (lambda (r1 r2 dir)
  4777. (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
  4778. (replace-regexp-in-string "[][]" r2
  4779. (match-string-no-properties 0)))))
  4780. (re-search-forward (regexp-quote re) nil t dir)))))
  4781. (save-match-data
  4782. (save-excursion
  4783. (goto-char beg)
  4784. (back-to-indentation)
  4785. (cond ((looking-at end-re)
  4786. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4787. ((looking-at begin-re)
  4788. (cons beg (or (funcall extend "end" "]" 1) end)))
  4789. (t (cons beg end)))))))
  4790. (defun org-activate-footnote-links (limit)
  4791. "Add text properties for footnotes."
  4792. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4793. (when fn
  4794. (let* ((beg (nth 1 fn))
  4795. (end (nth 2 fn))
  4796. (label (car fn))
  4797. (referencep (/= (line-beginning-position) beg)))
  4798. (when (and referencep (nth 3 fn))
  4799. (save-excursion
  4800. (goto-char beg)
  4801. (search-forward (or label "fn:"))
  4802. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4803. (add-text-properties beg end
  4804. (list 'mouse-face 'highlight
  4805. 'keymap org-mouse-map
  4806. 'help-echo
  4807. (if referencep "Footnote reference"
  4808. "Footnote definition")
  4809. 'font-lock-fontified t
  4810. 'font-lock-multiline t
  4811. 'face 'org-footnote))))))
  4812. (defun org-activate-dates (limit)
  4813. "Add text properties for dates."
  4814. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4815. (not (equal (char-before (match-beginning 0)) 91)))
  4816. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4817. (add-text-properties (match-beginning 0) (match-end 0)
  4818. (list 'mouse-face 'highlight
  4819. 'keymap org-mouse-map))
  4820. (org-rear-nonsticky-at (match-end 0))
  4821. (when org-display-custom-times
  4822. ;; If it's a date range, activate custom time for second date.
  4823. (when (match-end 3)
  4824. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4825. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4826. t))
  4827. (defun org-activate-target-links (limit)
  4828. "Add text properties for target matches."
  4829. (when org-target-link-regexp
  4830. (let ((case-fold-search t))
  4831. ;; `org-target-link-regexp' matches one character before the
  4832. ;; actual target.
  4833. (unless (bolp) (forward-char -1))
  4834. (when (re-search-forward org-target-link-regexp limit t)
  4835. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4836. (add-text-properties (match-beginning 1) (match-end 1)
  4837. (list 'mouse-face 'highlight
  4838. 'keymap org-mouse-map
  4839. 'help-echo "Radio target link"
  4840. 'org-linked-text t))
  4841. (org-rear-nonsticky-at (match-end 1))
  4842. t))))
  4843. (defvar org-latex-and-related-regexp nil
  4844. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4845. (defun org-compute-latex-and-related-regexp ()
  4846. "Compute regular expression for LaTeX, entities and sub/superscript.
  4847. Result depends on variable `org-highlight-latex-and-related'."
  4848. (let ((re-sub
  4849. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4850. ((eq org-use-sub-superscripts '{})
  4851. (list org-match-substring-with-braces-regexp))
  4852. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4853. (re-latex
  4854. (when (or (memq 'latex org-highlight-latex-and-related)
  4855. (memq 'native org-highlight-latex-and-related))
  4856. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4857. (delq nil
  4858. (mapcar (lambda (x)
  4859. (and (member (car x) matchers) (nth 1 x)))
  4860. org-latex-regexps)))))
  4861. (re-entities
  4862. (when (memq 'entities org-highlight-latex-and-related)
  4863. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4864. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4865. (setq-local org-latex-and-related-regexp
  4866. (mapconcat #'identity
  4867. (append re-latex re-entities re-sub)
  4868. "\\|"))))
  4869. (defun org-do-latex-and-related (_limit)
  4870. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4871. Stop at first highlighted object, if any. Return t if some
  4872. highlighting was done, nil otherwise."
  4873. (when (org-string-nw-p org-latex-and-related-regexp)
  4874. (catch 'found
  4875. (while (re-search-forward org-latex-and-related-regexp
  4876. nil t) ;; on purpose, we ignore LIMIT
  4877. (unless (cl-some (lambda (f) (memq f '(org-code org-verbatim underline
  4878. org-special-keyword)))
  4879. (save-excursion
  4880. (goto-char (1+ (match-beginning 0)))
  4881. (face-at-point nil t)))
  4882. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4883. '(?_ ?^))
  4884. 1
  4885. 0))
  4886. (start (+ offset (match-beginning 0)))
  4887. (end (match-end 0)))
  4888. (if (memq 'native org-highlight-latex-and-related)
  4889. (org-src-font-lock-fontify-block "latex" start end)
  4890. (font-lock-prepend-text-property start end
  4891. 'face 'org-latex-and-related))
  4892. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4893. '(font-lock-multiline t)))
  4894. (throw 'found t)))
  4895. nil)))
  4896. (defun org-restart-font-lock ()
  4897. "Restart `font-lock-mode', to force refontification."
  4898. (when (and (boundp 'font-lock-mode) font-lock-mode)
  4899. (font-lock-mode -1)
  4900. (font-lock-mode 1)))
  4901. (defun org-activate-tags (limit)
  4902. (when (re-search-forward org-tag-line-re limit t)
  4903. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4904. (add-text-properties (match-beginning 1) (match-end 1)
  4905. (list 'mouse-face 'highlight
  4906. 'keymap org-mouse-map))
  4907. (org-rear-nonsticky-at (match-end 1))
  4908. t))
  4909. (defun org-outline-level ()
  4910. "Compute the outline level of the heading at point.
  4911. If this is called at a normal headline, the level is the number
  4912. of stars. Use `org-reduced-level' to remove the effect of
  4913. `org-odd-levels'. Unlike to `org-current-level', this function
  4914. takes into consideration inlinetasks."
  4915. (org-with-wide-buffer
  4916. (end-of-line)
  4917. (if (re-search-backward org-outline-regexp-bol nil t)
  4918. (1- (- (match-end 0) (match-beginning 0)))
  4919. 0)))
  4920. (defvar org-font-lock-keywords nil)
  4921. (defsubst org-re-property (property &optional literal allow-null value)
  4922. "Return a regexp matching a PROPERTY line.
  4923. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4924. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4925. non-nil, match properties even without a value.
  4926. Match group 3 is set to the value when it exists. If there is no
  4927. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4928. With optional argument VALUE, match only property lines with
  4929. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4930. unless LITERAL is non-nil."
  4931. (concat
  4932. "^\\(?4:[ \t]*\\)"
  4933. (format "\\(?1::\\(?2:%s\\):\\)"
  4934. (if literal property (regexp-quote property)))
  4935. (cond (value
  4936. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4937. (if literal value (regexp-quote value))))
  4938. (allow-null
  4939. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4940. (t
  4941. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4942. (defconst org-property-re
  4943. (org-re-property "\\S-+" 'literal t)
  4944. "Regular expression matching a property line.
  4945. There are four matching groups:
  4946. 1: :PROPKEY: including the leading and trailing colon,
  4947. 2: PROPKEY without the leading and trailing colon,
  4948. 3: PROPVAL without leading or trailing spaces,
  4949. 4: the indentation of the current line,
  4950. 5: trailing whitespace.")
  4951. (defvar org-font-lock-hook nil
  4952. "Functions to be called for special font lock stuff.")
  4953. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4954. (defvar org-font-lock-set-keywords-hook nil
  4955. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4956. This is called after `org-font-lock-extra-keywords' is defined, but before
  4957. it is installed to be used by font lock. This can be useful if something
  4958. needs to be inserted at a specific position in the font-lock sequence.")
  4959. (defun org-font-lock-hook (limit)
  4960. "Run `org-font-lock-hook' within LIMIT."
  4961. (run-hook-with-args 'org-font-lock-hook limit))
  4962. (defun org-set-font-lock-defaults ()
  4963. "Set font lock defaults for the current buffer."
  4964. (let* ((em org-fontify-emphasized-text)
  4965. (lk org-highlight-links)
  4966. (org-font-lock-extra-keywords
  4967. (list
  4968. ;; Call the hook
  4969. '(org-font-lock-hook)
  4970. ;; Headlines
  4971. `(,(if org-fontify-whole-heading-line
  4972. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4973. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4974. (1 (org-get-level-face 1))
  4975. (2 (org-get-level-face 2))
  4976. (3 (org-get-level-face 3)))
  4977. ;; Table lines
  4978. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4979. (1 'org-table t))
  4980. ;; Table internals
  4981. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4982. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4983. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4984. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4985. ;; Properties
  4986. (list org-property-re
  4987. '(1 'org-special-keyword t)
  4988. '(3 'org-property-value t))
  4989. ;; Drawers
  4990. '(org-fontify-drawers)
  4991. ;; Link related fontification.
  4992. '(org-activate-links)
  4993. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  4994. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  4995. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  4996. (when (memq 'footnote lk) '(org-activate-footnote-links))
  4997. ;; Targets.
  4998. (list org-radio-target-regexp '(0 'org-target t))
  4999. (list org-target-regexp '(0 'org-target t))
  5000. ;; Diary sexps.
  5001. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5002. ;; Macro
  5003. '(org-fontify-macros)
  5004. ;; TODO keyword
  5005. (list (format org-heading-keyword-regexp-format
  5006. org-todo-regexp)
  5007. '(2 (org-get-todo-face 2) t))
  5008. ;; TODO
  5009. (when org-fontify-todo-headline
  5010. (list (format org-heading-keyword-regexp-format
  5011. (concat
  5012. "\\(?:"
  5013. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  5014. "\\)"))
  5015. '(2 'org-headline-todo t)))
  5016. ;; DONE
  5017. (when org-fontify-done-headline
  5018. (list (format org-heading-keyword-regexp-format
  5019. (concat
  5020. "\\(?:"
  5021. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5022. "\\)"))
  5023. '(2 'org-headline-done t)))
  5024. ;; Priorities
  5025. '(org-font-lock-add-priority-faces)
  5026. ;; Tags
  5027. '(org-font-lock-add-tag-faces)
  5028. ;; Tags groups
  5029. (when (and org-group-tags org-tag-groups-alist)
  5030. (list (concat org-outline-regexp-bol ".+\\(:"
  5031. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5032. ":\\).*$")
  5033. '(1 'org-tag-group prepend)))
  5034. ;; Special keywords
  5035. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5036. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5037. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5038. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5039. ;; Emphasis
  5040. (when em '(org-do-emphasis-faces))
  5041. ;; Checkboxes
  5042. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5043. 1 'org-checkbox prepend)
  5044. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5045. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5046. (0 (org-get-checkbox-statistics-face) t)))
  5047. ;; Description list items
  5048. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5049. 1 'org-list-dt prepend)
  5050. ;; ARCHIVEd headings
  5051. (list (concat
  5052. org-outline-regexp-bol
  5053. "\\(.*:" org-archive-tag ":.*\\)")
  5054. '(1 'org-archived prepend))
  5055. ;; Specials
  5056. '(org-do-latex-and-related)
  5057. '(org-fontify-entities)
  5058. '(org-raise-scripts)
  5059. ;; Code
  5060. '(org-activate-code (1 'org-code t))
  5061. ;; COMMENT
  5062. (list (format
  5063. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5064. org-todo-regexp
  5065. org-comment-string)
  5066. '(9 'org-special-keyword t))
  5067. ;; Blocks and meta lines
  5068. '(org-fontify-meta-lines-and-blocks))))
  5069. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5070. (run-hooks 'org-font-lock-set-keywords-hook)
  5071. ;; Now set the full font-lock-keywords
  5072. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5073. (setq-local font-lock-defaults
  5074. '(org-font-lock-keywords t nil nil backward-paragraph))
  5075. (setq-local font-lock-extend-after-change-region-function
  5076. #'org-fontify-extend-region)
  5077. (kill-local-variable 'font-lock-keywords)
  5078. nil))
  5079. (defun org-toggle-pretty-entities ()
  5080. "Toggle the composition display of entities as UTF8 characters."
  5081. (interactive)
  5082. (setq-local org-pretty-entities (not org-pretty-entities))
  5083. (org-restart-font-lock)
  5084. (if org-pretty-entities
  5085. (message "Entities are now displayed as UTF8 characters")
  5086. (save-restriction
  5087. (widen)
  5088. (decompose-region (point-min) (point-max))
  5089. (message "Entities are now displayed as plain text"))))
  5090. (defvar-local org-custom-properties-overlays nil
  5091. "List of overlays used for custom properties.")
  5092. (defun org-toggle-custom-properties-visibility ()
  5093. "Display or hide properties in `org-custom-properties'."
  5094. (interactive)
  5095. (if org-custom-properties-overlays
  5096. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5097. (setq org-custom-properties-overlays nil))
  5098. (when org-custom-properties
  5099. (org-with-wide-buffer
  5100. (goto-char (point-min))
  5101. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5102. (while (re-search-forward regexp nil t)
  5103. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5104. (when (and end (< (point) end))
  5105. ;; Hide first custom property in current drawer.
  5106. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5107. (overlay-put o 'invisible t)
  5108. (overlay-put o 'org-custom-property t)
  5109. (push o org-custom-properties-overlays))
  5110. ;; Hide additional custom properties in the same drawer.
  5111. (while (re-search-forward regexp end t)
  5112. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5113. (overlay-put o 'invisible t)
  5114. (overlay-put o 'org-custom-property t)
  5115. (push o org-custom-properties-overlays)))))
  5116. ;; Each entry is limited to a single property drawer.
  5117. (outline-next-heading)))))))
  5118. (defun org-fontify-entities (limit)
  5119. "Find an entity to fontify."
  5120. (let (ee)
  5121. (when org-pretty-entities
  5122. (catch 'match
  5123. ;; "\_ "-family is left out on purpose. Only the first one,
  5124. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5125. ;; confusing when adding a second white space character.
  5126. (while (re-search-forward
  5127. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5128. limit t)
  5129. (when (and (not (org-at-comment-p))
  5130. (setq ee (org-entity-get (match-string 1)))
  5131. (= (length (nth 6 ee)) 1))
  5132. (let* ((end (if (equal (match-string 2) "{}")
  5133. (match-end 2)
  5134. (match-end 1))))
  5135. (add-text-properties
  5136. (match-beginning 0) end
  5137. (list 'font-lock-fontified t))
  5138. (compose-region (match-beginning 0) end
  5139. (nth 6 ee) nil)
  5140. (backward-char 1)
  5141. (throw 'match t))))
  5142. nil))))
  5143. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5144. "Fontify string S like in Org mode."
  5145. (with-temp-buffer
  5146. (insert s)
  5147. (let ((org-odd-levels-only odd-levels))
  5148. (org-mode)
  5149. (org-font-lock-ensure)
  5150. (buffer-string))))
  5151. (defun org-get-level-face (n)
  5152. "Get the right face for match N in font-lock matching of headlines."
  5153. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5154. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5155. (org-f (if org-cycle-level-faces
  5156. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5157. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5158. (cond
  5159. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5160. ((eq n 2) org-f)
  5161. (t (unless org-level-color-stars-only org-f)))))
  5162. (defun org-face-from-face-or-color (context inherit face-or-color)
  5163. "Create a face list that inherits INHERIT, but sets the foreground color.
  5164. When FACE-OR-COLOR is not a string, just return it."
  5165. (if (stringp face-or-color)
  5166. (list :inherit inherit
  5167. (cdr (assoc context org-faces-easy-properties))
  5168. face-or-color)
  5169. face-or-color))
  5170. (defun org-get-todo-face (kwd)
  5171. "Get the right face for a TODO keyword KWD.
  5172. If KWD is a number, get the corresponding match group."
  5173. (when (numberp kwd) (setq kwd (match-string kwd)))
  5174. (or (org-face-from-face-or-color
  5175. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5176. (and (member kwd org-done-keywords) 'org-done)
  5177. 'org-todo))
  5178. (defun org-get-priority-face (priority)
  5179. "Get the right face for PRIORITY.
  5180. PRIORITY is a character."
  5181. (or (org-face-from-face-or-color
  5182. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5183. 'org-priority))
  5184. (defun org-get-tag-face (tag)
  5185. "Get the right face for TAG.
  5186. If TAG is a number, get the corresponding match group."
  5187. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5188. (or (org-face-from-face-or-color
  5189. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5190. 'org-tag)))
  5191. (defvar org-priority-regexp) ; defined later in the file
  5192. (defun org-font-lock-add-priority-faces (limit)
  5193. "Add the special priority faces."
  5194. (while (re-search-forward org-priority-regexp limit t)
  5195. (add-text-properties
  5196. (match-beginning 1) (match-end 1)
  5197. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5198. 'font-lock-fontified t))))
  5199. (defun org-font-lock-add-tag-faces (limit)
  5200. "Add the special tag faces."
  5201. (when (and org-tag-faces org-tags-special-faces-re)
  5202. (while (re-search-forward org-tags-special-faces-re limit t)
  5203. (add-text-properties (match-beginning 1) (match-end 1)
  5204. (list 'face (org-get-tag-face 1)
  5205. 'font-lock-fontified t))
  5206. (backward-char 1))))
  5207. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5208. "Remove fontification and activation overlays from links."
  5209. (font-lock-default-unfontify-region beg end)
  5210. (let* ((buffer-undo-list t)
  5211. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5212. (inhibit-modification-hooks t)
  5213. deactivate-mark buffer-file-name buffer-file-truename)
  5214. (decompose-region beg end)
  5215. (remove-text-properties beg end
  5216. '(mouse-face t keymap t org-linked-text t
  5217. invisible t intangible t
  5218. org-emphasis t))
  5219. (org-remove-font-lock-display-properties beg end)))
  5220. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5221. ((raise 0.3) (height 0.7))
  5222. ((raise -0.5))
  5223. ((raise 0.5)))
  5224. "Display properties for showing superscripts and subscripts.")
  5225. (defun org-remove-font-lock-display-properties (beg end)
  5226. "Remove specific display properties that have been added by font lock.
  5227. The will remove the raise properties that are used to show superscripts
  5228. and subscripts."
  5229. (let (next prop)
  5230. (while (< beg end)
  5231. (setq next (next-single-property-change beg 'display nil end)
  5232. prop (get-text-property beg 'display))
  5233. (when (member prop org-script-display)
  5234. (put-text-property beg next 'display nil))
  5235. (setq beg next))))
  5236. (defun org-raise-scripts (limit)
  5237. "Add raise properties to sub/superscripts."
  5238. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5239. (re-search-forward
  5240. (if (eq org-use-sub-superscripts t)
  5241. org-match-substring-regexp
  5242. org-match-substring-with-braces-regexp)
  5243. limit t))
  5244. (let* ((pos (point)) table-p comment-p
  5245. (mpos (match-beginning 3))
  5246. (emph-p (get-text-property mpos 'org-emphasis))
  5247. (link-p (get-text-property mpos 'mouse-face))
  5248. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5249. (goto-char (point-at-bol))
  5250. (setq table-p (looking-at-p org-table-dataline-regexp)
  5251. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5252. (goto-char pos)
  5253. ;; Handle a_b^c
  5254. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5255. (unless (or comment-p emph-p link-p keyw-p)
  5256. (put-text-property (match-beginning 3) (match-end 0)
  5257. 'display
  5258. (if (equal (char-after (match-beginning 2)) ?^)
  5259. (nth (if table-p 3 1) org-script-display)
  5260. (nth (if table-p 2 0) org-script-display)))
  5261. (add-text-properties (match-beginning 2) (match-end 2)
  5262. (list 'invisible t))
  5263. (when (and (eq (char-after (match-beginning 3)) ?{)
  5264. (eq (char-before (match-end 3)) ?}))
  5265. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5266. (list 'invisible t))
  5267. (add-text-properties (1- (match-end 3)) (match-end 3)
  5268. (list 'invisible t))))
  5269. t)))
  5270. (defun org-remove-empty-overlays-at (pos)
  5271. "Remove outline overlays that do not contain non-white stuff."
  5272. (dolist (o (overlays-at pos))
  5273. (and (eq 'outline (overlay-get o 'invisible))
  5274. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5275. (overlay-end o))))
  5276. (delete-overlay o))))
  5277. (defun org-show-empty-lines-in-parent ()
  5278. "Move to the parent and re-show empty lines before visible headlines."
  5279. (save-excursion
  5280. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5281. (org-cycle-show-empty-lines context))))
  5282. (defun org-files-list ()
  5283. "Return `org-agenda-files' list, plus all open Org files.
  5284. This is useful for operations that need to scan all of a user's
  5285. open and agenda-wise Org files."
  5286. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5287. (dolist (buf (buffer-list))
  5288. (with-current-buffer buf
  5289. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5290. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5291. :test #'equal))))
  5292. files))
  5293. (defsubst org-entry-beginning-position ()
  5294. "Return the beginning position of the current entry."
  5295. (save-excursion (org-back-to-heading t) (point)))
  5296. (defsubst org-entry-end-position ()
  5297. "Return the end position of the current entry."
  5298. (save-excursion (outline-next-heading) (point)))
  5299. (defun org-subtree-end-visible-p ()
  5300. "Is the end of the current subtree visible?"
  5301. (pos-visible-in-window-p
  5302. (save-excursion (org-end-of-subtree t) (point))))
  5303. (defun org-first-headline-recenter ()
  5304. "Move cursor to the first headline and recenter the headline."
  5305. (let ((window (get-buffer-window)))
  5306. (when window
  5307. (goto-char (point-min))
  5308. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5309. (set-window-start window (line-beginning-position))))))
  5310. ;;; Visibility (headlines, blocks, drawers)
  5311. ;;;; Headlines visibility
  5312. (defun org-show-entry ()
  5313. "Show the body directly following this heading.
  5314. Show the heading too, if it is currently invisible."
  5315. (interactive)
  5316. (save-excursion
  5317. (ignore-errors
  5318. (org-back-to-heading t)
  5319. (org-flag-region
  5320. (line-end-position 0)
  5321. (save-excursion
  5322. (if (re-search-forward
  5323. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5324. (match-beginning 1)
  5325. (point-max)))
  5326. nil
  5327. 'outline))))
  5328. (defun org-show-children (&optional level)
  5329. "Show all direct subheadings of this heading.
  5330. Prefix arg LEVEL is how many levels below the current level
  5331. should be shown. Default is enough to cause the following
  5332. heading to appear."
  5333. (interactive "p")
  5334. (save-excursion
  5335. (org-back-to-heading t)
  5336. (let* ((current-level (funcall outline-level))
  5337. (max-level (org-get-valid-level
  5338. current-level
  5339. (if level (prefix-numeric-value level) 1)))
  5340. (end (save-excursion (org-end-of-subtree t t)))
  5341. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5342. (past-first-child nil)
  5343. ;; Make sure to skip inlinetasks.
  5344. (re (format regexp-fmt
  5345. current-level
  5346. (cond
  5347. ((not (featurep 'org-inlinetask)) "")
  5348. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5349. 3))
  5350. (t (1- org-inlinetask-min-level))))))
  5351. ;; Display parent heading.
  5352. (org-flag-heading nil)
  5353. (forward-line)
  5354. ;; Display children. First child may be deeper than expected
  5355. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5356. ;; MAX-LEVEL accordingly.
  5357. (while (re-search-forward re end t)
  5358. (unless past-first-child
  5359. (setq re (format regexp-fmt
  5360. current-level
  5361. (max (funcall outline-level) max-level)))
  5362. (setq past-first-child t))
  5363. (org-flag-heading nil)))))
  5364. (defun org-show-subtree ()
  5365. "Show everything after this heading at deeper levels."
  5366. (interactive)
  5367. (org-flag-region
  5368. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5369. ;;;; Blocks visibility
  5370. (defun org-hide-block-toggle-maybe ()
  5371. "Toggle visibility of block at point.
  5372. Unlike to `org-hide-block-toggle', this function does not throw
  5373. an error. Return a non-nil value when toggling is successful."
  5374. (interactive)
  5375. (ignore-errors (org-hide-block-toggle)))
  5376. (defun org-hide-block-toggle (&optional force)
  5377. "Toggle the visibility of the current block.
  5378. When optional argument FORCE is `off', make block visible. If it
  5379. is non-nil, hide it unconditionally. Throw an error when not at
  5380. a block. Return a non-nil value when toggling is successful."
  5381. (interactive)
  5382. (let ((element (org-element-at-point)))
  5383. (unless (memq (org-element-type element)
  5384. '(center-block comment-block dynamic-block example-block
  5385. export-block quote-block special-block
  5386. src-block verse-block))
  5387. (user-error "Not at a block"))
  5388. (let* ((post (org-element-property :post-affiliated element))
  5389. (start (save-excursion
  5390. (goto-char post)
  5391. (line-end-position)))
  5392. (end (save-excursion
  5393. (goto-char (org-element-property :end element))
  5394. (skip-chars-backward " \t\n")
  5395. (line-end-position))))
  5396. ;; Do nothing when not before or at the block opening line or at
  5397. ;; the block closing line.
  5398. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5399. (cond ((eq force 'off)
  5400. (org-flag-region start end nil 'org-hide-block))
  5401. (force
  5402. (org-flag-region start end t 'org-hide-block))
  5403. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5404. (org-flag-region start end nil 'org-hide-block))
  5405. (t
  5406. (org-flag-region start end t 'org-hide-block)))
  5407. ;; When the block is hidden away, make sure point is left in
  5408. ;; a visible part of the buffer.
  5409. (when (invisible-p (max (1- (point)) (point-min)))
  5410. (goto-char post))
  5411. ;; Signal success.
  5412. t))))
  5413. (defun org-hide-block-toggle-all ()
  5414. "Toggle the visibility of all blocks in the current buffer."
  5415. (org-block-map 'org-hide-block-toggle))
  5416. (defun org-hide-block-all ()
  5417. "Fold all blocks in the current buffer."
  5418. (interactive)
  5419. (org-show-all '(blocks))
  5420. (org-block-map 'org-hide-block-toggle-maybe))
  5421. ;;;; Drawers visibility
  5422. (defun org-cycle-hide-drawers (state &optional exceptions)
  5423. "Re-hide all drawers after a visibility state change.
  5424. STATE should be one of the symbols listed in the docstring of
  5425. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5426. a list of strings specifying which drawers should not be hidden."
  5427. (when (and (derived-mode-p 'org-mode)
  5428. (not (memq state '(overview folded contents))))
  5429. (save-excursion
  5430. (let* ((globalp (eq state 'all))
  5431. (beg (if globalp (point-min) (point)))
  5432. (end (if globalp (point-max)
  5433. (if (eq state 'children)
  5434. (save-excursion (outline-next-heading) (point))
  5435. (org-end-of-subtree t)))))
  5436. (goto-char beg)
  5437. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5438. (unless (member-ignore-case (match-string 1) exceptions)
  5439. (let ((drawer (org-element-at-point)))
  5440. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5441. (org-flag-drawer t drawer)
  5442. ;; Make sure to skip drawer entirely or we might flag
  5443. ;; it another time when matching its ending line with
  5444. ;; `org-drawer-regexp'.
  5445. (goto-char (org-element-property :end drawer))))))))))
  5446. (defun org-flag-drawer (flag &optional element beg end)
  5447. "When FLAG is non-nil, hide the drawer we are at.
  5448. Otherwise make it visible.
  5449. When optional argument ELEMENT is a parsed drawer, as returned by
  5450. `org-element-at-point', hide or show that drawer instead.
  5451. When buffer positions BEG and END are provided, hide or show that
  5452. region as a drawer without further ado."
  5453. (if (and beg end) (org-flag-region beg end flag 'org-hide-drawer)
  5454. (let ((drawer (or element
  5455. (and (save-excursion
  5456. (beginning-of-line)
  5457. (looking-at-p org-drawer-regexp))
  5458. (org-element-at-point)))))
  5459. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5460. (let ((post (org-element-property :post-affiliated drawer)))
  5461. (org-flag-region
  5462. (save-excursion (goto-char post) (line-end-position))
  5463. (save-excursion (goto-char (org-element-property :end drawer))
  5464. (skip-chars-backward " \t\n")
  5465. (line-end-position))
  5466. flag 'org-hide-drawer)
  5467. ;; When the drawer is hidden away, make sure point lies in
  5468. ;; a visible part of the buffer.
  5469. (when (invisible-p (max (1- (point)) (point-min)))
  5470. (goto-char post)))))))
  5471. ;;;; Visibility cycling
  5472. (defvar-local org-cycle-global-status nil)
  5473. (put 'org-cycle-global-status 'org-state t)
  5474. (defvar-local org-cycle-subtree-status nil)
  5475. (put 'org-cycle-subtree-status 'org-state t)
  5476. (defun org-show-all (&optional types)
  5477. "Show all contents in the visible part of the buffer.
  5478. By default, the function expands headings, blocks and drawers.
  5479. When optional argument TYPE is a list of symbols among `blocks',
  5480. `drawers' and `headings', to only expand one specific type."
  5481. (interactive)
  5482. (dolist (type (or types '(blocks drawers headings)))
  5483. (org-flag-region (point-min) (point-max) nil
  5484. (pcase type
  5485. (`blocks 'org-hide-block)
  5486. (`drawers 'org-hide-drawer)
  5487. (`headings 'outline)
  5488. (_ (error "Invalid type: %S" type))))))
  5489. ;;;###autoload
  5490. (defun org-cycle (&optional arg)
  5491. "TAB-action and visibility cycling for Org mode.
  5492. This is the command invoked in Org mode by the `TAB' key. Its main
  5493. purpose is outline visibility cycling, but it also invokes other actions
  5494. in special contexts.
  5495. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5496. the entire
  5497. buffer through 3 states (global cycling)
  5498. 1. OVERVIEW: Show only top-level headlines.
  5499. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5500. 3. SHOW ALL: Show everything.
  5501. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5502. switch to the startup visibility,
  5503. determined by the variable `org-startup-folded', and by any VISIBILITY
  5504. properties in the buffer.
  5505. With a `\\[universal-argument] \\[universal-argument] \
  5506. \\[universal-argument]' prefix argument, show the entire buffer, including
  5507. any drawers.
  5508. When inside a table, re-align the table and move to the next field.
  5509. When point is at the beginning of a headline, rotate the subtree started
  5510. by this line through 3 different states (local cycling)
  5511. 1. FOLDED: Only the main headline is shown.
  5512. 2. CHILDREN: The main headline and the direct children are shown.
  5513. From this state, you can move to one of the children
  5514. and zoom in further.
  5515. 3. SUBTREE: Show the entire subtree, including body text.
  5516. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5517. When point is at the beginning of an empty headline and the variable
  5518. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5519. of the headline by demoting and promoting it to likely levels. This
  5520. speeds up creation document structure by pressing `TAB' once or several
  5521. times right after creating a new headline.
  5522. When there is a numeric prefix, go up to a heading with level ARG, do
  5523. a `show-subtree' and return to the previous cursor position. If ARG
  5524. is negative, go up that many levels.
  5525. When point is not at the beginning of a headline, execute the global
  5526. binding for `TAB', which is re-indenting the line. See the option
  5527. `org-cycle-emulate-tab' for details.
  5528. As a special case, if point is at the beginning of the buffer and there is
  5529. no headline in line 1, this function will act as if called with prefix arg
  5530. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5531. prefix arg, but only
  5532. if the variable `org-cycle-global-at-bob' is t."
  5533. (interactive "P")
  5534. (org-load-modules-maybe)
  5535. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5536. (and org-cycle-level-after-item/entry-creation
  5537. (or (org-cycle-level)
  5538. (org-cycle-item-indentation))))
  5539. (let* ((limit-level
  5540. (or org-cycle-max-level
  5541. (and (boundp 'org-inlinetask-min-level)
  5542. org-inlinetask-min-level
  5543. (1- org-inlinetask-min-level))))
  5544. (nstars (and limit-level
  5545. (if org-odd-levels-only
  5546. (and limit-level (1- (* limit-level 2)))
  5547. limit-level)))
  5548. (org-outline-regexp
  5549. (if (not (derived-mode-p 'org-mode))
  5550. outline-regexp
  5551. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5552. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5553. (not (looking-at org-outline-regexp))))
  5554. (org-cycle-hook
  5555. (if bob-special
  5556. (delq 'org-optimize-window-after-visibility-change
  5557. (copy-sequence org-cycle-hook))
  5558. org-cycle-hook))
  5559. (pos (point)))
  5560. (cond
  5561. ((equal arg '(16))
  5562. (setq last-command 'dummy)
  5563. (org-set-startup-visibility)
  5564. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5565. ((equal arg '(64))
  5566. (org-show-all)
  5567. (org-unlogged-message "Entire buffer visible, including drawers"))
  5568. ((equal arg '(4)) (org-cycle-internal-global))
  5569. ;; Try hiding block at point.
  5570. ((org-hide-block-toggle-maybe))
  5571. ;; Try cdlatex TAB completion
  5572. ((org-try-cdlatex-tab))
  5573. ;; Table: enter it or move to the next field.
  5574. ((org-at-table-p 'any)
  5575. (if (org-at-table.el-p)
  5576. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5577. Use `\\[org-edit-special]' to edit table.el tables"))
  5578. (if arg (org-table-edit-field t)
  5579. (org-table-justify-field-maybe)
  5580. (call-interactively 'org-table-next-field))))
  5581. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5582. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5583. (bob-special (org-cycle-internal-global))
  5584. ;; Drawers: delegate to `org-flag-drawer'.
  5585. ((save-excursion
  5586. (beginning-of-line 1)
  5587. (looking-at org-drawer-regexp))
  5588. (org-flag-drawer ; toggle block visibility
  5589. (not (get-char-property (match-end 0) 'invisible))))
  5590. ;; Show-subtree, ARG levels up from here.
  5591. ((integerp arg)
  5592. (save-excursion
  5593. (org-back-to-heading)
  5594. (outline-up-heading (if (< arg 0) (- arg)
  5595. (- (funcall outline-level) arg)))
  5596. (org-show-subtree)))
  5597. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5598. ((and (featurep 'org-inlinetask)
  5599. (org-inlinetask-at-task-p)
  5600. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5601. (org-inlinetask-toggle-visibility))
  5602. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5603. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5604. (save-excursion (move-beginning-of-line 1)
  5605. (looking-at org-outline-regexp)))
  5606. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5607. (org-cycle-internal-local))
  5608. ;; From there: TAB emulation and template completion.
  5609. (buffer-read-only (org-back-to-heading))
  5610. ((run-hook-with-args-until-success
  5611. 'org-tab-after-check-for-cycling-hook))
  5612. ((run-hook-with-args-until-success
  5613. 'org-tab-before-tab-emulation-hook))
  5614. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5615. (or (not (bolp))
  5616. (not (looking-at org-outline-regexp))))
  5617. (call-interactively (global-key-binding "\t")))
  5618. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5619. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5620. (or (and (eq org-cycle-emulate-tab 'white)
  5621. (= (match-end 0) (point-at-eol)))
  5622. (and (eq org-cycle-emulate-tab 'whitestart)
  5623. (>= (match-end 0) pos))))
  5624. t
  5625. (eq org-cycle-emulate-tab t))
  5626. (call-interactively (global-key-binding "\t")))
  5627. (t (save-excursion
  5628. (org-back-to-heading)
  5629. (org-cycle)))))))
  5630. (defun org-cycle-internal-global ()
  5631. "Do the global cycling action."
  5632. ;; Hack to avoid display of messages for .org attachments in Gnus
  5633. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5634. (cond
  5635. ((and (eq last-command this-command)
  5636. (eq org-cycle-global-status 'overview))
  5637. ;; We just created the overview - now do table of contents
  5638. ;; This can be slow in very large buffers, so indicate action
  5639. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5640. (unless ga (org-unlogged-message "CONTENTS..."))
  5641. (org-content)
  5642. (unless ga (org-unlogged-message "CONTENTS...done"))
  5643. (setq org-cycle-global-status 'contents)
  5644. (run-hook-with-args 'org-cycle-hook 'contents))
  5645. ((and (eq last-command this-command)
  5646. (eq org-cycle-global-status 'contents))
  5647. ;; We just showed the table of contents - now show everything
  5648. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5649. (org-show-all '(headings blocks))
  5650. (unless ga (org-unlogged-message "SHOW ALL"))
  5651. (setq org-cycle-global-status 'all)
  5652. (run-hook-with-args 'org-cycle-hook 'all))
  5653. (t
  5654. ;; Default action: go to overview
  5655. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5656. (org-overview)
  5657. (unless ga (org-unlogged-message "OVERVIEW"))
  5658. (setq org-cycle-global-status 'overview)
  5659. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5660. (defvar org-called-with-limited-levels nil
  5661. "Non-nil when `org-with-limited-levels' is currently active.")
  5662. (defun org-cycle-internal-local ()
  5663. "Do the local cycling action."
  5664. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5665. ;; First, determine end of headline (EOH), end of subtree or item
  5666. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5667. (save-excursion
  5668. (if (org-at-item-p)
  5669. (progn
  5670. (beginning-of-line)
  5671. (setq struct (org-list-struct))
  5672. (setq eoh (point-at-eol))
  5673. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5674. (setq has-children (org-list-has-child-p (point) struct)))
  5675. (org-back-to-heading)
  5676. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5677. (setq eos (save-excursion (org-end-of-subtree t t)
  5678. (when (bolp) (backward-char)) (point)))
  5679. (setq has-children
  5680. (save-excursion
  5681. (let ((level (funcall outline-level)))
  5682. (outline-next-heading)
  5683. (and (org-at-heading-p t)
  5684. (> (funcall outline-level) level))))))
  5685. ;; Determine end invisible part of buffer (EOL)
  5686. (beginning-of-line 2)
  5687. (while (and (not (eobp)) ;This is like `next-line'.
  5688. (get-char-property (1- (point)) 'invisible))
  5689. (goto-char (next-single-char-property-change (point) 'invisible))
  5690. (and (eolp) (beginning-of-line 2)))
  5691. (setq eol (point)))
  5692. ;; Find out what to do next and set `this-command'
  5693. (cond
  5694. ((= eos eoh)
  5695. ;; Nothing is hidden behind this heading
  5696. (unless (org-before-first-heading-p)
  5697. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5698. (org-unlogged-message "EMPTY ENTRY")
  5699. (setq org-cycle-subtree-status nil)
  5700. (save-excursion
  5701. (goto-char eos)
  5702. (outline-next-heading)
  5703. (when (org-invisible-p) (org-flag-heading nil))))
  5704. ((and (or (>= eol eos)
  5705. (not (string-match "\\S-" (buffer-substring eol eos))))
  5706. (or has-children
  5707. (not (setq children-skipped
  5708. org-cycle-skip-children-state-if-no-children))))
  5709. ;; Entire subtree is hidden in one line: children view
  5710. (unless (org-before-first-heading-p)
  5711. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5712. (if (org-at-item-p)
  5713. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5714. (org-show-entry)
  5715. (org-with-limited-levels (org-show-children))
  5716. (org-show-set-visibility 'canonical)
  5717. ;; Fold every list in subtree to top-level items.
  5718. (when (eq org-cycle-include-plain-lists 'integrate)
  5719. (save-excursion
  5720. (org-back-to-heading)
  5721. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5722. (beginning-of-line 1)
  5723. (let* ((struct (org-list-struct))
  5724. (prevs (org-list-prevs-alist struct))
  5725. (end (org-list-get-bottom-point struct)))
  5726. (dolist (e (org-list-get-all-items (point) struct prevs))
  5727. (org-list-set-item-visibility e struct 'folded))
  5728. (goto-char (if (< end eos) end eos)))))))
  5729. (org-unlogged-message "CHILDREN")
  5730. (save-excursion
  5731. (goto-char eos)
  5732. (outline-next-heading)
  5733. (when (org-invisible-p) (org-flag-heading nil)))
  5734. (setq org-cycle-subtree-status 'children)
  5735. (unless (org-before-first-heading-p)
  5736. (run-hook-with-args 'org-cycle-hook 'children)))
  5737. ((or children-skipped
  5738. (and (eq last-command this-command)
  5739. (eq org-cycle-subtree-status 'children)))
  5740. ;; We just showed the children, or no children are there,
  5741. ;; now show everything.
  5742. (unless (org-before-first-heading-p)
  5743. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5744. (org-flag-region eoh eos nil 'outline)
  5745. (org-unlogged-message
  5746. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5747. (setq org-cycle-subtree-status 'subtree)
  5748. (unless (org-before-first-heading-p)
  5749. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5750. (t
  5751. ;; Default action: hide the subtree.
  5752. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5753. (org-flag-region eoh eos t 'outline)
  5754. (org-unlogged-message "FOLDED")
  5755. (setq org-cycle-subtree-status 'folded)
  5756. (unless (org-before-first-heading-p)
  5757. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5758. ;;;###autoload
  5759. (defun org-global-cycle (&optional arg)
  5760. "Cycle the global visibility. For details see `org-cycle'.
  5761. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5762. With a numeric prefix, show all headlines up to that level."
  5763. (interactive "P")
  5764. (let ((org-cycle-include-plain-lists
  5765. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  5766. (cond
  5767. ((integerp arg)
  5768. (org-show-all '(headings blocks))
  5769. (outline-hide-sublevels arg)
  5770. (setq org-cycle-global-status 'contents))
  5771. ((equal arg '(4))
  5772. (org-set-startup-visibility)
  5773. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5774. (t
  5775. (org-cycle '(4))))))
  5776. (defun org-set-startup-visibility ()
  5777. "Set the visibility required by startup options and properties."
  5778. (cond
  5779. ((eq org-startup-folded t)
  5780. (org-overview))
  5781. ((eq org-startup-folded 'content)
  5782. (org-content))
  5783. ((or (eq org-startup-folded 'showeverything)
  5784. (eq org-startup-folded nil))
  5785. (org-show-all)))
  5786. (unless (eq org-startup-folded 'showeverything)
  5787. (when org-hide-block-startup (org-hide-block-all))
  5788. (org-set-visibility-according-to-property)
  5789. (org-cycle-hide-archived-subtrees 'all)
  5790. (org-cycle-hide-drawers 'all)
  5791. (org-cycle-show-empty-lines t)))
  5792. (defun org-set-visibility-according-to-property ()
  5793. "Switch subtree visibility according to VISIBILITY property."
  5794. (interactive)
  5795. (let ((regexp (org-re-property "VISIBILITY")))
  5796. (org-with-point-at 1
  5797. (while (re-search-forward regexp nil t)
  5798. (let ((state (match-string 3)))
  5799. (if (not (org-at-property-p)) (outline-next-heading)
  5800. (save-excursion
  5801. (org-back-to-heading t)
  5802. (org-flag-subtree t)
  5803. (org-reveal)
  5804. (pcase state
  5805. ("folded"
  5806. (org-flag-subtree t))
  5807. ("children"
  5808. (org-show-hidden-entry)
  5809. (org-show-children))
  5810. ("content"
  5811. (save-excursion
  5812. (save-restriction
  5813. (org-narrow-to-subtree)
  5814. (org-content))))
  5815. ((or "all" "showall")
  5816. (outline-show-subtree))
  5817. (_ nil)))
  5818. (org-end-of-subtree)))))))
  5819. (defun org-overview ()
  5820. "Switch to overview mode, showing only top-level headlines.
  5821. This shows all headlines with a level equal or greater than the level
  5822. of the first headline in the buffer. This is important, because if the
  5823. first headline is not level one, then (hide-sublevels 1) gives confusing
  5824. results."
  5825. (interactive)
  5826. (save-excursion
  5827. (let ((level
  5828. (save-excursion
  5829. (goto-char (point-min))
  5830. (when (re-search-forward org-outline-regexp-bol nil t)
  5831. (goto-char (match-beginning 0))
  5832. (funcall outline-level)))))
  5833. (and level (outline-hide-sublevels level)))))
  5834. (defun org-content (&optional arg)
  5835. "Show all headlines in the buffer, like a table of contents.
  5836. With numerical argument N, show content up to level N."
  5837. (interactive "P")
  5838. (org-overview)
  5839. (save-excursion
  5840. ;; Visit all headings and show their offspring
  5841. (and (integerp arg) (org-overview))
  5842. (goto-char (point-max))
  5843. (catch 'exit
  5844. (while (and (progn (condition-case nil
  5845. (outline-previous-visible-heading 1)
  5846. (error (goto-char (point-min))))
  5847. t)
  5848. (looking-at org-outline-regexp))
  5849. (if (integerp arg)
  5850. (org-show-children (1- arg))
  5851. (outline-show-branches))
  5852. (when (bobp) (throw 'exit nil))))))
  5853. (defun org-optimize-window-after-visibility-change (state)
  5854. "Adjust the window after a change in outline visibility.
  5855. This function is the default value of the hook `org-cycle-hook'."
  5856. (when (get-buffer-window (current-buffer))
  5857. (cond
  5858. ((eq state 'content) nil)
  5859. ((eq state 'all) nil)
  5860. ((eq state 'folded) nil)
  5861. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  5862. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  5863. (defun org-clean-visibility-after-subtree-move ()
  5864. "Fix visibility issues after moving a subtree."
  5865. ;; First, find a reasonable region to look at:
  5866. ;; Start two siblings above, end three below
  5867. (let* ((beg (save-excursion
  5868. (and (org-get-last-sibling)
  5869. (org-get-last-sibling))
  5870. (point)))
  5871. (end (save-excursion
  5872. (and (org-get-next-sibling)
  5873. (org-get-next-sibling)
  5874. (org-get-next-sibling))
  5875. (if (org-at-heading-p)
  5876. (point-at-eol)
  5877. (point))))
  5878. (level (looking-at "\\*+"))
  5879. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5880. (save-excursion
  5881. (save-restriction
  5882. (narrow-to-region beg end)
  5883. (when re
  5884. ;; Properly fold already folded siblings
  5885. (goto-char (point-min))
  5886. (while (re-search-forward re nil t)
  5887. (when (and (not (org-invisible-p))
  5888. (org-invisible-p (line-end-position)))
  5889. (outline-hide-entry))))
  5890. (org-cycle-hide-drawers 'all)
  5891. (org-cycle-show-empty-lines 'overview)))))
  5892. (defun org-cycle-show-empty-lines (state)
  5893. "Show empty lines above all visible headlines.
  5894. The region to be covered depends on STATE when called through
  5895. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5896. entire buffer covered. Note that an empty line is only shown if there
  5897. are at least `org-cycle-separator-lines' empty lines before the headline."
  5898. (when (/= org-cycle-separator-lines 0)
  5899. (save-excursion
  5900. (let* ((n (abs org-cycle-separator-lines))
  5901. (re (cond
  5902. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5903. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5904. (t (let ((ns (number-to-string (- n 2))))
  5905. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5906. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5907. beg end)
  5908. (cond
  5909. ((memq state '(overview contents t))
  5910. (setq beg (point-min) end (point-max)))
  5911. ((memq state '(children folded))
  5912. (setq beg (point)
  5913. end (progn (org-end-of-subtree t t)
  5914. (line-beginning-position 2)))))
  5915. (when beg
  5916. (goto-char beg)
  5917. (while (re-search-forward re end t)
  5918. (unless (get-char-property (match-end 1) 'invisible)
  5919. (let ((e (match-end 1))
  5920. (b (if (>= org-cycle-separator-lines 0)
  5921. (match-beginning 1)
  5922. (save-excursion
  5923. (goto-char (match-beginning 0))
  5924. (skip-chars-backward " \t\n")
  5925. (line-end-position)))))
  5926. (org-flag-region b e nil 'outline))))))))
  5927. ;; Never hide empty lines at the end of the file.
  5928. (save-excursion
  5929. (goto-char (point-max))
  5930. (outline-previous-heading)
  5931. (outline-end-of-heading)
  5932. (when (and (looking-at "[ \t\n]+")
  5933. (= (match-end 0) (point-max)))
  5934. (org-flag-region (point) (match-end 0) nil 'outline))))
  5935. ;;;; Reveal point location
  5936. (defun org-show-context (&optional key)
  5937. "Make sure point and context are visible.
  5938. Optional argument KEY, when non-nil, is a symbol. See
  5939. `org-show-context-detail' for allowed values and how much is to
  5940. be shown."
  5941. (org-show-set-visibility
  5942. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  5943. ((cdr (assq key org-show-context-detail)))
  5944. (t (cdr (assq 'default org-show-context-detail))))))
  5945. (defun org-show-set-visibility (detail)
  5946. "Set visibility around point according to DETAIL.
  5947. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  5948. `tree', `canonical' or t. See `org-show-context-detail' for more
  5949. information."
  5950. ;; Show current heading and possibly its entry, following headline
  5951. ;; or all children.
  5952. (if (and (org-at-heading-p) (not (eq detail 'local)))
  5953. (org-flag-heading nil)
  5954. (org-show-entry)
  5955. ;; If point is hidden within a drawer or a block, make sure to
  5956. ;; expose it.
  5957. (dolist (o (overlays-at (point)))
  5958. (when (memq (overlay-get o 'invisible)
  5959. '(org-hide-block org-hide-drawer outline))
  5960. (delete-overlay o)))
  5961. (unless (org-before-first-heading-p)
  5962. (org-with-limited-levels
  5963. (cl-case detail
  5964. ((tree canonical t) (org-show-children))
  5965. ((nil minimal ancestors))
  5966. (t (save-excursion
  5967. (outline-next-heading)
  5968. (org-flag-heading nil)))))))
  5969. ;; Show all siblings.
  5970. (when (eq detail 'lineage) (org-show-siblings))
  5971. ;; Show ancestors, possibly with their children.
  5972. (when (memq detail '(ancestors lineage tree canonical t))
  5973. (save-excursion
  5974. (while (org-up-heading-safe)
  5975. (org-flag-heading nil)
  5976. (when (memq detail '(canonical t)) (org-show-entry))
  5977. (when (memq detail '(tree canonical t)) (org-show-children))))))
  5978. (defvar org-reveal-start-hook nil
  5979. "Hook run before revealing a location.")
  5980. (defun org-reveal (&optional siblings)
  5981. "Show current entry, hierarchy above it, and the following headline.
  5982. This can be used to show a consistent set of context around
  5983. locations exposed with `org-show-context'.
  5984. With optional argument SIBLINGS, on each level of the hierarchy all
  5985. siblings are shown. This repairs the tree structure to what it would
  5986. look like when opened with hierarchical calls to `org-cycle'.
  5987. With a \\[universal-argument] \\[universal-argument] prefix, \
  5988. go to the parent and show the entire tree."
  5989. (interactive "P")
  5990. (run-hooks 'org-reveal-start-hook)
  5991. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  5992. ((equal siblings '(16))
  5993. (save-excursion
  5994. (when (org-up-heading-safe)
  5995. (org-show-subtree)
  5996. (run-hook-with-args 'org-cycle-hook 'subtree))))
  5997. (t (org-show-set-visibility 'lineage))))
  5998. ;;; Indirect buffer display of subtrees
  5999. (defvar org-indirect-dedicated-frame nil
  6000. "This is the frame being used for indirect tree display.")
  6001. (defvar org-last-indirect-buffer nil)
  6002. (defun org-tree-to-indirect-buffer (&optional arg)
  6003. "Create indirect buffer and narrow it to current subtree.
  6004. With a numerical prefix ARG, go up to this level and then take that tree.
  6005. If ARG is negative, go up that many levels.
  6006. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6007. indirect buffer previously made with this command, to avoid proliferation of
  6008. indirect buffers. However, when you call the command with a \
  6009. `\\[universal-argument]' prefix, or
  6010. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6011. so that you can work with several indirect buffers at the same time. If
  6012. `org-indirect-buffer-display' is `dedicated-frame', the \
  6013. `\\[universal-argument]' prefix also
  6014. requests that a new frame be made for the new buffer, so that the dedicated
  6015. frame is not changed."
  6016. (interactive "P")
  6017. (let ((cbuf (current-buffer))
  6018. (cwin (selected-window))
  6019. (pos (point))
  6020. beg end level heading ibuf)
  6021. (save-excursion
  6022. (org-back-to-heading t)
  6023. (when (numberp arg)
  6024. (setq level (org-outline-level))
  6025. (when (< arg 0) (setq arg (+ level arg)))
  6026. (while (> (setq level (org-outline-level)) arg)
  6027. (org-up-heading-safe)))
  6028. (setq beg (point)
  6029. heading (org-get-heading 'no-tags))
  6030. (org-end-of-subtree t t)
  6031. (when (org-at-heading-p) (backward-char 1))
  6032. (setq end (point)))
  6033. (when (and (buffer-live-p org-last-indirect-buffer)
  6034. (not (eq org-indirect-buffer-display 'new-frame))
  6035. (not arg))
  6036. (kill-buffer org-last-indirect-buffer))
  6037. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6038. org-last-indirect-buffer ibuf)
  6039. (cond
  6040. ((or (eq org-indirect-buffer-display 'new-frame)
  6041. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6042. (select-frame (make-frame))
  6043. (delete-other-windows)
  6044. (pop-to-buffer-same-window ibuf)
  6045. (org-set-frame-title heading))
  6046. ((eq org-indirect-buffer-display 'dedicated-frame)
  6047. (raise-frame
  6048. (select-frame (or (and org-indirect-dedicated-frame
  6049. (frame-live-p org-indirect-dedicated-frame)
  6050. org-indirect-dedicated-frame)
  6051. (setq org-indirect-dedicated-frame (make-frame)))))
  6052. (delete-other-windows)
  6053. (pop-to-buffer-same-window ibuf)
  6054. (org-set-frame-title (concat "Indirect: " heading)))
  6055. ((eq org-indirect-buffer-display 'current-window)
  6056. (pop-to-buffer-same-window ibuf))
  6057. ((eq org-indirect-buffer-display 'other-window)
  6058. (pop-to-buffer ibuf))
  6059. (t (error "Invalid value")))
  6060. (narrow-to-region beg end)
  6061. (org-show-all '(headings blocks))
  6062. (goto-char pos)
  6063. (run-hook-with-args 'org-cycle-hook 'all)
  6064. (and (window-live-p cwin) (select-window cwin))))
  6065. (defun org-get-indirect-buffer (&optional buffer heading)
  6066. (setq buffer (or buffer (current-buffer)))
  6067. (let ((n 1) (base (buffer-name buffer)) bname)
  6068. (while (buffer-live-p
  6069. (get-buffer
  6070. (setq bname
  6071. (concat base "-"
  6072. (if heading (concat heading "-" (number-to-string n))
  6073. (number-to-string n))))))
  6074. (setq n (1+ n)))
  6075. (condition-case nil
  6076. (make-indirect-buffer buffer bname 'clone)
  6077. (error (make-indirect-buffer buffer bname)))))
  6078. (defun org-set-frame-title (title)
  6079. "Set the title of the current frame to the string TITLE."
  6080. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6081. ;;;; Structure editing
  6082. ;;; Inserting headlines
  6083. (defun org--line-empty-p (n)
  6084. "Is the Nth next line empty?
  6085. Counts the current line as N = 1 and the previous line as N = 0;
  6086. see `beginning-of-line'."
  6087. (save-excursion
  6088. (and (not (bobp))
  6089. (or (beginning-of-line n) t)
  6090. (save-match-data
  6091. (looking-at "[ \t]*$")))))
  6092. (defun org-previous-line-empty-p ()
  6093. "Is the previous line a blank line?
  6094. When NEXT is non-nil, check the next line instead."
  6095. (org--line-empty-p 0))
  6096. (defun org-next-line-empty-p ()
  6097. "Is the previous line a blank line?
  6098. When NEXT is non-nil, check the next line instead."
  6099. (org--line-empty-p 2))
  6100. (defun org--blank-before-heading-p (&optional parent)
  6101. "Non-nil when an empty line should precede a new heading here.
  6102. When optional argument PARENT is non-nil, consider parent
  6103. headline instead of current one."
  6104. (pcase (assq 'heading org-blank-before-new-entry)
  6105. (`(heading . auto)
  6106. (save-excursion
  6107. (org-with-limited-levels
  6108. (unless (and (org-before-first-heading-p)
  6109. (not (outline-next-heading)))
  6110. (org-back-to-heading t)
  6111. (when parent (org-up-heading-safe))
  6112. (cond ((not (bobp))
  6113. (org-previous-line-empty-p))
  6114. ((outline-next-heading)
  6115. (org-previous-line-empty-p))
  6116. ;; Ignore trailing spaces on last buffer line.
  6117. ((progn (skip-chars-backward " \t") (bolp))
  6118. (org-previous-line-empty-p))
  6119. (t nil))))))
  6120. (`(heading . ,value) value)
  6121. (_ nil)))
  6122. (defun org-insert-heading (&optional arg invisible-ok top)
  6123. "Insert a new heading or an item with the same depth at point.
  6124. If point is at the beginning of a heading, insert a new heading
  6125. or a new headline above the current one. When at the beginning
  6126. of a regular line of text, turn it into a heading.
  6127. If point is in the middle of a line, split it and create a new
  6128. headline with the text in the current line after point (see
  6129. `org-M-RET-may-split-line' on how to modify this behavior). As
  6130. a special case, on a headline, splitting can only happen on the
  6131. title itself. E.g., this excludes breaking stars or tags.
  6132. With a `\\[universal-argument]' prefix, set \
  6133. `org-insert-heading-respect-content' to
  6134. a non-nil value for the duration of the command. This forces the
  6135. insertion of a heading after the current subtree, independently
  6136. on the location of point.
  6137. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6138. insert the heading at the end of the tree
  6139. above the current heading. For example, if point is within a
  6140. 2nd-level heading, then it will insert a 2nd-level heading at
  6141. the end of the 1st-level parent subtree.
  6142. When INVISIBLE-OK is set, stop at invisible headlines when going
  6143. back. This is important for non-interactive uses of the
  6144. command.
  6145. When optional argument TOP is non-nil, insert a level 1 heading,
  6146. unconditionally."
  6147. (interactive "P")
  6148. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6149. (level (org-current-level))
  6150. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6151. (cond
  6152. ((or org-insert-heading-respect-content
  6153. (member arg '((4) (16)))
  6154. (and (not invisible-ok)
  6155. (invisible-p (max (1- (point)) (point-min)))))
  6156. ;; Position point at the location of insertion. Make sure we
  6157. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6158. (org-with-limited-levels
  6159. (if (not level) (outline-next-heading) ;before first headline
  6160. (org-back-to-heading invisible-ok)
  6161. (when (equal arg '(16)) (org-up-heading-safe))
  6162. (org-end-of-subtree)))
  6163. (unless (bolp) (insert "\n"))
  6164. (unless (and blank? (org-previous-line-empty-p))
  6165. (org-N-empty-lines-before-current (if blank? 1 0)))
  6166. (insert stars " ")
  6167. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6168. ;; is visible.
  6169. (unless invisible-ok
  6170. (pcase (get-char-property-and-overlay (point) 'invisible)
  6171. (`(outline . ,o)
  6172. (move-overlay o (overlay-start o) (line-end-position 0)))
  6173. (_ nil))))
  6174. ;; At a headline...
  6175. ((org-at-heading-p)
  6176. (cond ((bolp)
  6177. (when blank? (save-excursion (insert "\n")))
  6178. (save-excursion (insert stars " \n"))
  6179. (unless (and blank? (org-previous-line-empty-p))
  6180. (org-N-empty-lines-before-current (if blank? 1 0)))
  6181. (end-of-line))
  6182. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6183. (org-match-line org-complex-heading-regexp)
  6184. (org-pos-in-match-range (point) 4))
  6185. ;; Grab the text that should moved to the new headline.
  6186. ;; Preserve tags.
  6187. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6188. (if (looking-at "[ \t]*$") (replace-match "")
  6189. (org-align-tags))
  6190. (end-of-line)
  6191. (when blank? (insert "\n"))
  6192. (insert "\n" stars " ")
  6193. (when (org-string-nw-p split) (insert split))))
  6194. (t
  6195. (end-of-line)
  6196. (when blank? (insert "\n"))
  6197. (insert "\n" stars " "))))
  6198. ;; On regular text, turn line into a headline or split, if
  6199. ;; appropriate.
  6200. ((bolp)
  6201. (insert stars " ")
  6202. (unless (and blank? (org-previous-line-empty-p))
  6203. (org-N-empty-lines-before-current (if blank? 1 0))))
  6204. (t
  6205. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6206. (end-of-line))
  6207. (insert "\n" stars " ")
  6208. (unless (and blank? (org-previous-line-empty-p))
  6209. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6210. (run-hooks 'org-insert-heading-hook))
  6211. (defun org-N-empty-lines-before-current (n)
  6212. "Make the number of empty lines before current exactly N.
  6213. So this will delete or add empty lines."
  6214. (let ((column (current-column)))
  6215. (beginning-of-line)
  6216. (unless (bobp)
  6217. (let ((start (save-excursion
  6218. (skip-chars-backward " \r\t\n")
  6219. (line-end-position))))
  6220. (delete-region start (line-end-position 0))))
  6221. (insert (make-string n ?\n))
  6222. (move-to-column column)))
  6223. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6224. "Return the heading of the current entry, without the stars.
  6225. When NO-TAGS is non-nil, don't include tags.
  6226. When NO-TODO is non-nil, don't include TODO keywords.
  6227. When NO-PRIORITY is non-nil, don't include priority cookie.
  6228. When NO-COMMENT is non-nil, don't include COMMENT string.
  6229. Return nil before first heading."
  6230. (unless (org-before-first-heading-p)
  6231. (save-excursion
  6232. (org-back-to-heading t)
  6233. (let ((case-fold-search nil))
  6234. (looking-at org-complex-heading-regexp)
  6235. (let ((todo (and (not no-todo) (match-string 2)))
  6236. (priority (and (not no-priority) (match-string 3)))
  6237. (headline (pcase (match-string 4)
  6238. (`nil "")
  6239. ((and (guard no-comment) h)
  6240. (replace-regexp-in-string
  6241. (eval-when-compile
  6242. (format "\\`%s[ \t]+" org-comment-string))
  6243. "" h))
  6244. (h h)))
  6245. (tags (and (not no-tags) (match-string 5))))
  6246. (mapconcat #'identity
  6247. (delq nil (list todo priority headline tags))
  6248. " "))))))
  6249. (defun org-heading-components ()
  6250. "Return the components of the current heading.
  6251. This is a list with the following elements:
  6252. - the level as an integer
  6253. - the reduced level, different if `org-odd-levels-only' is set.
  6254. - the TODO keyword, or nil
  6255. - the priority character, like ?A, or nil if no priority is given
  6256. - the headline text itself, or the tags string if no headline text
  6257. - the tags string, or nil."
  6258. (save-excursion
  6259. (org-back-to-heading t)
  6260. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6261. (list (length (match-string 1))
  6262. (org-reduced-level (length (match-string 1)))
  6263. (match-string-no-properties 2)
  6264. (and (match-end 3) (aref (match-string 3) 2))
  6265. (match-string-no-properties 4)
  6266. (match-string-no-properties 5)))))
  6267. (defun org-get-entry ()
  6268. "Get the entry text, after heading, entire subtree."
  6269. (save-excursion
  6270. (org-back-to-heading t)
  6271. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6272. (defun org-edit-headline (&optional heading)
  6273. "Edit the current headline.
  6274. Set it to HEADING when provided."
  6275. (interactive)
  6276. (org-with-wide-buffer
  6277. (org-back-to-heading t)
  6278. (let ((case-fold-search nil))
  6279. (when (looking-at org-complex-heading-regexp)
  6280. (let* ((old (match-string-no-properties 4))
  6281. (new (save-match-data
  6282. (org-trim (or heading (read-string "Edit: " old))))))
  6283. (unless (equal old new)
  6284. (if old (replace-match new t t nil 4)
  6285. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6286. (insert " " new))
  6287. (org-align-tags)
  6288. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6289. (defun org-insert-heading-after-current ()
  6290. "Insert a new heading with same level as current, after current subtree."
  6291. (interactive)
  6292. (org-back-to-heading)
  6293. (org-insert-heading)
  6294. (org-move-subtree-down)
  6295. (end-of-line 1))
  6296. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6297. "Insert heading with `org-insert-heading-respect-content' set to t."
  6298. (interactive)
  6299. (org-insert-heading '(4) invisible-ok))
  6300. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6301. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6302. (interactive)
  6303. (org-insert-todo-heading force-state '(4)))
  6304. (defun org-insert-todo-heading (arg &optional force-heading)
  6305. "Insert a new heading with the same level and TODO state as current heading.
  6306. If the heading has no TODO state, or if the state is DONE, use
  6307. the first state (TODO by default). Also with one prefix arg,
  6308. force first state. With two prefix args, force inserting at the
  6309. end of the parent subtree.
  6310. When called at a plain list item, insert a new item with an
  6311. unchecked check box."
  6312. (interactive "P")
  6313. (when (or force-heading (not (org-insert-item 'checkbox)))
  6314. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6315. force-heading))
  6316. (save-excursion
  6317. (org-forward-heading-same-level -1)
  6318. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6319. (let* ((new-mark-x
  6320. (if (or (equal arg '(4))
  6321. (not (match-beginning 2))
  6322. (member (match-string 2) org-done-keywords))
  6323. (car org-todo-keywords-1)
  6324. (match-string 2)))
  6325. (new-mark
  6326. (or
  6327. (run-hook-with-args-until-success
  6328. 'org-todo-get-default-hook new-mark-x nil)
  6329. new-mark-x)))
  6330. (beginning-of-line 1)
  6331. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6332. (if org-treat-insert-todo-heading-as-state-change
  6333. (org-todo new-mark)
  6334. (insert new-mark " "))))
  6335. (when org-provide-todo-statistics
  6336. (org-update-parent-todo-statistics))))
  6337. (defun org-insert-subheading (arg)
  6338. "Insert a new subheading and demote it.
  6339. Works for outline headings and for plain lists alike."
  6340. (interactive "P")
  6341. (org-insert-heading arg)
  6342. (cond
  6343. ((org-at-heading-p) (org-do-demote))
  6344. ((org-at-item-p) (org-indent-item))))
  6345. (defun org-insert-todo-subheading (arg)
  6346. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6347. Works for outline headings and for plain lists alike."
  6348. (interactive "P")
  6349. (org-insert-todo-heading arg)
  6350. (cond
  6351. ((org-at-heading-p) (org-do-demote))
  6352. ((org-at-item-p) (org-indent-item))))
  6353. ;;; Promotion and Demotion
  6354. (defvar org-after-demote-entry-hook nil
  6355. "Hook run after an entry has been demoted.
  6356. The cursor will be at the beginning of the entry.
  6357. When a subtree is being demoted, the hook will be called for each node.")
  6358. (defvar org-after-promote-entry-hook nil
  6359. "Hook run after an entry has been promoted.
  6360. The cursor will be at the beginning of the entry.
  6361. When a subtree is being promoted, the hook will be called for each node.")
  6362. (defun org-promote-subtree ()
  6363. "Promote the entire subtree.
  6364. See also `org-promote'."
  6365. (interactive)
  6366. (save-excursion
  6367. (org-with-limited-levels (org-map-tree 'org-promote)))
  6368. (org-fix-position-after-promote))
  6369. (defun org-demote-subtree ()
  6370. "Demote the entire subtree.
  6371. See `org-demote' and `org-promote'."
  6372. (interactive)
  6373. (save-excursion
  6374. (org-with-limited-levels (org-map-tree 'org-demote)))
  6375. (org-fix-position-after-promote))
  6376. (defun org-do-promote ()
  6377. "Promote the current heading higher up the tree.
  6378. If the region is active in `transient-mark-mode', promote all
  6379. headings in the region."
  6380. (interactive)
  6381. (save-excursion
  6382. (if (org-region-active-p)
  6383. (org-map-region 'org-promote (region-beginning) (region-end))
  6384. (org-promote)))
  6385. (org-fix-position-after-promote))
  6386. (defun org-do-demote ()
  6387. "Demote the current heading lower down the tree.
  6388. If the region is active in `transient-mark-mode', demote all
  6389. headings in the region."
  6390. (interactive)
  6391. (save-excursion
  6392. (if (org-region-active-p)
  6393. (org-map-region 'org-demote (region-beginning) (region-end))
  6394. (org-demote)))
  6395. (org-fix-position-after-promote))
  6396. (defun org-fix-position-after-promote ()
  6397. "Fix cursor position and indentation after demoting/promoting."
  6398. (let ((pos (point)))
  6399. (when (save-excursion
  6400. (beginning-of-line)
  6401. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6402. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6403. (cond ((eobp) (insert " "))
  6404. ((eolp) (insert " "))
  6405. ((equal (char-after) ?\s) (forward-char 1))))))
  6406. (defun org-current-level ()
  6407. "Return the level of the current entry, or nil if before the first headline.
  6408. The level is the number of stars at the beginning of the
  6409. headline. Use `org-reduced-level' to remove the effect of
  6410. `org-odd-levels'. Unlike to `org-outline-level', this function
  6411. ignores inlinetasks."
  6412. (let ((level (org-with-limited-levels (org-outline-level))))
  6413. (and (> level 0) level)))
  6414. (defun org-get-previous-line-level ()
  6415. "Return the outline depth of the last headline before the current line.
  6416. Returns 0 for the first headline in the buffer, and nil if before the
  6417. first headline."
  6418. (and (org-current-level)
  6419. (or (and (/= (line-beginning-position) (point-min))
  6420. (save-excursion (beginning-of-line 0) (org-current-level)))
  6421. 0)))
  6422. (defun org-reduced-level (l)
  6423. "Compute the effective level of a heading.
  6424. This takes into account the setting of `org-odd-levels-only'."
  6425. (cond
  6426. ((zerop l) 0)
  6427. (org-odd-levels-only (1+ (floor (/ l 2))))
  6428. (t l)))
  6429. (defun org-level-increment ()
  6430. "Return the number of stars that will be added or removed at a
  6431. time to headlines when structure editing, based on the value of
  6432. `org-odd-levels-only'."
  6433. (if org-odd-levels-only 2 1))
  6434. (defun org-get-valid-level (level &optional change)
  6435. "Rectify a level change under the influence of `org-odd-levels-only'.
  6436. LEVEL is a current level, CHANGE is by how much the level should
  6437. be modified. Even if CHANGE is nil, LEVEL may be returned
  6438. modified because even level numbers will become the next higher
  6439. odd number. Returns values greater than 0."
  6440. (if org-odd-levels-only
  6441. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6442. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6443. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6444. (max 1 (+ level (or change 0)))))
  6445. (defun org-promote ()
  6446. "Promote the current heading higher up the tree."
  6447. (org-with-wide-buffer
  6448. (org-back-to-heading t)
  6449. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6450. after-change-functions))
  6451. (level (save-match-data (funcall outline-level)))
  6452. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6453. (diff (abs (- level (length up-head) -1))))
  6454. (cond
  6455. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6456. (replace-match "# " nil t))
  6457. ((= level 1)
  6458. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6459. (t (replace-match up-head nil t)))
  6460. (unless (= level 1)
  6461. (when org-auto-align-tags (org-align-tags))
  6462. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6463. (run-hooks 'org-after-promote-entry-hook))))
  6464. (defun org-demote ()
  6465. "Demote the current heading lower down the tree."
  6466. (org-with-wide-buffer
  6467. (org-back-to-heading t)
  6468. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6469. after-change-functions))
  6470. (level (save-match-data (funcall outline-level)))
  6471. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6472. (diff (abs (- level (length down-head) -1))))
  6473. (replace-match down-head nil t)
  6474. (when org-auto-align-tags (org-align-tags))
  6475. (when org-adapt-indentation (org-fixup-indentation diff))
  6476. (run-hooks 'org-after-demote-entry-hook))))
  6477. (defun org-cycle-level ()
  6478. "Cycle the level of an empty headline through possible states.
  6479. This goes first to child, then to parent, level, then up the hierarchy.
  6480. After top level, it switches back to sibling level."
  6481. (interactive)
  6482. (let ((org-adapt-indentation nil))
  6483. (when (org-point-at-end-of-empty-headline)
  6484. (setq this-command 'org-cycle-level) ; Only needed for caching
  6485. (let ((cur-level (org-current-level))
  6486. (prev-level (org-get-previous-line-level)))
  6487. (cond
  6488. ;; If first headline in file, promote to top-level.
  6489. ((= prev-level 0)
  6490. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6491. do (org-do-promote)))
  6492. ;; If same level as prev, demote one.
  6493. ((= prev-level cur-level)
  6494. (org-do-demote))
  6495. ;; If parent is top-level, promote to top level if not already.
  6496. ((= prev-level 1)
  6497. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6498. do (org-do-promote)))
  6499. ;; If top-level, return to prev-level.
  6500. ((= cur-level 1)
  6501. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6502. do (org-do-demote)))
  6503. ;; If less than prev-level, promote one.
  6504. ((< cur-level prev-level)
  6505. (org-do-promote))
  6506. ;; If deeper than prev-level, promote until higher than
  6507. ;; prev-level.
  6508. ((> cur-level prev-level)
  6509. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6510. do (org-do-promote))))
  6511. t))))
  6512. (defun org-map-tree (fun)
  6513. "Call FUN for every heading underneath the current one."
  6514. (org-back-to-heading t)
  6515. (let ((level (funcall outline-level)))
  6516. (save-excursion
  6517. (funcall fun)
  6518. (while (and (progn
  6519. (outline-next-heading)
  6520. (> (funcall outline-level) level))
  6521. (not (eobp)))
  6522. (funcall fun)))))
  6523. (defun org-map-region (fun beg end)
  6524. "Call FUN for every heading between BEG and END."
  6525. (let ((org-ignore-region t))
  6526. (save-excursion
  6527. (setq end (copy-marker end))
  6528. (goto-char beg)
  6529. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6530. (< (point) end))
  6531. (funcall fun))
  6532. (while (and (progn
  6533. (outline-next-heading)
  6534. (< (point) end))
  6535. (not (eobp)))
  6536. (funcall fun)))))
  6537. (defun org-fixup-indentation (diff)
  6538. "Change the indentation in the current entry by DIFF.
  6539. DIFF is an integer. Indentation is done according to the
  6540. following rules:
  6541. - Planning information and property drawers are always indented
  6542. according to the new level of the headline;
  6543. - Footnote definitions and their contents are ignored;
  6544. - Inlinetasks' boundaries are not shifted;
  6545. - Empty lines are ignored;
  6546. - Other lines' indentation are shifted by DIFF columns, unless
  6547. it would introduce a structural change in the document, in
  6548. which case no shifting is done at all.
  6549. Assume point is at a heading or an inlinetask beginning."
  6550. (org-with-wide-buffer
  6551. (narrow-to-region (line-beginning-position)
  6552. (save-excursion
  6553. (if (org-with-limited-levels (org-at-heading-p))
  6554. (org-with-limited-levels (outline-next-heading))
  6555. (org-inlinetask-goto-end))
  6556. (point)))
  6557. (forward-line)
  6558. ;; Indent properly planning info and property drawer.
  6559. (when (looking-at-p org-planning-line-re)
  6560. (org-indent-line)
  6561. (forward-line))
  6562. (when (looking-at org-property-drawer-re)
  6563. (goto-char (match-end 0))
  6564. (forward-line)
  6565. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  6566. (catch 'no-shift
  6567. (when (zerop diff) (throw 'no-shift nil))
  6568. ;; If DIFF is negative, first check if a shift is possible at all
  6569. ;; (e.g., it doesn't break structure). This can only happen if
  6570. ;; some contents are not properly indented.
  6571. (let ((case-fold-search t))
  6572. (when (< diff 0)
  6573. (let ((diff (- diff))
  6574. (forbidden-re (concat org-outline-regexp
  6575. "\\|"
  6576. (substring org-footnote-definition-re 1))))
  6577. (save-excursion
  6578. (while (not (eobp))
  6579. (cond
  6580. ((looking-at-p "[ \t]*$") (forward-line))
  6581. ((and (looking-at-p org-footnote-definition-re)
  6582. (let ((e (org-element-at-point)))
  6583. (and (eq (org-element-type e) 'footnote-definition)
  6584. (goto-char (org-element-property :end e))))))
  6585. ((looking-at-p org-outline-regexp) (forward-line))
  6586. ;; Give up if shifting would move before column 0 or
  6587. ;; if it would introduce a headline or a footnote
  6588. ;; definition.
  6589. (t
  6590. (skip-chars-forward " \t")
  6591. (let ((ind (current-column)))
  6592. (when (or (< ind diff)
  6593. (and (= ind diff) (looking-at-p forbidden-re)))
  6594. (throw 'no-shift nil)))
  6595. ;; Ignore contents of example blocks and source
  6596. ;; blocks if their indentation is meant to be
  6597. ;; preserved. Jump to block's closing line.
  6598. (beginning-of-line)
  6599. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6600. (let ((e (org-element-at-point)))
  6601. (and (memq (org-element-type e)
  6602. '(example-block src-block))
  6603. (or org-src-preserve-indentation
  6604. (org-element-property :preserve-indent e))
  6605. (goto-char (org-element-property :end e))
  6606. (progn (skip-chars-backward " \r\t\n")
  6607. (beginning-of-line)
  6608. t))))
  6609. (forward-line))))))))
  6610. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6611. ;; by DIFF. Also skip contents of source or example blocks
  6612. ;; when indentation is meant to be preserved.
  6613. (while (not (eobp))
  6614. (cond
  6615. ((and (looking-at-p org-footnote-definition-re)
  6616. (let ((e (org-element-at-point)))
  6617. (and (eq (org-element-type e) 'footnote-definition)
  6618. (goto-char (org-element-property :end e))))))
  6619. ((looking-at-p org-outline-regexp) (forward-line))
  6620. ((looking-at-p "[ \t]*$") (forward-line))
  6621. (t
  6622. (indent-line-to (+ (current-indentation) diff))
  6623. (beginning-of-line)
  6624. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6625. (let ((e (org-element-at-point)))
  6626. (and (memq (org-element-type e)
  6627. '(example-block src-block))
  6628. (or org-src-preserve-indentation
  6629. (org-element-property :preserve-indent e))
  6630. (goto-char (org-element-property :end e))
  6631. (progn (skip-chars-backward " \r\t\n")
  6632. (beginning-of-line)
  6633. t))))
  6634. (forward-line)))))))))
  6635. (defun org-convert-to-odd-levels ()
  6636. "Convert an Org file with all levels allowed to one with odd levels.
  6637. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6638. level 5 etc."
  6639. (interactive)
  6640. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6641. (let ((outline-level 'org-outline-level)
  6642. (org-odd-levels-only nil) n)
  6643. (save-excursion
  6644. (goto-char (point-min))
  6645. (while (re-search-forward "^\\*\\*+ " nil t)
  6646. (setq n (- (length (match-string 0)) 2))
  6647. (while (>= (setq n (1- n)) 0)
  6648. (org-demote))
  6649. (end-of-line 1))))))
  6650. (defun org-convert-to-oddeven-levels ()
  6651. "Convert an Org file with only odd levels to one with odd/even levels.
  6652. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6653. file contains a section with an even level, conversion would
  6654. destroy the structure of the file. An error is signaled in this
  6655. case."
  6656. (interactive)
  6657. (goto-char (point-min))
  6658. ;; First check if there are no even levels
  6659. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6660. (org-show-set-visibility 'canonical)
  6661. (error "Not all levels are odd in this file. Conversion not possible"))
  6662. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6663. (let ((outline-regexp org-outline-regexp)
  6664. (outline-level 'org-outline-level)
  6665. (org-odd-levels-only nil) n)
  6666. (save-excursion
  6667. (goto-char (point-min))
  6668. (while (re-search-forward "^\\*\\*+ " nil t)
  6669. (setq n (/ (1- (length (match-string 0))) 2))
  6670. (while (>= (setq n (1- n)) 0)
  6671. (org-promote))
  6672. (end-of-line 1))))))
  6673. (defun org-tr-level (n)
  6674. "Make N odd if required."
  6675. (if org-odd-levels-only (1+ (/ n 2)) n))
  6676. ;;; Vertical tree motion, cutting and pasting of subtrees
  6677. (defun org-move-subtree-up (&optional arg)
  6678. "Move the current subtree up past ARG headlines of the same level."
  6679. (interactive "p")
  6680. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6681. (defun org-move-subtree-down (&optional arg)
  6682. "Move the current subtree down past ARG headlines of the same level."
  6683. (interactive "p")
  6684. (setq arg (prefix-numeric-value arg))
  6685. (org-preserve-local-variables
  6686. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6687. 'org-get-last-sibling))
  6688. (ins-point (make-marker))
  6689. (cnt (abs arg))
  6690. (col (current-column))
  6691. beg end txt folded)
  6692. ;; Select the tree
  6693. (org-back-to-heading)
  6694. (setq beg (point))
  6695. (save-match-data
  6696. (save-excursion (outline-end-of-heading)
  6697. (setq folded (org-invisible-p)))
  6698. (progn (org-end-of-subtree nil t)
  6699. (unless (eobp) (backward-char))))
  6700. (outline-next-heading)
  6701. (setq end (point))
  6702. (goto-char beg)
  6703. ;; Find insertion point, with error handling
  6704. (while (> cnt 0)
  6705. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6706. (goto-char beg)
  6707. (user-error "Cannot move past superior level or buffer limit"))
  6708. (setq cnt (1- cnt)))
  6709. (when (> arg 0)
  6710. ;; Moving forward - still need to move over subtree
  6711. (org-end-of-subtree t t)
  6712. (save-excursion
  6713. (org-back-over-empty-lines)
  6714. (or (bolp) (newline))))
  6715. (move-marker ins-point (point))
  6716. (setq txt (buffer-substring beg end))
  6717. (org-save-markers-in-region beg end)
  6718. (delete-region beg end)
  6719. (org-remove-empty-overlays-at beg)
  6720. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6721. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6722. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6723. (let ((bbb (point)))
  6724. (insert-before-markers txt)
  6725. (org-reinstall-markers-in-region bbb)
  6726. (move-marker ins-point bbb))
  6727. (or (bolp) (insert "\n"))
  6728. (goto-char ins-point)
  6729. (org-skip-whitespace)
  6730. (move-marker ins-point nil)
  6731. (if folded
  6732. (org-flag-subtree t)
  6733. (org-show-entry)
  6734. (org-show-children))
  6735. (org-clean-visibility-after-subtree-move)
  6736. ;; move back to the initial column we were at
  6737. (move-to-column col))))
  6738. (defvar org-subtree-clip ""
  6739. "Clipboard for cut and paste of subtrees.
  6740. This is actually only a copy of the kill, because we use the normal kill
  6741. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6742. (defvar org-subtree-clip-folded nil
  6743. "Was the last copied subtree folded?
  6744. This is used to fold the tree back after pasting.")
  6745. (defun org-cut-subtree (&optional n)
  6746. "Cut the current subtree into the clipboard.
  6747. With prefix arg N, cut this many sequential subtrees.
  6748. This is a short-hand for marking the subtree and then cutting it."
  6749. (interactive "p")
  6750. (org-copy-subtree n 'cut))
  6751. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6752. "Copy the current subtree into the clipboard.
  6753. With prefix arg N, copy this many sequential subtrees.
  6754. This is a short-hand for marking the subtree and then copying it.
  6755. If CUT is non-nil, actually cut the subtree.
  6756. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6757. of some markers in the region, even if CUT is non-nil. This is
  6758. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6759. (interactive "p")
  6760. (org-preserve-local-variables
  6761. (let (beg end folded (beg0 (point)))
  6762. (if (called-interactively-p 'any)
  6763. (org-back-to-heading nil) ; take what looks like a subtree
  6764. (org-back-to-heading t)) ; take what is really there
  6765. (setq beg (point))
  6766. (skip-chars-forward " \t\r\n")
  6767. (save-match-data
  6768. (if nosubtrees
  6769. (outline-next-heading)
  6770. (save-excursion (outline-end-of-heading)
  6771. (setq folded (org-invisible-p)))
  6772. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6773. (org-end-of-subtree t t)))
  6774. ;; Include the end of an inlinetask
  6775. (when (and (featurep 'org-inlinetask)
  6776. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6777. "END[ \t]*$")))
  6778. (end-of-line))
  6779. (setq end (point))
  6780. (goto-char beg0)
  6781. (when (> end beg)
  6782. (setq org-subtree-clip-folded folded)
  6783. (when (or cut force-store-markers)
  6784. (org-save-markers-in-region beg end))
  6785. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6786. (setq org-subtree-clip (current-kill 0))
  6787. (message "%s: Subtree(s) with %d characters"
  6788. (if cut "Cut" "Copied")
  6789. (length org-subtree-clip))))))
  6790. (defun org-paste-subtree (&optional level tree for-yank remove)
  6791. "Paste the clipboard as a subtree, with modification of headline level.
  6792. The entire subtree is promoted or demoted in order to match a new headline
  6793. level.
  6794. If the cursor is at the beginning of a headline, the same level as
  6795. that headline is used to paste the tree.
  6796. If not, the new level is derived from the *visible* headings
  6797. before and after the insertion point, and taken to be the inferior headline
  6798. level of the two. So if the previous visible heading is level 3 and the
  6799. next is level 4 (or vice versa), level 4 will be used for insertion.
  6800. This makes sure that the subtree remains an independent subtree and does
  6801. not swallow low level entries.
  6802. You can also force a different level, either by using a numeric prefix
  6803. argument, or by inserting the heading marker by hand. For example, if the
  6804. cursor is after \"*****\", then the tree will be shifted to level 5.
  6805. If optional TREE is given, use this text instead of the kill ring.
  6806. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6807. move back over whitespace before inserting, and move point to the end of
  6808. the inserted text when done.
  6809. When REMOVE is non-nil, remove the subtree from the clipboard."
  6810. (interactive "P")
  6811. (setq tree (or tree (and kill-ring (current-kill 0))))
  6812. (unless (org-kill-is-subtree-p tree)
  6813. (user-error
  6814. (substitute-command-keys
  6815. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6816. (org-with-limited-levels
  6817. (let* ((visp (not (org-invisible-p)))
  6818. (txt tree)
  6819. (old-level (if (string-match org-outline-regexp-bol txt)
  6820. (- (match-end 0) (match-beginning 0) 1)
  6821. -1))
  6822. (force-level
  6823. (cond
  6824. (level (prefix-numeric-value level))
  6825. ;; When point is after the stars in an otherwise empty
  6826. ;; headline, use the number of stars as the forced level.
  6827. ((and (org-match-line "^\\*+[ \t]*$")
  6828. (not (eq ?* (char-after))))
  6829. (org-outline-level))
  6830. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6831. (previous-level
  6832. (save-excursion
  6833. (org-previous-visible-heading 1)
  6834. (if (org-at-heading-p) (org-outline-level) 1)))
  6835. (next-level
  6836. (save-excursion
  6837. (if (org-at-heading-p) (org-outline-level)
  6838. (org-next-visible-heading 1)
  6839. (if (org-at-heading-p) (org-outline-level) 1))))
  6840. (new-level (or force-level (max previous-level next-level)))
  6841. (shift (if (or (= old-level -1)
  6842. (= new-level -1)
  6843. (= old-level new-level))
  6844. 0
  6845. (- new-level old-level)))
  6846. (delta (if (> shift 0) -1 1))
  6847. (func (if (> shift 0) #'org-demote #'org-promote))
  6848. (org-odd-levels-only nil)
  6849. beg end newend)
  6850. ;; Remove the forced level indicator.
  6851. (when (and force-level (not level))
  6852. (delete-region (line-beginning-position) (point)))
  6853. ;; Paste before the next visible heading or at end of buffer,
  6854. ;; unless point is at the beginning of a headline.
  6855. (unless (and (bolp) (org-at-heading-p))
  6856. (org-next-visible-heading 1)
  6857. (unless (bolp) (insert "\n")))
  6858. (setq beg (point))
  6859. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6860. (insert-before-markers txt)
  6861. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6862. (setq newend (point))
  6863. (org-reinstall-markers-in-region beg)
  6864. (setq end (point))
  6865. (goto-char beg)
  6866. (skip-chars-forward " \t\n\r")
  6867. (setq beg (point))
  6868. (when (and (org-invisible-p) visp)
  6869. (save-excursion (outline-show-heading)))
  6870. ;; Shift if necessary.
  6871. (unless (= shift 0)
  6872. (save-restriction
  6873. (narrow-to-region beg end)
  6874. (while (not (= shift 0))
  6875. (org-map-region func (point-min) (point-max))
  6876. (setq shift (+ delta shift)))
  6877. (goto-char (point-min))
  6878. (setq newend (point-max))))
  6879. (when (or for-yank (called-interactively-p 'interactive))
  6880. (message "Clipboard pasted as level %d subtree" new-level))
  6881. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6882. kill-ring
  6883. (equal org-subtree-clip (current-kill 0))
  6884. org-subtree-clip-folded)
  6885. ;; The tree was folded before it was killed/copied
  6886. (org-flag-subtree t))
  6887. (when for-yank (goto-char newend))
  6888. (when remove (pop kill-ring)))))
  6889. (defun org-kill-is-subtree-p (&optional txt)
  6890. "Check if the current kill is an outline subtree, or a set of trees.
  6891. Returns nil if kill does not start with a headline, or if the first
  6892. headline level is not the largest headline level in the tree.
  6893. So this will actually accept several entries of equal levels as well,
  6894. which is OK for `org-paste-subtree'.
  6895. If optional TXT is given, check this string instead of the current kill."
  6896. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6897. (re (org-get-limited-outline-regexp))
  6898. (^re (concat "^" re))
  6899. (start-level (and kill
  6900. (string-match
  6901. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6902. kill)
  6903. (- (match-end 2) (match-beginning 2) 1)))
  6904. (start (1+ (or (match-beginning 2) -1))))
  6905. (if (not start-level)
  6906. (progn
  6907. nil) ;; does not even start with a heading
  6908. (catch 'exit
  6909. (while (setq start (string-match ^re kill (1+ start)))
  6910. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6911. (throw 'exit nil)))
  6912. t))))
  6913. (defvar org-markers-to-move nil
  6914. "Markers that should be moved with a cut-and-paste operation.
  6915. Those markers are stored together with their positions relative to
  6916. the start of the region.")
  6917. (defun org-save-markers-in-region (beg end)
  6918. "Check markers in region.
  6919. If these markers are between BEG and END, record their position relative
  6920. to BEG, so that after moving the block of text, we can put the markers back
  6921. into place.
  6922. This function gets called just before an entry or tree gets cut from the
  6923. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6924. called immediately, to move the markers with the entries."
  6925. (setq org-markers-to-move nil)
  6926. (when (featurep 'org-clock)
  6927. (org-clock-save-markers-for-cut-and-paste beg end))
  6928. (when (featurep 'org-agenda)
  6929. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6930. (defun org-check-and-save-marker (marker beg end)
  6931. "Check if MARKER is between BEG and END.
  6932. If yes, remember the marker and the distance to BEG."
  6933. (when (and (marker-buffer marker)
  6934. (equal (marker-buffer marker) (current-buffer))
  6935. (>= marker beg) (< marker end))
  6936. (push (cons marker (- marker beg)) org-markers-to-move)))
  6937. (defun org-reinstall-markers-in-region (beg)
  6938. "Move all remembered markers to their position relative to BEG."
  6939. (dolist (x org-markers-to-move)
  6940. (move-marker (car x) (+ beg (cdr x))))
  6941. (setq org-markers-to-move nil))
  6942. (defun org-narrow-to-subtree ()
  6943. "Narrow buffer to the current subtree."
  6944. (interactive)
  6945. (save-excursion
  6946. (save-match-data
  6947. (org-with-limited-levels
  6948. (narrow-to-region
  6949. (progn (org-back-to-heading t) (point))
  6950. (progn (org-end-of-subtree t t)
  6951. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6952. (point)))))))
  6953. (defun org-toggle-narrow-to-subtree ()
  6954. "Narrow to the subtree at point or widen a narrowed buffer."
  6955. (interactive)
  6956. (if (buffer-narrowed-p)
  6957. (progn (widen) (message "Buffer widen"))
  6958. (org-narrow-to-subtree)
  6959. (message "Buffer narrowed to current subtree")))
  6960. (defun org-narrow-to-block ()
  6961. "Narrow buffer to the current block."
  6962. (interactive)
  6963. (let* ((case-fold-search t)
  6964. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6965. "^[ \t]*#\\+end_.*")))
  6966. (if blockp
  6967. (narrow-to-region (car blockp) (cdr blockp))
  6968. (user-error "Not in a block"))))
  6969. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6970. "Clone the task (subtree) at point N times.
  6971. The clones will be inserted as siblings.
  6972. In interactive use, the user will be prompted for the number of
  6973. clones to be produced. If the entry has a timestamp, the user
  6974. will also be prompted for a time shift, which may be a repeater
  6975. as used in time stamps, for example `+3d'. To disable this,
  6976. you can call the function with a universal prefix argument.
  6977. When a valid repeater is given and the entry contains any time
  6978. stamps, the clones will become a sequence in time, with time
  6979. stamps in the subtree shifted for each clone produced. If SHIFT
  6980. is nil or the empty string, time stamps will be left alone. The
  6981. ID property of the original subtree is removed.
  6982. In each clone, all the CLOCK entries will be removed. This
  6983. prevents Org from considering that the clocked times overlap.
  6984. If the original subtree did contain time stamps with a repeater,
  6985. the following will happen:
  6986. - the repeater will be removed in each clone
  6987. - an additional clone will be produced, with the current, unshifted
  6988. date(s) in the entry.
  6989. - the original entry will be placed *after* all the clones, with
  6990. repeater intact.
  6991. - the start days in the repeater in the original entry will be shifted
  6992. to past the last clone.
  6993. In this way you can spell out a number of instances of a repeating task,
  6994. and still retain the repeater to cover future instances of the task.
  6995. As described above, N+1 clones are produced when the original
  6996. subtree has a repeater. Setting N to 0, then, can be used to
  6997. remove the repeater from a subtree and create a shifted clone
  6998. with the original repeater."
  6999. (interactive "nNumber of clones to produce: ")
  7000. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7001. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7002. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7003. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7004. (shift
  7005. (or shift
  7006. (if (and (not (equal current-prefix-arg '(4)))
  7007. (save-excursion
  7008. (goto-char beg)
  7009. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7010. (read-from-minibuffer
  7011. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7012. ""))) ;No time shift
  7013. (doshift
  7014. (and (org-string-nw-p shift)
  7015. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7016. shift)
  7017. (user-error "Invalid shift specification %s" shift)))))
  7018. (goto-char end-of-tree)
  7019. (unless (bolp) (insert "\n"))
  7020. (let* ((end (point))
  7021. (template (buffer-substring beg end))
  7022. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7023. (shift-what (pcase (and doshift (match-string 2 shift))
  7024. (`nil nil)
  7025. ("d" 'day)
  7026. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7027. ("m" 'month)
  7028. ("y" 'year)
  7029. (_ (error "Unsupported time unit"))))
  7030. (nmin 1)
  7031. (nmax n)
  7032. (n-no-remove -1)
  7033. (idprop (org-entry-get beg "ID")))
  7034. (when (and doshift
  7035. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7036. template))
  7037. (delete-region beg end)
  7038. (setq end beg)
  7039. (setq nmin 0)
  7040. (setq nmax (1+ nmax))
  7041. (setq n-no-remove nmax))
  7042. (goto-char end)
  7043. (cl-loop for n from nmin to nmax do
  7044. (insert
  7045. ;; Prepare clone.
  7046. (with-temp-buffer
  7047. (insert template)
  7048. (org-mode)
  7049. (goto-char (point-min))
  7050. (org-show-subtree)
  7051. (and idprop (if org-clone-delete-id
  7052. (org-entry-delete nil "ID")
  7053. (org-id-get-create t)))
  7054. (unless (= n 0)
  7055. (while (re-search-forward org-clock-line-re nil t)
  7056. (delete-region (line-beginning-position)
  7057. (line-beginning-position 2)))
  7058. (goto-char (point-min))
  7059. (while (re-search-forward org-drawer-regexp nil t)
  7060. (org-remove-empty-drawer-at (point))))
  7061. (goto-char (point-min))
  7062. (when doshift
  7063. (while (re-search-forward org-ts-regexp-both nil t)
  7064. (org-timestamp-change (* n shift-n) shift-what))
  7065. (unless (= n n-no-remove)
  7066. (goto-char (point-min))
  7067. (while (re-search-forward org-ts-regexp nil t)
  7068. (save-excursion
  7069. (goto-char (match-beginning 0))
  7070. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7071. (delete-region (match-beginning 1) (match-end 1)))))))
  7072. (buffer-string)))))
  7073. (goto-char beg)))
  7074. ;;; Outline Sorting
  7075. (defun org-sort (&optional with-case)
  7076. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7077. Optional argument WITH-CASE means sort case-sensitively."
  7078. (interactive "P")
  7079. (org-call-with-arg
  7080. (cond ((org-at-table-p) #'org-table-sort-lines)
  7081. ((org-at-item-p) #'org-sort-list)
  7082. (t #'org-sort-entries))
  7083. with-case))
  7084. (defun org-sort-remove-invisible (s)
  7085. "Remove invisible part of links and emphasis markers from string S."
  7086. (remove-text-properties 0 (length s) org-rm-props s)
  7087. (replace-regexp-in-string
  7088. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7089. (replace-regexp-in-string
  7090. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7091. (org-link-display-format s)
  7092. t t) t t))
  7093. (defvar org-after-sorting-entries-or-items-hook nil
  7094. "Hook that is run after a bunch of entries or items have been sorted.
  7095. When children are sorted, the cursor is in the parent line when this
  7096. hook gets called. When a region or a plain list is sorted, the cursor
  7097. will be in the first entry of the sorted region/list.")
  7098. (defun org-sort-entries
  7099. (&optional with-case sorting-type getkey-func compare-func property
  7100. interactive?)
  7101. "Sort entries on a certain level of an outline tree.
  7102. If there is an active region, the entries in the region are sorted.
  7103. Else, if the cursor is before the first entry, sort the top-level items.
  7104. Else, the children of the entry at point are sorted.
  7105. Sorting can be alphabetically, numerically, by date/time as given by
  7106. a time stamp, by a property, by priority order, or by a custom function.
  7107. The command prompts for the sorting type unless it has been given to the
  7108. function through the SORTING-TYPE argument, which needs to be a character,
  7109. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7110. the precise meaning of each character:
  7111. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7112. c By creation time, which is assumed to be the first inactive time stamp
  7113. at the beginning of a line.
  7114. d By deadline date/time.
  7115. k By clocking time.
  7116. n Numerically, by converting the beginning of the entry/item to a number.
  7117. o By order of TODO keywords.
  7118. p By priority according to the cookie.
  7119. r By the value of a property.
  7120. s By scheduled date/time.
  7121. t By date/time, either the first active time stamp in the entry, or, if
  7122. none exist, by the first inactive one.
  7123. Capital letters will reverse the sort order.
  7124. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7125. called with point at the beginning of the record. It must return a
  7126. value that is compatible with COMPARE-FUNC, the function used to
  7127. compare entries.
  7128. Comparing entries ignores case by default. However, with an optional argument
  7129. WITH-CASE, the sorting considers case as well.
  7130. Sorting is done against the visible part of the headlines, it ignores hidden
  7131. links.
  7132. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7133. A non-nil value for INTERACTIVE? is used to signal that this
  7134. function is being called interactively."
  7135. (interactive (list current-prefix-arg nil nil nil nil t))
  7136. (let ((case-func (if with-case 'identity 'downcase))
  7137. start beg end stars re re2
  7138. txt what tmp)
  7139. ;; Find beginning and end of region to sort
  7140. (cond
  7141. ((org-region-active-p)
  7142. ;; we will sort the region
  7143. (setq end (region-end)
  7144. what "region")
  7145. (goto-char (region-beginning))
  7146. (unless (org-at-heading-p) (outline-next-heading))
  7147. (setq start (point)))
  7148. ((or (org-at-heading-p)
  7149. (ignore-errors (progn (org-back-to-heading) t)))
  7150. ;; we will sort the children of the current headline
  7151. (org-back-to-heading)
  7152. (setq start (point)
  7153. end (progn (org-end-of-subtree t t)
  7154. (or (bolp) (insert "\n"))
  7155. (when (>= (org-back-over-empty-lines) 1)
  7156. (forward-line 1))
  7157. (point))
  7158. what "children")
  7159. (goto-char start)
  7160. (outline-show-subtree)
  7161. (outline-next-heading))
  7162. (t
  7163. ;; we will sort the top-level entries in this file
  7164. (goto-char (point-min))
  7165. (or (org-at-heading-p) (outline-next-heading))
  7166. (setq start (point))
  7167. (goto-char (point-max))
  7168. (beginning-of-line 1)
  7169. (when (looking-at ".*?\\S-")
  7170. ;; File ends in a non-white line
  7171. (end-of-line 1)
  7172. (insert "\n"))
  7173. (setq end (point-max))
  7174. (setq what "top-level")
  7175. (goto-char start)
  7176. (org-show-all '(headings blocks))))
  7177. (setq beg (point))
  7178. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7179. (looking-at "\\(\\*+\\)")
  7180. (setq stars (match-string 1)
  7181. re (concat "^" (regexp-quote stars) " +")
  7182. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7183. txt (buffer-substring beg end))
  7184. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7185. (when (and (not (equal stars "*")) (string-match re2 txt))
  7186. (user-error "Region to sort contains a level above the first entry"))
  7187. (unless sorting-type
  7188. (message
  7189. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7190. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7191. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7192. what)
  7193. (setq sorting-type (read-char-exclusive)))
  7194. (unless getkey-func
  7195. (and (= (downcase sorting-type) ?f)
  7196. (setq getkey-func
  7197. (or (and interactive?
  7198. (org-read-function
  7199. "Function for extracting keys: "))
  7200. (error "Missing key extractor")))))
  7201. (and (= (downcase sorting-type) ?r)
  7202. (not property)
  7203. (setq property
  7204. (completing-read "Property: "
  7205. (mapcar #'list (org-buffer-property-keys t))
  7206. nil t)))
  7207. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7208. (message "Sorting entries...")
  7209. (save-restriction
  7210. (narrow-to-region start end)
  7211. (let ((restore-clock?
  7212. ;; The clock marker is lost when using `sort-subr'; mark
  7213. ;; the clock with temporary `:org-clock-marker-backup'
  7214. ;; text property.
  7215. (when (and (eq (org-clock-is-active) (current-buffer))
  7216. (<= start (marker-position org-clock-marker))
  7217. (>= end (marker-position org-clock-marker)))
  7218. (with-silent-modifications
  7219. (put-text-property (1- org-clock-marker) org-clock-marker
  7220. :org-clock-marker-backup t))
  7221. t))
  7222. (dcst (downcase sorting-type))
  7223. (case-fold-search nil)
  7224. (now (current-time)))
  7225. (org-preserve-local-variables
  7226. (sort-subr
  7227. (/= dcst sorting-type)
  7228. ;; This function moves to the beginning character of the
  7229. ;; "record" to be sorted.
  7230. (lambda nil
  7231. (if (re-search-forward re nil t)
  7232. (goto-char (match-beginning 0))
  7233. (goto-char (point-max))))
  7234. ;; This function moves to the last character of the "record" being
  7235. ;; sorted.
  7236. (lambda nil
  7237. (save-match-data
  7238. (condition-case nil
  7239. (outline-forward-same-level 1)
  7240. (error
  7241. (goto-char (point-max))))))
  7242. ;; This function returns the value that gets sorted against.
  7243. (lambda ()
  7244. (cond
  7245. ((= dcst ?n)
  7246. (string-to-number
  7247. (org-sort-remove-invisible (org-get-heading t t t t))))
  7248. ((= dcst ?a)
  7249. (funcall case-func
  7250. (org-sort-remove-invisible (org-get-heading t t t t))))
  7251. ((= dcst ?k)
  7252. (or (get-text-property (point) :org-clock-minutes) 0))
  7253. ((= dcst ?t)
  7254. (let ((end (save-excursion (outline-next-heading) (point))))
  7255. (if (or (re-search-forward org-ts-regexp end t)
  7256. (re-search-forward org-ts-regexp-both end t))
  7257. (org-time-string-to-seconds (match-string 0))
  7258. (float-time now))))
  7259. ((= dcst ?c)
  7260. (let ((end (save-excursion (outline-next-heading) (point))))
  7261. (if (re-search-forward
  7262. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7263. end t)
  7264. (org-time-string-to-seconds (match-string 0))
  7265. (float-time now))))
  7266. ((= dcst ?s)
  7267. (let ((end (save-excursion (outline-next-heading) (point))))
  7268. (if (re-search-forward org-scheduled-time-regexp end t)
  7269. (org-time-string-to-seconds (match-string 1))
  7270. (float-time now))))
  7271. ((= dcst ?d)
  7272. (let ((end (save-excursion (outline-next-heading) (point))))
  7273. (if (re-search-forward org-deadline-time-regexp end t)
  7274. (org-time-string-to-seconds (match-string 1))
  7275. (float-time now))))
  7276. ((= dcst ?p)
  7277. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7278. (string-to-char (match-string 2))
  7279. org-priority-default))
  7280. ((= dcst ?r)
  7281. (or (org-entry-get nil property) ""))
  7282. ((= dcst ?o)
  7283. (when (looking-at org-complex-heading-regexp)
  7284. (let* ((m (match-string 2))
  7285. (s (if (member m org-done-keywords) '- '+)))
  7286. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7287. ((= dcst ?f)
  7288. (if getkey-func
  7289. (progn
  7290. (setq tmp (funcall getkey-func))
  7291. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7292. tmp)
  7293. (error "Invalid key function `%s'" getkey-func)))
  7294. (t (error "Invalid sorting type `%c'" sorting-type))))
  7295. nil
  7296. (cond
  7297. ((= dcst ?a) 'org-string-collate-lessp)
  7298. ((= dcst ?f)
  7299. (or compare-func
  7300. (and interactive?
  7301. (org-read-function
  7302. (concat "Function for comparing keys "
  7303. "(empty for default `sort-subr' predicate): ")
  7304. 'allow-empty))))
  7305. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7306. (org-cycle-hide-drawers 'all)
  7307. (when restore-clock?
  7308. (move-marker org-clock-marker
  7309. (1+ (next-single-property-change
  7310. start :org-clock-marker-backup)))
  7311. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7312. '(:org-clock-marker-backup t)))))
  7313. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7314. (message "Sorting entries...done")))
  7315. (defun org-contextualize-keys (alist contexts)
  7316. "Return valid elements in ALIST depending on CONTEXTS.
  7317. `org-agenda-custom-commands' or `org-capture-templates' are the
  7318. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7319. or `org-capture-templates-contexts' are the associated contexts
  7320. definitions."
  7321. (let ((contexts
  7322. ;; normalize contexts
  7323. (mapcar
  7324. (lambda(c) (cond ((listp (cadr c))
  7325. (list (car c) (car c) (nth 1 c)))
  7326. ((string= "" (cadr c))
  7327. (list (car c) (car c) (nth 2 c)))
  7328. (t c)))
  7329. contexts))
  7330. (a alist) r s)
  7331. ;; loop over all commands or templates
  7332. (dolist (c a)
  7333. (let (vrules repl)
  7334. (cond
  7335. ((not (assoc (car c) contexts))
  7336. (push c r))
  7337. ((and (assoc (car c) contexts)
  7338. (setq vrules (org-contextualize-validate-key
  7339. (car c) contexts)))
  7340. (mapc (lambda (vr)
  7341. (unless (equal (car vr) (cadr vr))
  7342. (setq repl vr)))
  7343. vrules)
  7344. (if (not repl) (push c r)
  7345. (push (cadr repl) s)
  7346. (push
  7347. (cons (car c)
  7348. (cdr (or (assoc (cadr repl) alist)
  7349. (error "Undefined key `%s' as contextual replacement for `%s'"
  7350. (cadr repl) (car c)))))
  7351. r))))))
  7352. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7353. (delq
  7354. nil
  7355. (delete-dups
  7356. (mapcar (lambda (x)
  7357. (let ((tpl (car x)))
  7358. (unless (delq
  7359. nil
  7360. (mapcar (lambda (y)
  7361. (equal y tpl))
  7362. s))
  7363. x)))
  7364. (reverse r))))))
  7365. (defun org-contextualize-validate-key (key contexts)
  7366. "Check CONTEXTS for agenda or capture KEY."
  7367. (let (res)
  7368. (dolist (r contexts)
  7369. (dolist (rr (car (last r)))
  7370. (when
  7371. (and (equal key (car r))
  7372. (if (functionp rr) (funcall rr)
  7373. (or (and (eq (car rr) 'in-file)
  7374. (buffer-file-name)
  7375. (string-match (cdr rr) (buffer-file-name)))
  7376. (and (eq (car rr) 'in-mode)
  7377. (string-match (cdr rr) (symbol-name major-mode)))
  7378. (and (eq (car rr) 'in-buffer)
  7379. (string-match (cdr rr) (buffer-name)))
  7380. (when (and (eq (car rr) 'not-in-file)
  7381. (buffer-file-name))
  7382. (not (string-match (cdr rr) (buffer-file-name))))
  7383. (when (eq (car rr) 'not-in-mode)
  7384. (not (string-match (cdr rr) (symbol-name major-mode))))
  7385. (when (eq (car rr) 'not-in-buffer)
  7386. (not (string-match (cdr rr) (buffer-name)))))))
  7387. (push r res))))
  7388. (delete-dups (delq nil res))))
  7389. ;; Defined to provide a value for defcustom, since there is no
  7390. ;; string-collate-greaterp in Emacs.
  7391. (defun org-string-collate-greaterp (s1 s2)
  7392. "Return non-nil if S1 is greater than S2 in collation order."
  7393. (not (org-string-collate-lessp s1 s2)))
  7394. ;;;###autoload
  7395. (defun org-run-like-in-org-mode (cmd)
  7396. "Run a command, pretending that the current buffer is in Org mode.
  7397. This will temporarily bind local variables that are typically bound in
  7398. Org mode to the values they have in Org mode, and then interactively
  7399. call CMD."
  7400. (org-load-modules-maybe)
  7401. (let (binds)
  7402. (dolist (var (org-get-local-variables))
  7403. (when (or (not (boundp (car var)))
  7404. (eq (symbol-value (car var))
  7405. (default-value (car var))))
  7406. (push (list (car var) `(quote ,(cadr var))) binds)))
  7407. (eval `(let ,binds
  7408. (call-interactively (quote ,cmd))))))
  7409. (defun org-get-category (&optional pos force-refresh)
  7410. "Get the category applying to position POS."
  7411. (save-match-data
  7412. (when force-refresh (org-refresh-category-properties))
  7413. (let ((pos (or pos (point))))
  7414. (or (get-text-property pos 'org-category)
  7415. (progn (org-refresh-category-properties)
  7416. (get-text-property pos 'org-category))))))
  7417. ;;; Refresh properties
  7418. (defun org-refresh-properties (dprop tprop)
  7419. "Refresh buffer text properties.
  7420. DPROP is the drawer property and TPROP is either the
  7421. corresponding text property to set, or an alist with each element
  7422. being a text property (as a symbol) and a function to apply to
  7423. the value of the drawer property."
  7424. (let* ((case-fold-search t)
  7425. (inhibit-read-only t)
  7426. (inherit? (org-property-inherit-p dprop))
  7427. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7428. (global-or-keyword (and inherit?
  7429. (org--property-global-or-keyword-value dprop nil))))
  7430. (with-silent-modifications
  7431. (org-with-point-at 1
  7432. ;; Set global and keyword based values to the whole buffer.
  7433. (when global-or-keyword
  7434. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7435. ;; Set values based on property-drawers throughout the document.
  7436. (while (re-search-forward property-re nil t)
  7437. (when (org-at-property-p)
  7438. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7439. (outline-next-heading))))))
  7440. (defun org-refresh-property (tprop p &optional inherit)
  7441. "Refresh the buffer text property TPROP from the drawer property P.
  7442. The refresh happens only for the current entry, or the whole
  7443. sub-tree if optional argument INHERIT is non-nil.
  7444. If point is before first headline, the function applies to the
  7445. part before the first headline. In that particular case, when
  7446. optional argument INHERIT is non-nil, it refreshes properties for
  7447. the whole buffer."
  7448. (save-excursion
  7449. (org-back-to-heading-or-point-min t)
  7450. (let ((start (point))
  7451. (end (save-excursion
  7452. (cond ((and inherit (org-before-first-heading-p))
  7453. (point-max))
  7454. (inherit
  7455. (org-end-of-subtree t t))
  7456. ((outline-next-heading))
  7457. ((point-max))))))
  7458. (if (symbolp tprop)
  7459. ;; TPROP is a text property symbol.
  7460. (put-text-property start end tprop p)
  7461. ;; TPROP is an alist with (property . function) elements.
  7462. (pcase-dolist (`(,prop . ,f) tprop)
  7463. (put-text-property start end prop (funcall f p)))))))
  7464. (defun org-refresh-category-properties ()
  7465. "Refresh category text properties in the buffer."
  7466. (let ((case-fold-search t)
  7467. (inhibit-read-only t)
  7468. (default-category
  7469. (cond ((null org-category)
  7470. (if buffer-file-name
  7471. (file-name-sans-extension
  7472. (file-name-nondirectory buffer-file-name))
  7473. "???"))
  7474. ((symbolp org-category) (symbol-name org-category))
  7475. (t org-category))))
  7476. (with-silent-modifications
  7477. (org-with-wide-buffer
  7478. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7479. ;; keyword. If none is found, fall-back to `org-category' or
  7480. ;; buffer file name, or set it by the document property drawer.
  7481. (put-text-property
  7482. (point-min) (point-max)
  7483. 'org-category
  7484. (catch 'buffer-category
  7485. (goto-char (point-max))
  7486. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7487. (let ((element (org-element-at-point)))
  7488. (when (eq (org-element-type element) 'keyword)
  7489. (throw 'buffer-category
  7490. (org-element-property :value element)))))
  7491. default-category))
  7492. ;; Set categories from the document property drawer or
  7493. ;; property drawers in the outline. If category is found in
  7494. ;; the property drawer for the whole buffer that value
  7495. ;; overrides the keyword-based value set above.
  7496. (goto-char (point-min))
  7497. (let ((regexp (org-re-property "CATEGORY")))
  7498. (while (re-search-forward regexp nil t)
  7499. (let ((value (match-string-no-properties 3)))
  7500. (when (org-at-property-p)
  7501. (put-text-property
  7502. (save-excursion (org-back-to-heading-or-point-min t))
  7503. (save-excursion (if (org-before-first-heading-p)
  7504. (point-max)
  7505. (org-end-of-subtree t t)))
  7506. 'org-category
  7507. value)))))))))
  7508. (defun org-refresh-stats-properties ()
  7509. "Refresh stats text properties in the buffer."
  7510. (with-silent-modifications
  7511. (org-with-point-at 1
  7512. (let ((regexp (concat org-outline-regexp-bol
  7513. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7514. (while (re-search-forward regexp nil t)
  7515. (let* ((numerator (string-to-number (match-string 1)))
  7516. (denominator (and (match-end 2)
  7517. (string-to-number (match-string 2))))
  7518. (stats (cond ((not denominator) numerator) ;percent
  7519. ((= denominator 0) 0)
  7520. (t (/ (* numerator 100) denominator)))))
  7521. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7522. 'org-stats stats)))))))
  7523. (defun org-refresh-effort-properties ()
  7524. "Refresh effort properties."
  7525. (org-refresh-properties
  7526. org-effort-property
  7527. '((effort . identity)
  7528. (effort-minutes . org-duration-to-minutes))))
  7529. (defun org-find-file-at-mouse (ev)
  7530. "Open file link or URL at mouse."
  7531. (interactive "e")
  7532. (mouse-set-point ev)
  7533. (org-open-at-point 'in-emacs))
  7534. (defun org-open-at-mouse (ev)
  7535. "Open file link or URL at mouse.
  7536. See the docstring of `org-open-file' for details."
  7537. (interactive "e")
  7538. (mouse-set-point ev)
  7539. (when (eq major-mode 'org-agenda-mode)
  7540. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7541. (org-open-at-point))
  7542. (defvar org-window-config-before-follow-link nil
  7543. "The window configuration before following a link.
  7544. This is saved in case the need arises to restore it.")
  7545. (defun org--file-default-apps ()
  7546. "Return the default applications for this operating system."
  7547. (pcase system-type
  7548. (`darwin org-file-apps-macos)
  7549. (`windows-nt org-file-apps-windowsnt)
  7550. (_ org-file-apps-gnu)))
  7551. (defun org--file-apps-entry-dlink-p (entry)
  7552. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7553. It assumes that is the case when the entry uses a regular
  7554. expression which has at least one grouping construct and the
  7555. action is either a Lisp form or a command string containing
  7556. \"%1\", i.e., using at least one subexpression match as
  7557. a parameter."
  7558. (pcase entry
  7559. (`(,selector . ,action)
  7560. (and (stringp selector)
  7561. (> (regexp-opt-depth selector) 0)
  7562. (or (and (stringp action)
  7563. (string-match "%[0-9]" action))
  7564. (consp action))))
  7565. (_ nil)))
  7566. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7567. "Convert extensions to regular expressions in the cars of LIST.
  7568. Also, weed out any non-string entries, because the return value
  7569. is used only for regexp matching.
  7570. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7571. point to the symbol `emacs', indicating that the file should be
  7572. opened in Emacs."
  7573. (append
  7574. (delq nil
  7575. (mapcar (lambda (x)
  7576. (unless (not (stringp (car x)))
  7577. (if (string-match "\\W" (car x))
  7578. x
  7579. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7580. list))
  7581. (when add-auto-mode
  7582. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7583. ;;;###autoload
  7584. (defun org-open-file (path &optional in-emacs line search)
  7585. "Open the file at PATH.
  7586. First, this expands any special file name abbreviations. Then the
  7587. configuration variable `org-file-apps' is checked if it contains an
  7588. entry for this file type, and if yes, the corresponding command is launched.
  7589. If no application is found, Emacs simply visits the file.
  7590. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7591. With a double \\[universal-argument] \\[universal-argument] \
  7592. prefix arg, Org tries to avoid opening in Emacs
  7593. and to use an external application to visit the file.
  7594. Optional LINE specifies a line to go to, optional SEARCH a string
  7595. to search for. If LINE or SEARCH is given, the file will be
  7596. opened in Emacs, unless an entry from `org-file-apps' that makes
  7597. use of groups in a regexp matches.
  7598. If you want to change the way frames are used when following a
  7599. link, please customize `org-link-frame-setup'.
  7600. If the file does not exist, throw an error."
  7601. (let* ((file (if (equal path "") buffer-file-name
  7602. (substitute-in-file-name (expand-file-name path))))
  7603. (file-apps (append org-file-apps (org--file-default-apps)))
  7604. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7605. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7606. file-apps))
  7607. (remp (and (assq 'remote apps) (file-remote-p file)))
  7608. (dirp (unless remp (file-directory-p file)))
  7609. (file (if (and dirp org-open-directory-means-index-dot-org)
  7610. (concat (file-name-as-directory file) "index.org")
  7611. file))
  7612. (a-m-a-p (assq 'auto-mode apps))
  7613. (dfile (downcase file))
  7614. ;; Reconstruct the original link from the PATH, LINE and
  7615. ;; SEARCH args.
  7616. (link (cond (line (concat file "::" (number-to-string line)))
  7617. (search (concat file "::" search))
  7618. (t file)))
  7619. (dlink (downcase link))
  7620. (ext
  7621. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7622. (match-string 1 dfile)))
  7623. (save-position-maybe
  7624. (let ((old-buffer (current-buffer))
  7625. (old-pos (point))
  7626. (old-mode major-mode))
  7627. (lambda ()
  7628. (and (derived-mode-p 'org-mode)
  7629. (eq old-mode 'org-mode)
  7630. (or (not (eq old-buffer (current-buffer)))
  7631. (not (eq old-pos (point))))
  7632. (org-mark-ring-push old-pos old-buffer)))))
  7633. cmd link-match-data)
  7634. (cond
  7635. ((member in-emacs '((16) system))
  7636. (setq cmd (cdr (assq 'system apps))))
  7637. (in-emacs (setq cmd 'emacs))
  7638. (t
  7639. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7640. (and dirp (cdr (assq 'directory apps)))
  7641. ;; First, try matching against apps-dlink if we
  7642. ;; get a match here, store the match data for
  7643. ;; later.
  7644. (let ((match (assoc-default dlink apps-dlink
  7645. 'string-match)))
  7646. (if match
  7647. (progn (setq link-match-data (match-data))
  7648. match)
  7649. (progn (setq in-emacs (or in-emacs line search))
  7650. nil))) ; if we have no match in apps-dlink,
  7651. ; always open the file in emacs if line or search
  7652. ; is given (for backwards compatibility)
  7653. (assoc-default dfile
  7654. (org--file-apps-regexp-alist apps a-m-a-p)
  7655. 'string-match)
  7656. (cdr (assoc ext apps))
  7657. (cdr (assq t apps))))))
  7658. (when (eq cmd 'system)
  7659. (setq cmd (cdr (assq 'system apps))))
  7660. (when (eq cmd 'default)
  7661. (setq cmd (cdr (assoc t apps))))
  7662. (when (eq cmd 'mailcap)
  7663. (require 'mailcap)
  7664. (mailcap-parse-mailcaps)
  7665. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7666. (command (mailcap-mime-info mime-type)))
  7667. (if (stringp command)
  7668. (setq cmd command)
  7669. (setq cmd 'emacs))))
  7670. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7671. (not (file-exists-p file))
  7672. (not org-open-non-existing-files))
  7673. (user-error "No such file: %s" file))
  7674. (cond
  7675. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7676. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7677. (while (string-match "['\"]%s['\"]" cmd)
  7678. (setq cmd (replace-match "%s" t t cmd)))
  7679. (setq cmd (replace-regexp-in-string
  7680. "%s"
  7681. (shell-quote-argument (convert-standard-filename file))
  7682. cmd
  7683. nil t))
  7684. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7685. (save-match-data
  7686. (let ((match-index 1)
  7687. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7688. (set-match-data link-match-data)
  7689. (while (<= match-index number-of-groups)
  7690. (let ((regex (concat "%" (number-to-string match-index)))
  7691. (replace-with (match-string match-index dlink)))
  7692. (while (string-match regex cmd)
  7693. (setq cmd (replace-match replace-with t t cmd))))
  7694. (setq match-index (+ match-index 1)))))
  7695. (save-window-excursion
  7696. (message "Running %s...done" cmd)
  7697. (start-process-shell-command cmd nil cmd)
  7698. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7699. ((or (stringp cmd)
  7700. (eq cmd 'emacs))
  7701. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7702. (widen)
  7703. (cond (line (org-goto-line line)
  7704. (when (derived-mode-p 'org-mode) (org-reveal)))
  7705. (search (condition-case err
  7706. (org-link-search search)
  7707. ;; Save position before error-ing out so user
  7708. ;; can easily move back to the original buffer.
  7709. (error (funcall save-position-maybe)
  7710. (error (nth 1 err)))))))
  7711. ((functionp cmd)
  7712. (save-match-data
  7713. (set-match-data link-match-data)
  7714. (condition-case nil
  7715. (funcall cmd file link)
  7716. ;; FIXME: Remove this check when most default installations
  7717. ;; of Emacs have at least Org 9.0.
  7718. ((debug wrong-number-of-arguments wrong-type-argument
  7719. invalid-function)
  7720. (user-error "Please see Org News for version 9.0 about \
  7721. `org-file-apps'--Lisp error: %S" cmd)))))
  7722. ((consp cmd)
  7723. ;; FIXME: Remove this check when most default installations of
  7724. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7725. ;; fall back to `org-link-frame-setup' for an old usage of
  7726. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7727. (user-error "Please see Org News for version 9.0 about \
  7728. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7729. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7730. (funcall save-position-maybe)))
  7731. ;;;###autoload
  7732. (defun org-open-at-point-global ()
  7733. "Follow a link or a time-stamp like Org mode does.
  7734. Also follow links and emails as seen by `thing-at-point'.
  7735. This command can be called in any mode to follow an external
  7736. link or a time-stamp that has Org mode syntax. Its behavior
  7737. is undefined when called on internal links like fuzzy links.
  7738. Raise a user error when there is nothing to follow."
  7739. (interactive)
  7740. (let ((tap-url (thing-at-point 'url))
  7741. (tap-email (thing-at-point 'email)))
  7742. (cond ((org-in-regexp org-link-any-re)
  7743. (org-link-open-from-string (match-string-no-properties 0)))
  7744. ((or (org-in-regexp org-ts-regexp-both nil t)
  7745. (org-in-regexp org-tsr-regexp-both nil t))
  7746. (org-follow-timestamp-link))
  7747. (tap-url (org-link-open-from-string tap-url))
  7748. (tap-email (org-link-open-from-string
  7749. (concat "mailto:" tap-email)))
  7750. (t (user-error "No link found")))))
  7751. (defvar org-open-at-point-functions nil
  7752. "Hook that is run when following a link at point.
  7753. Functions in this hook must return t if they identify and follow
  7754. a link at point. If they don't find anything interesting at point,
  7755. they must return nil.")
  7756. (defun org-open-at-point (&optional arg)
  7757. "Open link, timestamp, footnote or tags at point.
  7758. When point is on a link, follow it. Normally, files will be
  7759. opened by an appropriate application. If the optional prefix
  7760. argument ARG is non-nil, Emacs will visit the file. With
  7761. a double prefix argument, try to open outside of Emacs, in the
  7762. application the system uses for this file type.
  7763. When point is on a timestamp, open the agenda at the day
  7764. specified.
  7765. When point is a footnote definition, move to the first reference
  7766. found. If it is on a reference, move to the associated
  7767. definition.
  7768. When point is on a headline, display a list of every link in the
  7769. entry, so it is possible to pick one, or all, of them. If point
  7770. is on a tag, call `org-tags-view' instead.
  7771. On top of syntactically correct links, this function also tries
  7772. to open links and time-stamps in comments, node properties, and
  7773. keywords if point is on something looking like a timestamp or
  7774. a link."
  7775. (interactive "P")
  7776. (org-load-modules-maybe)
  7777. (setq org-window-config-before-follow-link (current-window-configuration))
  7778. (org-remove-occur-highlights nil nil t)
  7779. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7780. (let* ((context
  7781. ;; Only consider supported types, even if they are not the
  7782. ;; closest one.
  7783. (org-element-lineage
  7784. (org-element-context)
  7785. '(clock comment comment-block footnote-definition
  7786. footnote-reference headline inline-src-block inlinetask
  7787. keyword link node-property planning src-block timestamp)
  7788. t))
  7789. (type (org-element-type context))
  7790. (value (org-element-property :value context)))
  7791. (cond
  7792. ((not type) (user-error "No link found"))
  7793. ;; No valid link at point. For convenience, look if something
  7794. ;; looks like a link under point in some specific places.
  7795. ((memq type '(comment comment-block node-property keyword))
  7796. (call-interactively #'org-open-at-point-global))
  7797. ;; On a headline or an inlinetask, but not on a timestamp,
  7798. ;; a link, a footnote reference.
  7799. ((memq type '(headline inlinetask))
  7800. (org-match-line org-complex-heading-regexp)
  7801. (let ((tags-beg (match-beginning 5))
  7802. (tags-end (match-end 5)))
  7803. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7804. ;; On tags.
  7805. (org-tags-view
  7806. arg
  7807. (save-excursion
  7808. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7809. (end-tag (search-forward ":" tags-end nil 2)))
  7810. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7811. ;; Not on tags.
  7812. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7813. (`(nil . ,_)
  7814. (require 'org-attach)
  7815. (when (org-attach-dir)
  7816. (message "Opening attachment")
  7817. (if (equal arg '(4))
  7818. (org-attach-reveal-in-emacs)
  7819. (org-attach-reveal))))
  7820. (`(,links . ,links-end)
  7821. (dolist (link (if (stringp links) (list links) links))
  7822. (search-forward link nil links-end)
  7823. (goto-char (match-beginning 0))
  7824. (org-open-at-point arg)))))))
  7825. ;; On a footnote reference or at definition's label.
  7826. ((or (eq type 'footnote-reference)
  7827. (and (eq type 'footnote-definition)
  7828. (save-excursion
  7829. ;; Do not validate action when point is on the
  7830. ;; spaces right after the footnote label, in order
  7831. ;; to be on par with behavior on links.
  7832. (skip-chars-forward " \t")
  7833. (let ((begin
  7834. (org-element-property :contents-begin context)))
  7835. (if begin (< (point) begin)
  7836. (= (org-element-property :post-affiliated context)
  7837. (line-beginning-position)))))))
  7838. (org-footnote-action))
  7839. ;; On a planning line. Check if we are really on a timestamp.
  7840. ((and (eq type 'planning)
  7841. (org-in-regexp org-ts-regexp-both nil t))
  7842. (org-follow-timestamp-link))
  7843. ;; On a clock line, make sure point is on the timestamp
  7844. ;; before opening it.
  7845. ((and (eq type 'clock)
  7846. value
  7847. (>= (point) (org-element-property :begin value))
  7848. (<= (point) (org-element-property :end value)))
  7849. (org-follow-timestamp-link))
  7850. ((eq type 'src-block) (org-babel-open-src-block-result))
  7851. ;; Do nothing on white spaces after an object.
  7852. ((>= (point)
  7853. (save-excursion
  7854. (goto-char (org-element-property :end context))
  7855. (skip-chars-backward " \t")
  7856. (point)))
  7857. (user-error "No link found"))
  7858. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7859. ((eq type 'timestamp) (org-follow-timestamp-link))
  7860. ((eq type 'link) (org-link-open context arg))
  7861. (t (user-error "No link found")))))
  7862. (run-hook-with-args 'org-follow-link-hook))
  7863. ;;;###autoload
  7864. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7865. "Offer links in the current entry and return the selected link.
  7866. If there is only one link, return it.
  7867. If NTH is an integer, return the NTH link found.
  7868. If ZERO is a string, check also this string for a link, and if
  7869. there is one, return it."
  7870. (with-current-buffer buffer
  7871. (org-with-wide-buffer
  7872. (goto-char marker)
  7873. (let ((cnt ?0)
  7874. have-zero end links link c)
  7875. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7876. (push (match-string 0 zero) links)
  7877. (setq cnt (1- cnt) have-zero t))
  7878. (save-excursion
  7879. (org-back-to-heading t)
  7880. (setq end (save-excursion (outline-next-heading) (point)))
  7881. (while (re-search-forward org-link-any-re end t)
  7882. (push (match-string 0) links))
  7883. (setq links (org-uniquify (reverse links))))
  7884. (cond
  7885. ((null links)
  7886. (message "No links"))
  7887. ((equal (length links) 1)
  7888. (setq link (car links)))
  7889. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7890. (setq link (nth (if have-zero nth (1- nth)) links)))
  7891. (t ; we have to select a link
  7892. (save-excursion
  7893. (save-window-excursion
  7894. (delete-other-windows)
  7895. (with-output-to-temp-buffer "*Select Link*"
  7896. (dolist (l links)
  7897. (cond
  7898. ((not (string-match org-link-bracket-re l))
  7899. (princ (format "[%c] %s\n" (cl-incf cnt)
  7900. (org-unbracket-string "<" ">" l))))
  7901. ((match-end 2)
  7902. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7903. (match-string 2 l) (match-string 1 l))))
  7904. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7905. (match-string 1 l)))))))
  7906. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7907. (message "Select link to open, RET to open all:")
  7908. (setq c (read-char-exclusive))
  7909. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7910. (when (equal c ?q) (user-error "Abort"))
  7911. (if (equal c ?\C-m)
  7912. (setq link links)
  7913. (setq nth (- c ?0))
  7914. (when have-zero (setq nth (1+ nth)))
  7915. (unless (and (integerp nth) (>= (length links) nth))
  7916. (user-error "Invalid link selection"))
  7917. (setq link (nth (1- nth) links)))))
  7918. (cons link end)))))
  7919. ;;; File search
  7920. (defun org-do-occur (regexp &optional cleanup)
  7921. "Call the Emacs command `occur'.
  7922. If CLEANUP is non-nil, remove the printout of the regular expression
  7923. in the *Occur* buffer. This is useful if the regex is long and not useful
  7924. to read."
  7925. (occur regexp)
  7926. (when cleanup
  7927. (let ((cwin (selected-window)) win beg end)
  7928. (when (setq win (get-buffer-window "*Occur*"))
  7929. (select-window win))
  7930. (goto-char (point-min))
  7931. (when (re-search-forward "match[a-z]+" nil t)
  7932. (setq beg (match-end 0))
  7933. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7934. (setq end (1- (match-beginning 0)))))
  7935. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7936. (goto-char (point-min))
  7937. (select-window cwin))))
  7938. ;;; The Mark Ring
  7939. (defvar org-mark-ring nil
  7940. "Mark ring for positions before jumps in Org mode.")
  7941. (defvar org-mark-ring-last-goto nil
  7942. "Last position in the mark ring used to go back.")
  7943. ;; Fill and close the ring
  7944. (setq org-mark-ring nil)
  7945. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7946. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7947. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7948. org-mark-ring)
  7949. (defun org-mark-ring-push (&optional pos buffer)
  7950. "Put the current position into the mark ring and rotate it.
  7951. Also push position into the Emacs mark ring. If optional
  7952. argument POS and BUFFER are not nil, mark this location instead."
  7953. (interactive)
  7954. (let ((pos (or pos (point)))
  7955. (buffer (or buffer (current-buffer))))
  7956. (with-current-buffer buffer
  7957. (org-with-point-at pos (push-mark nil t)))
  7958. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  7959. (move-marker (car org-mark-ring) pos buffer))
  7960. (message
  7961. (substitute-command-keys
  7962. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  7963. (defun org-mark-ring-goto (&optional n)
  7964. "Jump to the previous position in the mark ring.
  7965. With prefix arg N, jump back that many stored positions. When
  7966. called several times in succession, walk through the entire ring.
  7967. Org mode commands jumping to a different position in the current file,
  7968. or to another Org file, automatically push the old position onto the ring."
  7969. (interactive "p")
  7970. (let (p m)
  7971. (if (eq last-command this-command)
  7972. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  7973. (setq p org-mark-ring))
  7974. (setq org-mark-ring-last-goto p)
  7975. (setq m (car p))
  7976. (pop-to-buffer-same-window (marker-buffer m))
  7977. (goto-char m)
  7978. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  7979. ;;; Following specific links
  7980. (defvar org-agenda-buffer-tmp-name)
  7981. (defvar org-agenda-start-on-weekday)
  7982. (defun org-follow-timestamp-link ()
  7983. "Open an agenda view for the time-stamp date/range at point."
  7984. (cond
  7985. ((org-at-date-range-p t)
  7986. (let ((org-agenda-start-on-weekday)
  7987. (t1 (match-string 1))
  7988. (t2 (match-string 2)) tt1 tt2)
  7989. (setq tt1 (time-to-days (org-time-string-to-time t1))
  7990. tt2 (time-to-days (org-time-string-to-time t2)))
  7991. (let ((org-agenda-buffer-tmp-name
  7992. (format "*Org Agenda(a:%s)"
  7993. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  7994. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  7995. ((org-at-timestamp-p 'lax)
  7996. (let ((org-agenda-buffer-tmp-name
  7997. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  7998. (org-agenda-list nil (time-to-days (org-time-string-to-time
  7999. (substring (match-string 1) 0 10)))
  8000. 1)))
  8001. (t (error "This should not happen"))))
  8002. ;;; Following file links
  8003. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  8004. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  8005. (declare-function mailcap-mime-info
  8006. "mailcap" (string &optional request no-decode))
  8007. (defvar org-wait nil)
  8008. ;;;; Refiling
  8009. (defun org-get-org-file ()
  8010. "Read a filename, with default directory `org-directory'."
  8011. (let ((default (or org-default-notes-file remember-data-file)))
  8012. (read-file-name (format "File name [%s]: " default)
  8013. (file-name-as-directory org-directory)
  8014. default)))
  8015. (defun org-notes-order-reversed-p ()
  8016. "Check if the current file should receive notes in reversed order."
  8017. (cond
  8018. ((not org-reverse-note-order) nil)
  8019. ((eq t org-reverse-note-order) t)
  8020. ((not (listp org-reverse-note-order)) nil)
  8021. (t (catch 'exit
  8022. (dolist (entry org-reverse-note-order)
  8023. (when (string-match (car entry) buffer-file-name)
  8024. (throw 'exit (cdr entry))))))))
  8025. (defvar org-refile-target-table nil
  8026. "The list of refile targets, created by `org-refile'.")
  8027. (defvar org-agenda-new-buffers nil
  8028. "Buffers created to visit agenda files.")
  8029. (defvar org-refile-cache nil
  8030. "Cache for refile targets.")
  8031. (defvar org-refile-markers nil
  8032. "All the markers used for caching refile locations.")
  8033. (defun org-refile-marker (pos)
  8034. "Get a new refile marker, but only if caching is in use."
  8035. (if (not org-refile-use-cache)
  8036. pos
  8037. (let ((m (make-marker)))
  8038. (move-marker m pos)
  8039. (push m org-refile-markers)
  8040. m)))
  8041. (defun org-refile-cache-clear ()
  8042. "Clear the refile cache and disable all the markers."
  8043. (dolist (m org-refile-markers) (move-marker m nil))
  8044. (setq org-refile-markers nil)
  8045. (setq org-refile-cache nil)
  8046. (message "Refile cache has been cleared"))
  8047. (defun org-refile-cache-check-set (set)
  8048. "Check if all the markers in the cache still have live buffers."
  8049. (let (marker)
  8050. (catch 'exit
  8051. (while (and set (setq marker (nth 3 (pop set))))
  8052. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  8053. (when (and marker (null (marker-buffer marker)))
  8054. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  8055. (sit-for 3)
  8056. (throw 'exit nil)))
  8057. t)))
  8058. (defun org-refile-cache-put (set &rest identifiers)
  8059. "Push the refile targets SET into the cache, under IDENTIFIERS."
  8060. (let* ((key (sha1 (prin1-to-string identifiers)))
  8061. (entry (assoc key org-refile-cache)))
  8062. (if entry
  8063. (setcdr entry set)
  8064. (push (cons key set) org-refile-cache))))
  8065. (defun org-refile-cache-get (&rest identifiers)
  8066. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  8067. (cond
  8068. ((not org-refile-cache) nil)
  8069. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  8070. (t
  8071. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  8072. org-refile-cache))))
  8073. (and set (org-refile-cache-check-set set) set)))))
  8074. (defvar org-outline-path-cache nil
  8075. "Alist between buffer positions and outline paths.
  8076. It value is an alist (POSITION . PATH) where POSITION is the
  8077. buffer position at the beginning of an entry and PATH is a list
  8078. of strings describing the outline path for that entry, in reverse
  8079. order.")
  8080. (defun org-refile-get-targets (&optional default-buffer)
  8081. "Produce a table with refile targets."
  8082. (let ((case-fold-search nil)
  8083. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  8084. (entries (or org-refile-targets '((nil . (:level . 1)))))
  8085. targets tgs files desc descre)
  8086. (message "Getting targets...")
  8087. (with-current-buffer (or default-buffer (current-buffer))
  8088. (dolist (entry entries)
  8089. (setq files (car entry) desc (cdr entry))
  8090. (cond
  8091. ((null files) (setq files (list (current-buffer))))
  8092. ((eq files 'org-agenda-files)
  8093. (setq files (org-agenda-files 'unrestricted)))
  8094. ((and (symbolp files) (fboundp files))
  8095. (setq files (funcall files)))
  8096. ((and (symbolp files) (boundp files))
  8097. (setq files (symbol-value files))))
  8098. (when (stringp files) (setq files (list files)))
  8099. (cond
  8100. ((eq (car desc) :tag)
  8101. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  8102. ((eq (car desc) :todo)
  8103. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  8104. ((eq (car desc) :regexp)
  8105. (setq descre (cdr desc)))
  8106. ((eq (car desc) :level)
  8107. (setq descre (concat "^\\*\\{" (number-to-string
  8108. (if org-odd-levels-only
  8109. (1- (* 2 (cdr desc)))
  8110. (cdr desc)))
  8111. "\\}[ \t]")))
  8112. ((eq (car desc) :maxlevel)
  8113. (setq descre (concat "^\\*\\{1," (number-to-string
  8114. (if org-odd-levels-only
  8115. (1- (* 2 (cdr desc)))
  8116. (cdr desc)))
  8117. "\\}[ \t]")))
  8118. (t (error "Bad refiling target description %s" desc)))
  8119. (dolist (f files)
  8120. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  8121. (or
  8122. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  8123. (progn
  8124. (when (bufferp f)
  8125. (setq f (buffer-file-name (buffer-base-buffer f))))
  8126. (setq f (and f (expand-file-name f)))
  8127. (when (eq org-refile-use-outline-path 'file)
  8128. (push (list (file-name-nondirectory f) f nil nil) tgs))
  8129. (when (eq org-refile-use-outline-path 'buffer-name)
  8130. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  8131. (when (eq org-refile-use-outline-path 'full-file-path)
  8132. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  8133. (org-with-wide-buffer
  8134. (goto-char (point-min))
  8135. (setq org-outline-path-cache nil)
  8136. (while (re-search-forward descre nil t)
  8137. (beginning-of-line)
  8138. (let ((case-fold-search nil))
  8139. (looking-at org-complex-heading-regexp))
  8140. (let ((begin (point))
  8141. (heading (match-string-no-properties 4)))
  8142. (unless (or (and
  8143. org-refile-target-verify-function
  8144. (not
  8145. (funcall org-refile-target-verify-function)))
  8146. (not heading))
  8147. (let ((re (format org-complex-heading-regexp-format
  8148. (regexp-quote heading)))
  8149. (target
  8150. (if (not org-refile-use-outline-path) heading
  8151. (mapconcat
  8152. #'identity
  8153. (append
  8154. (pcase org-refile-use-outline-path
  8155. (`file (list (file-name-nondirectory
  8156. (buffer-file-name
  8157. (buffer-base-buffer)))))
  8158. (`full-file-path
  8159. (list (buffer-file-name
  8160. (buffer-base-buffer))))
  8161. (`buffer-name
  8162. (list (buffer-name
  8163. (buffer-base-buffer))))
  8164. (_ nil))
  8165. (mapcar (lambda (s) (replace-regexp-in-string
  8166. "/" "\\/" s nil t))
  8167. (org-get-outline-path t t)))
  8168. "/"))))
  8169. (push (list target f re (org-refile-marker (point)))
  8170. tgs)))
  8171. (when (= (point) begin)
  8172. ;; Verification function has not moved point.
  8173. (end-of-line)))))))
  8174. (when org-refile-use-cache
  8175. (org-refile-cache-put tgs (buffer-file-name) descre))
  8176. (setq targets (append tgs targets))))))
  8177. (message "Getting targets...done")
  8178. (delete-dups (nreverse targets))))
  8179. (defun org--get-outline-path-1 (&optional use-cache)
  8180. "Return outline path to current headline.
  8181. Outline path is a list of strings, in reverse order. When
  8182. optional argument USE-CACHE is non-nil, make use of a cache. See
  8183. `org-get-outline-path' for details.
  8184. Assume buffer is widened and point is on a headline."
  8185. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  8186. (let ((p (point))
  8187. (heading (let ((case-fold-search nil))
  8188. (looking-at org-complex-heading-regexp)
  8189. (if (not (match-end 4)) ""
  8190. ;; Remove statistics cookies.
  8191. (org-trim
  8192. (org-link-display-format
  8193. (replace-regexp-in-string
  8194. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  8195. (match-string-no-properties 4))))))))
  8196. (if (org-up-heading-safe)
  8197. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  8198. (when use-cache
  8199. (push (cons p path) org-outline-path-cache))
  8200. path)
  8201. ;; This is a new root node. Since we assume we are moving
  8202. ;; forward, we can drop previous cache so as to limit number
  8203. ;; of associations there.
  8204. (let ((path (list heading)))
  8205. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  8206. path)))))
  8207. (defun org-get-outline-path (&optional with-self use-cache)
  8208. "Return the outline path to the current entry.
  8209. An outline path is a list of ancestors for current headline, as
  8210. a list of strings. Statistics cookies are removed and links are
  8211. replaced with their description, if any, or their path otherwise.
  8212. When optional argument WITH-SELF is non-nil, the path also
  8213. includes the current headline.
  8214. When optional argument USE-CACHE is non-nil, cache outline paths
  8215. between calls to this function so as to avoid backtracking. This
  8216. argument is useful when planning to find more than one outline
  8217. path in the same document. In that case, there are two
  8218. conditions to satisfy:
  8219. - `org-outline-path-cache' is set to nil before starting the
  8220. process;
  8221. - outline paths are computed by increasing buffer positions."
  8222. (org-with-wide-buffer
  8223. (and (or (and with-self (org-back-to-heading t))
  8224. (org-up-heading-safe))
  8225. (reverse (org--get-outline-path-1 use-cache)))))
  8226. (defun org-format-outline-path (path &optional width prefix separator)
  8227. "Format the outline path PATH for display.
  8228. WIDTH is the maximum number of characters that is available.
  8229. PREFIX is a prefix to be included in the returned string,
  8230. such as the file name.
  8231. SEPARATOR is inserted between the different parts of the path,
  8232. the default is \"/\"."
  8233. (setq width (or width 79))
  8234. (setq path (delq nil path))
  8235. (unless (> width 0)
  8236. (user-error "Argument `width' must be positive"))
  8237. (setq separator (or separator "/"))
  8238. (let* ((org-odd-levels-only nil)
  8239. (fpath (concat
  8240. prefix (and prefix path separator)
  8241. (mapconcat
  8242. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  8243. (cl-loop for head in path
  8244. for n from 0
  8245. collect (org-add-props
  8246. head nil 'face
  8247. (nth (% n org-n-level-faces) org-level-faces)))
  8248. separator))))
  8249. (when (> (length fpath) width)
  8250. (if (< width 7)
  8251. ;; It's unlikely that `width' will be this small, but don't
  8252. ;; waste characters by adding ".." if it is.
  8253. (setq fpath (substring fpath 0 width))
  8254. (setf (substring fpath (- width 2)) "..")))
  8255. fpath))
  8256. (defun org-display-outline-path (&optional file current separator just-return-string)
  8257. "Display the current outline path in the echo area.
  8258. If FILE is non-nil, prepend the output with the file name.
  8259. If CURRENT is non-nil, append the current heading to the output.
  8260. SEPARATOR is passed through to `org-format-outline-path'. It separates
  8261. the different parts of the path and defaults to \"/\".
  8262. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  8263. (interactive "P")
  8264. (let* (case-fold-search
  8265. (bfn (buffer-file-name (buffer-base-buffer)))
  8266. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  8267. res)
  8268. (when current (setq path (append path
  8269. (save-excursion
  8270. (org-back-to-heading t)
  8271. (when (looking-at org-complex-heading-regexp)
  8272. (list (match-string 4)))))))
  8273. (setq res
  8274. (org-format-outline-path
  8275. path
  8276. (1- (frame-width))
  8277. (and file bfn (concat (file-name-nondirectory bfn) separator))
  8278. separator))
  8279. (if just-return-string
  8280. (org-no-properties res)
  8281. (org-unlogged-message "%s" res))))
  8282. (defvar org-refile-history nil
  8283. "History for refiling operations.")
  8284. (defvar org-after-refile-insert-hook nil
  8285. "Hook run after `org-refile' has inserted its stuff at the new location.
  8286. Note that this is still *before* the stuff will be removed from
  8287. the *old* location.")
  8288. (defvar org-capture-last-stored-marker)
  8289. (defvar org-refile-keep nil
  8290. "Non-nil means `org-refile' will copy instead of refile.")
  8291. (defun org-copy ()
  8292. "Like `org-refile', but copy."
  8293. (interactive)
  8294. (let ((org-refile-keep t))
  8295. (org-refile nil nil nil "Copy")))
  8296. (defun org-refile (&optional arg default-buffer rfloc msg)
  8297. "Move the entry or entries at point to another heading.
  8298. The list of target headings is compiled using the information in
  8299. `org-refile-targets', which see.
  8300. At the target location, the entry is filed as a subitem of the
  8301. target heading. Depending on `org-reverse-note-order', the new
  8302. subitem will either be the first or the last subitem.
  8303. If there is an active region, all entries in that region will be
  8304. refiled. However, the region must fulfill the requirement that
  8305. the first heading sets the top-level of the moved text.
  8306. With a `\\[universal-argument]' ARG, the command will only visit the target \
  8307. location
  8308. and not actually move anything.
  8309. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  8310. location where the last
  8311. refiling operation has put the subtree.
  8312. With a numeric prefix argument of `2', refile to the running clock.
  8313. With a numeric prefix argument of `3', emulate `org-refile-keep'
  8314. being set to t and copy to the target location, don't move it.
  8315. Beware that keeping refiled entries may result in duplicated ID
  8316. properties.
  8317. RFLOC can be a refile location obtained in a different way.
  8318. MSG is a string to replace \"Refile\" in the default prompt with
  8319. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  8320. See also `org-refile-use-outline-path'.
  8321. If you are using target caching (see `org-refile-use-cache'), you
  8322. have to clear the target cache in order to find new targets.
  8323. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  8324. prefix argument (`C-u C-u C-u C-c C-w')."
  8325. (interactive "P")
  8326. (if (member arg '(0 (64)))
  8327. (org-refile-cache-clear)
  8328. (let* ((actionmsg (cond (msg msg)
  8329. ((equal arg 3) "Refile (and keep)")
  8330. (t "Refile")))
  8331. (regionp (org-region-active-p))
  8332. (region-start (and regionp (region-beginning)))
  8333. (region-end (and regionp (region-end)))
  8334. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  8335. pos it nbuf file level reversed)
  8336. (setq last-command nil)
  8337. (when regionp
  8338. (goto-char region-start)
  8339. (beginning-of-line)
  8340. (setq region-start (point))
  8341. (unless (or (org-kill-is-subtree-p
  8342. (buffer-substring region-start region-end))
  8343. (prog1 org-refile-active-region-within-subtree
  8344. (let ((s (point-at-eol)))
  8345. (org-toggle-heading)
  8346. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  8347. (user-error "The region is not a (sequence of) subtree(s)")))
  8348. (if (equal arg '(16))
  8349. (org-refile-goto-last-stored)
  8350. (when (or
  8351. (and (equal arg 2)
  8352. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  8353. (prog1
  8354. (setq it (list (or org-clock-heading "running clock")
  8355. (buffer-file-name
  8356. (marker-buffer org-clock-hd-marker))
  8357. ""
  8358. (marker-position org-clock-hd-marker)))
  8359. (setq arg nil)))
  8360. (setq it
  8361. (or rfloc
  8362. (let (heading-text)
  8363. (save-excursion
  8364. (unless (and arg (listp arg))
  8365. (org-back-to-heading t)
  8366. (setq heading-text
  8367. (replace-regexp-in-string
  8368. org-link-bracket-re
  8369. "\\2"
  8370. (or (nth 4 (org-heading-components))
  8371. ""))))
  8372. (org-refile-get-location
  8373. (cond ((and arg (listp arg)) "Goto")
  8374. (regionp (concat actionmsg " region to"))
  8375. (t (concat actionmsg " subtree \""
  8376. heading-text "\" to")))
  8377. default-buffer
  8378. (and (not (equal '(4) arg))
  8379. org-refile-allow-creating-parent-nodes)))))))
  8380. (setq file (nth 1 it)
  8381. pos (nth 3 it))
  8382. (when (and (not arg)
  8383. pos
  8384. (equal (buffer-file-name) file)
  8385. (if regionp
  8386. (and (>= pos region-start)
  8387. (<= pos region-end))
  8388. (and (>= pos (point))
  8389. (< pos (save-excursion
  8390. (org-end-of-subtree t t))))))
  8391. (error "Cannot refile to position inside the tree or region"))
  8392. (setq nbuf (or (find-buffer-visiting file)
  8393. (find-file-noselect file)))
  8394. (if (and arg (not (equal arg 3)))
  8395. (progn
  8396. (pop-to-buffer-same-window nbuf)
  8397. (goto-char (cond (pos)
  8398. ((org-notes-order-reversed-p) (point-min))
  8399. (t (point-max))))
  8400. (org-show-context 'org-goto))
  8401. (if regionp
  8402. (progn
  8403. (org-kill-new (buffer-substring region-start region-end))
  8404. (org-save-markers-in-region region-start region-end))
  8405. (org-copy-subtree 1 nil t))
  8406. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  8407. (find-file-noselect file)))
  8408. (setq reversed (org-notes-order-reversed-p))
  8409. (org-with-wide-buffer
  8410. (if pos
  8411. (progn
  8412. (goto-char pos)
  8413. (setq level (org-get-valid-level (funcall outline-level) 1))
  8414. (goto-char
  8415. (if reversed
  8416. (or (outline-next-heading) (point-max))
  8417. (or (save-excursion (org-get-next-sibling))
  8418. (org-end-of-subtree t t)
  8419. (point-max)))))
  8420. (setq level 1)
  8421. (if (not reversed)
  8422. (goto-char (point-max))
  8423. (goto-char (point-min))
  8424. (or (outline-next-heading) (goto-char (point-max)))))
  8425. (unless (bolp) (newline))
  8426. (org-paste-subtree level nil nil t)
  8427. ;; Record information, according to `org-log-refile'.
  8428. ;; Do not prompt for a note when refiling multiple
  8429. ;; headlines, however. Simply add a time stamp.
  8430. (cond
  8431. ((not org-log-refile))
  8432. (regionp
  8433. (org-map-region
  8434. (lambda () (org-add-log-setup 'refile nil nil 'time))
  8435. (point)
  8436. (+ (point) (- region-end region-start))))
  8437. (t
  8438. (org-add-log-setup 'refile nil nil org-log-refile)))
  8439. (and org-auto-align-tags
  8440. (let ((org-loop-over-headlines-in-active-region nil))
  8441. (org-align-tags)))
  8442. (let ((bookmark-name (plist-get org-bookmark-names-plist
  8443. :last-refile)))
  8444. (when bookmark-name
  8445. (with-demoted-errors
  8446. (bookmark-set bookmark-name))))
  8447. ;; If we are refiling for capture, make sure that the
  8448. ;; last-capture pointers point here
  8449. (when (bound-and-true-p org-capture-is-refiling)
  8450. (let ((bookmark-name (plist-get org-bookmark-names-plist
  8451. :last-capture-marker)))
  8452. (when bookmark-name
  8453. (with-demoted-errors
  8454. (bookmark-set bookmark-name))))
  8455. (move-marker org-capture-last-stored-marker (point)))
  8456. (when (fboundp 'deactivate-mark) (deactivate-mark))
  8457. (run-hooks 'org-after-refile-insert-hook)))
  8458. (unless org-refile-keep
  8459. (if regionp
  8460. (delete-region (point) (+ (point) (- region-end region-start)))
  8461. (org-preserve-local-variables
  8462. (delete-region
  8463. (and (org-back-to-heading t) (point))
  8464. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  8465. (when (featurep 'org-inlinetask)
  8466. (org-inlinetask-remove-END-maybe))
  8467. (setq org-markers-to-move nil)
  8468. (message "%s to \"%s\" in file %s: done" actionmsg
  8469. (car it) file)))))))
  8470. (defun org-refile-goto-last-stored ()
  8471. "Go to the location where the last refile was stored."
  8472. (interactive)
  8473. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  8474. (message "This is the location of the last refile"))
  8475. (defun org-refile--get-location (refloc tbl)
  8476. "When user refile to REFLOC, find the associated target in TBL.
  8477. Also check `org-refile-target-table'."
  8478. (car (delq
  8479. nil
  8480. (mapcar
  8481. (lambda (r) (or (assoc r tbl)
  8482. (assoc r org-refile-target-table)))
  8483. (list (replace-regexp-in-string "/$" "" refloc)
  8484. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  8485. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  8486. "Prompt the user for a refile location, using PROMPT.
  8487. PROMPT should not be suffixed with a colon and a space, because
  8488. this function appends the default value from
  8489. `org-refile-history' automatically, if that is not empty."
  8490. (let ((org-refile-targets org-refile-targets)
  8491. (org-refile-use-outline-path org-refile-use-outline-path))
  8492. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  8493. (unless org-refile-target-table
  8494. (user-error "No refile targets"))
  8495. (let* ((cbuf (current-buffer))
  8496. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  8497. (cfunc (if (and org-refile-use-outline-path
  8498. org-outline-path-complete-in-steps)
  8499. #'org-olpath-completing-read
  8500. #'completing-read))
  8501. (extra (if org-refile-use-outline-path "/" ""))
  8502. (cbnex (concat (buffer-name) extra))
  8503. (filename (and cfn (expand-file-name cfn)))
  8504. (tbl (mapcar
  8505. (lambda (x)
  8506. (if (and (not (member org-refile-use-outline-path
  8507. '(file full-file-path)))
  8508. (not (equal filename (nth 1 x))))
  8509. (cons (concat (car x) extra " ("
  8510. (file-name-nondirectory (nth 1 x)) ")")
  8511. (cdr x))
  8512. (cons (concat (car x) extra) (cdr x))))
  8513. org-refile-target-table))
  8514. (completion-ignore-case t)
  8515. cdef
  8516. (prompt (concat prompt
  8517. (or (and (car org-refile-history)
  8518. (concat " (default " (car org-refile-history) ")"))
  8519. (and (assoc cbnex tbl) (setq cdef cbnex)
  8520. (concat " (default " cbnex ")"))) ": "))
  8521. pa answ parent-target child parent old-hist)
  8522. (setq old-hist org-refile-history)
  8523. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  8524. nil 'org-refile-history (or cdef (car org-refile-history))))
  8525. (if (setq pa (org-refile--get-location answ tbl))
  8526. (progn
  8527. (org-refile-check-position pa)
  8528. (when (or (not org-refile-history)
  8529. (not (eq old-hist org-refile-history))
  8530. (not (equal (car pa) (car org-refile-history))))
  8531. (setq org-refile-history
  8532. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  8533. org-refile-history
  8534. (cdr org-refile-history))))
  8535. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  8536. (pop org-refile-history)))
  8537. pa)
  8538. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  8539. (progn
  8540. (setq parent (match-string 1 answ)
  8541. child (match-string 2 answ))
  8542. (setq parent-target (org-refile--get-location parent tbl))
  8543. (when (and parent-target
  8544. (or (eq new-nodes t)
  8545. (and (eq new-nodes 'confirm)
  8546. (y-or-n-p (format "Create new node \"%s\"? "
  8547. child)))))
  8548. (org-refile-new-child parent-target child)))
  8549. (user-error "Invalid target location")))))
  8550. (declare-function org-string-nw-p "org-macs" (s))
  8551. (defun org-refile-check-position (refile-pointer)
  8552. "Check if the refile pointer matches the headline to which it points."
  8553. (let* ((file (nth 1 refile-pointer))
  8554. (re (nth 2 refile-pointer))
  8555. (pos (nth 3 refile-pointer))
  8556. buffer)
  8557. (if (and (not (markerp pos)) (not file))
  8558. (user-error "Please indicate a target file in the refile path")
  8559. (when (org-string-nw-p re)
  8560. (setq buffer (if (markerp pos)
  8561. (marker-buffer pos)
  8562. (or (find-buffer-visiting file)
  8563. (find-file-noselect file))))
  8564. (with-current-buffer buffer
  8565. (org-with-wide-buffer
  8566. (goto-char pos)
  8567. (beginning-of-line 1)
  8568. (unless (looking-at-p re)
  8569. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  8570. (defun org-refile-new-child (parent-target child)
  8571. "Use refile target PARENT-TARGET to add new CHILD below it."
  8572. (unless parent-target
  8573. (error "Cannot find parent for new node"))
  8574. (let ((file (nth 1 parent-target))
  8575. (pos (nth 3 parent-target))
  8576. level)
  8577. (with-current-buffer (or (find-buffer-visiting file)
  8578. (find-file-noselect file))
  8579. (org-with-wide-buffer
  8580. (if pos
  8581. (goto-char pos)
  8582. (goto-char (point-max))
  8583. (unless (bolp) (newline)))
  8584. (when (looking-at org-outline-regexp)
  8585. (setq level (funcall outline-level))
  8586. (org-end-of-subtree t t))
  8587. (org-back-over-empty-lines)
  8588. (insert "\n" (make-string
  8589. (if pos (org-get-valid-level level 1) 1) ?*)
  8590. " " child "\n")
  8591. (beginning-of-line 0)
  8592. (list (concat (car parent-target) "/" child) file "" (point))))))
  8593. (defun org-olpath-completing-read (prompt collection &rest args)
  8594. "Read an outline path like a file name."
  8595. (let ((thetable collection))
  8596. (apply #'completing-read
  8597. prompt
  8598. (lambda (string predicate &optional flag)
  8599. (cond
  8600. ((eq flag nil) (try-completion string thetable))
  8601. ((eq flag t)
  8602. (let ((l (length string)))
  8603. (mapcar (lambda (x)
  8604. (let ((r (substring x l))
  8605. (f (if (string-match " ([^)]*)$" x)
  8606. (match-string 0 x)
  8607. "")))
  8608. (if (string-match "/" r)
  8609. (concat string (substring r 0 (match-end 0)) f)
  8610. x)))
  8611. (all-completions string thetable predicate))))
  8612. ;; Exact match?
  8613. ((eq flag 'lambda) (assoc string thetable))))
  8614. args)))
  8615. ;;;; Dynamic blocks
  8616. (defun org-find-dblock (name)
  8617. "Find the first dynamic block with name NAME in the buffer.
  8618. If not found, stay at current position and return nil."
  8619. (let ((case-fold-search t) pos)
  8620. (save-excursion
  8621. (goto-char (point-min))
  8622. (setq pos (and (re-search-forward
  8623. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8624. (match-beginning 0))))
  8625. (when pos (goto-char pos))
  8626. pos))
  8627. (defun org-create-dblock (plist)
  8628. "Create a dynamic block section, with parameters taken from PLIST.
  8629. PLIST must contain a :name entry which is used as the name of the block."
  8630. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8631. (end-of-line 1)
  8632. (newline))
  8633. (let ((col (current-column))
  8634. (name (plist-get plist :name)))
  8635. (insert "#+BEGIN: " name)
  8636. (while plist
  8637. (if (eq (car plist) :name)
  8638. (setq plist (cddr plist))
  8639. (insert " " (prin1-to-string (pop plist)))))
  8640. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8641. (beginning-of-line -2)))
  8642. (defun org-prepare-dblock ()
  8643. "Prepare dynamic block for refresh.
  8644. This empties the block, puts the cursor at the insert position and returns
  8645. the property list including an extra property :name with the block name."
  8646. (unless (looking-at org-dblock-start-re)
  8647. (user-error "Not at a dynamic block"))
  8648. (let* ((begdel (1+ (match-end 0)))
  8649. (name (org-no-properties (match-string 1)))
  8650. (params (append (list :name name)
  8651. (read (concat "(" (match-string 3) ")")))))
  8652. (save-excursion
  8653. (beginning-of-line 1)
  8654. (skip-chars-forward " \t")
  8655. (setq params (plist-put params :indentation-column (current-column))))
  8656. (unless (re-search-forward org-dblock-end-re nil t)
  8657. (error "Dynamic block not terminated"))
  8658. (setq params
  8659. (append params
  8660. (list :content (buffer-substring
  8661. begdel (match-beginning 0)))))
  8662. (delete-region begdel (match-beginning 0))
  8663. (goto-char begdel)
  8664. (open-line 1)
  8665. params))
  8666. (defun org-map-dblocks (&optional command)
  8667. "Apply COMMAND to all dynamic blocks in the current buffer.
  8668. If COMMAND is not given, use `org-update-dblock'."
  8669. (let ((cmd (or command 'org-update-dblock)))
  8670. (save-excursion
  8671. (goto-char (point-min))
  8672. (while (re-search-forward org-dblock-start-re nil t)
  8673. (goto-char (match-beginning 0))
  8674. (save-excursion
  8675. (condition-case nil
  8676. (funcall cmd)
  8677. (error (message "Error during update of dynamic block"))))
  8678. (unless (re-search-forward org-dblock-end-re nil t)
  8679. (error "Dynamic block not terminated"))))))
  8680. (defvar org-dynamic-block-alist nil
  8681. "Alist defining all the Org dynamic blocks.
  8682. The key is the dynamic block type name, as a string. The value
  8683. is the function used to insert the dynamic block.
  8684. Use `org-dynamic-block-define' to populate it.")
  8685. (defun org-dynamic-block-function (type)
  8686. "Return function associated to a given dynamic block type.
  8687. TYPE is the dynamic block type, as a string."
  8688. (cdr (assoc type org-dynamic-block-alist)))
  8689. (defun org-dynamic-block-types ()
  8690. "List all defined dynamic block types."
  8691. (mapcar #'car org-dynamic-block-alist))
  8692. (defun org-dynamic-block-define (type func)
  8693. "Define dynamic block TYPE with FUNC.
  8694. TYPE is a string. FUNC is the function creating the dynamic
  8695. block of such type."
  8696. (pcase (assoc type org-dynamic-block-alist)
  8697. (`nil (push (cons type func) org-dynamic-block-alist))
  8698. (def (setcdr def func))))
  8699. (defun org-dynamic-block-insert-dblock (type)
  8700. "Insert a dynamic block of type TYPE.
  8701. When used interactively, select the dynamic block types among
  8702. defined types, per `org-dynamic-block-define'."
  8703. (interactive (list (completing-read "Dynamic block: "
  8704. (org-dynamic-block-types))))
  8705. (pcase (org-dynamic-block-function type)
  8706. (`nil (error "No such dynamic block: %S" type))
  8707. ((and f (pred functionp)) (funcall f))
  8708. (_ (error "Invalid function for dynamic block %S" type))))
  8709. (defun org-dblock-update (&optional arg)
  8710. "User command for updating dynamic blocks.
  8711. Update the dynamic block at point. With prefix ARG, update all dynamic
  8712. blocks in the buffer."
  8713. (interactive "P")
  8714. (if arg
  8715. (org-update-all-dblocks)
  8716. (or (looking-at org-dblock-start-re)
  8717. (org-beginning-of-dblock))
  8718. (org-update-dblock)))
  8719. (defun org-update-dblock ()
  8720. "Update the dynamic block at point.
  8721. This means to empty the block, parse for parameters and then call
  8722. the correct writing function."
  8723. (interactive)
  8724. (save-excursion
  8725. (let* ((win (selected-window))
  8726. (pos (point))
  8727. (line (org-current-line))
  8728. (params (org-prepare-dblock))
  8729. (name (plist-get params :name))
  8730. (indent (plist-get params :indentation-column))
  8731. (cmd (intern (concat "org-dblock-write:" name))))
  8732. (message "Updating dynamic block `%s' at line %d..." name line)
  8733. (funcall cmd params)
  8734. (message "Updating dynamic block `%s' at line %d...done" name line)
  8735. (goto-char pos)
  8736. (when (and indent (> indent 0))
  8737. (setq indent (make-string indent ?\ ))
  8738. (save-excursion
  8739. (select-window win)
  8740. (org-beginning-of-dblock)
  8741. (forward-line 1)
  8742. (while (not (looking-at org-dblock-end-re))
  8743. (insert indent)
  8744. (beginning-of-line 2))
  8745. (when (looking-at org-dblock-end-re)
  8746. (and (looking-at "[ \t]+")
  8747. (replace-match ""))
  8748. (insert indent)))))))
  8749. (defun org-beginning-of-dblock ()
  8750. "Find the beginning of the dynamic block at point.
  8751. Error if there is no such block at point."
  8752. (let ((pos (point))
  8753. beg)
  8754. (end-of-line 1)
  8755. (if (and (re-search-backward org-dblock-start-re nil t)
  8756. (setq beg (match-beginning 0))
  8757. (re-search-forward org-dblock-end-re nil t)
  8758. (> (match-end 0) pos))
  8759. (goto-char beg)
  8760. (goto-char pos)
  8761. (error "Not in a dynamic block"))))
  8762. (defun org-update-all-dblocks ()
  8763. "Update all dynamic blocks in the buffer.
  8764. This function can be used in a hook."
  8765. (interactive)
  8766. (when (derived-mode-p 'org-mode)
  8767. (org-map-dblocks 'org-update-dblock)))
  8768. ;;;; Completion
  8769. (declare-function org-export-backend-options "ox" (cl-x) t)
  8770. (defun org-get-export-keywords ()
  8771. "Return a list of all currently understood export keywords.
  8772. Export keywords include options, block names, attributes and
  8773. keywords relative to each registered export back-end."
  8774. (let (keywords)
  8775. (dolist (backend
  8776. (bound-and-true-p org-export-registered-backends)
  8777. (delq nil keywords))
  8778. ;; Back-end name (for keywords, like #+LATEX:)
  8779. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8780. (dolist (option-entry (org-export-backend-options backend))
  8781. ;; Back-end options.
  8782. (push (nth 1 option-entry) keywords)))))
  8783. (defconst org-options-keywords
  8784. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8785. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8786. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8787. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8788. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8789. (defcustom org-structure-template-alist
  8790. '(("a" . "export ascii")
  8791. ("c" . "center")
  8792. ("C" . "comment")
  8793. ("e" . "example")
  8794. ("E" . "export")
  8795. ("h" . "export html")
  8796. ("l" . "export latex")
  8797. ("q" . "quote")
  8798. ("s" . "src")
  8799. ("v" . "verse"))
  8800. "An alist of keys and block types.
  8801. `org-insert-structure-template' will display a menu with this
  8802. list of templates to choose from. The block type is inserted,
  8803. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8804. The menu keys are defined by the car of each entry in this alist.
  8805. If two entries have the keys \"a\" and \"aa\" respectively, the
  8806. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8807. latter will be inserted by typing \"aa\". If an entry with the
  8808. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8809. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8810. block can be inserted by pressing TAB after the string \"<KEY\"."
  8811. :group 'org-edit-structure
  8812. :type '(repeat
  8813. (cons (string :tag "Key")
  8814. (string :tag "Template")))
  8815. :package-version '(Org . "9.2"))
  8816. (defun org--check-org-structure-template-alist (&optional checklist)
  8817. "Check whether `org-structure-template-alist' is set up correctly.
  8818. In particular, check if the Org 9.2 format is used as opposed to
  8819. previous format.
  8820. "
  8821. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8822. (or (eval checklist)
  8823. org-structure-template-alist))))
  8824. (when elm
  8825. (org-display-warning
  8826. (format "
  8827. Please update the entries of `%s'.
  8828. In Org 9.2 the format was changed from something like
  8829. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8830. to something like
  8831. (\"s\" . \"src\")
  8832. Please refer to the documentation of `org-structure-template-alist'.
  8833. The following entries must be updated:
  8834. %s"
  8835. (or checklist 'org-structure-template-alist)
  8836. (pp-to-string elm))))))
  8837. (defun org--insert-structure-template-mks ()
  8838. "Present `org-structure-template-alist' with `org-mks'.
  8839. Menus are added if keys require more than one keystroke. Tabs
  8840. are added to single key entries when more than one stroke is
  8841. needed. Keys longer than two characters are reduced to two
  8842. characters."
  8843. (org--check-org-structure-template-alist)
  8844. (let* (case-fold-search
  8845. (templates (append org-structure-template-alist
  8846. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8847. (keys (mapcar #'car templates))
  8848. (start-letters
  8849. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8850. ;; Sort each element of `org-structure-template-alist' into
  8851. ;; sublists according to the first letter.
  8852. (superlist
  8853. (mapcar (lambda (letter)
  8854. (list letter
  8855. (cl-remove-if-not
  8856. (apply-partially #'string-match-p (concat "^" letter))
  8857. templates :key #'car)))
  8858. start-letters)))
  8859. (org-mks
  8860. (apply #'append
  8861. ;; Make an `org-mks' table. If only one element is
  8862. ;; present in a sublist, make it part of the top-menu,
  8863. ;; otherwise make a submenu according to the starting
  8864. ;; letter and populate it.
  8865. (mapcar (lambda (sublist)
  8866. (if (eq 1 (length (cadr sublist)))
  8867. (mapcar (lambda (elm)
  8868. (list (substring (car elm) 0 1)
  8869. (cdr elm) ""))
  8870. (cadr sublist))
  8871. ;; Create submenu.
  8872. (let* ((topkey (car sublist))
  8873. (elms (cadr sublist))
  8874. (keys (mapcar #'car elms))
  8875. (long (> (length elms) 3)))
  8876. (append
  8877. (list
  8878. ;; Make a description of the submenu.
  8879. (list topkey
  8880. (concat
  8881. (mapconcat #'cdr
  8882. (cl-subseq elms 0 (if long 3 (length elms)))
  8883. ", ")
  8884. (when long ", ..."))))
  8885. ;; List of entries in submenu.
  8886. (cl-mapcar #'list
  8887. (org--insert-structure-template-unique-keys keys)
  8888. (mapcar #'cdr elms)
  8889. (make-list (length elms) ""))))))
  8890. superlist))
  8891. "Select a key\n============"
  8892. "Key: ")))
  8893. (defun org--insert-structure-template-unique-keys (keys)
  8894. "Make a list of unique, two characters long elements from KEYS.
  8895. Elements of length one have a tab appended. Elements of length
  8896. two are kept as is. Longer elements are truncated to length two.
  8897. If an element cannot be made unique, an error is raised."
  8898. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8899. menu-keys)
  8900. (dolist (key ordered-keys)
  8901. (let ((potential-key
  8902. (cl-case (length key)
  8903. (1 (concat key "\t"))
  8904. (2 key)
  8905. (otherwise
  8906. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8907. (mapcar (apply-partially #'concat (substring key 0 1))
  8908. (split-string (substring key 1) "" t)))))))
  8909. (if (or (not potential-key) (assoc potential-key menu-keys))
  8910. (user-error "Could not make unique key for %s." key)
  8911. (push (cons potential-key key) menu-keys))))
  8912. (mapcar #'car
  8913. (cl-sort menu-keys #'<
  8914. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8915. (defun org-insert-structure-template (type)
  8916. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8917. Select a block from `org-structure-template-alist' then type
  8918. either RET, TAB or SPC to write the block type. With an active
  8919. region, wrap the region in the block. Otherwise, insert an empty
  8920. block."
  8921. (interactive
  8922. (list (pcase (org--insert-structure-template-mks)
  8923. (`("\t" . ,_) (read-string "Structure type: "))
  8924. (`(,_ ,choice . ,_) choice))))
  8925. (let* ((region? (use-region-p))
  8926. (region-start (and region? (region-beginning)))
  8927. (region-end (and region? (copy-marker (region-end))))
  8928. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8929. (verbatim? (string-match-p
  8930. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8931. type)))
  8932. (when region? (goto-char region-start))
  8933. (let ((column (current-indentation)))
  8934. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8935. (beginning-of-line)
  8936. (insert "\n"))
  8937. (save-excursion
  8938. (indent-to column)
  8939. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8940. (when region?
  8941. (when verbatim? (org-escape-code-in-region (point) region-end))
  8942. (goto-char region-end)
  8943. ;; Ignore empty lines at the end of the region.
  8944. (skip-chars-backward " \r\t\n")
  8945. (end-of-line))
  8946. (unless (bolp) (insert "\n"))
  8947. (indent-to column)
  8948. (insert (format "#+end_%s" (car (split-string type))))
  8949. (if (looking-at "[ \t]*$") (replace-match "")
  8950. (insert "\n"))
  8951. (when (and (eobp) (not (bolp))) (insert "\n")))
  8952. (if extended? (end-of-line)
  8953. (forward-line)
  8954. (skip-chars-forward " \t")))))
  8955. ;;;; TODO, DEADLINE, Comments
  8956. (defun org-toggle-comment ()
  8957. "Change the COMMENT state of an entry."
  8958. (interactive)
  8959. (save-excursion
  8960. (org-back-to-heading)
  8961. (let ((case-fold-search nil))
  8962. (looking-at org-complex-heading-regexp))
  8963. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8964. (skip-chars-forward " \t")
  8965. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8966. (if (org-in-commented-heading-p t)
  8967. (delete-region (point)
  8968. (progn (search-forward " " (line-end-position) 'move)
  8969. (skip-chars-forward " \t")
  8970. (point)))
  8971. (insert org-comment-string)
  8972. (unless (eolp) (insert " ")))))
  8973. (defvar org-last-todo-state-is-todo nil
  8974. "This is non-nil when the last TODO state change led to a TODO state.
  8975. If the last change removed the TODO tag or switched to DONE, then
  8976. this is nil.")
  8977. (defvar org-todo-setup-filter-hook nil
  8978. "Hook for functions that pre-filter todo specs.
  8979. Each function takes a todo spec and returns either nil or the spec
  8980. transformed into canonical form." )
  8981. (defvar org-todo-get-default-hook nil
  8982. "Hook for functions that get a default item for todo.
  8983. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8984. nil or a string to be used for the todo mark." )
  8985. (defvar org-agenda-headline-snapshot-before-repeat)
  8986. (defun org-current-effective-time ()
  8987. "Return current time adjusted for `org-extend-today-until' variable."
  8988. (let* ((ct (org-current-time))
  8989. (dct (decode-time ct))
  8990. (ct1
  8991. (cond
  8992. (org-use-last-clock-out-time-as-effective-time
  8993. (or (org-clock-get-last-clock-out-time) ct))
  8994. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8995. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8996. (t ct))))
  8997. ct1))
  8998. (defun org-todo-yesterday (&optional arg)
  8999. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  9000. (interactive "P")
  9001. (if (eq major-mode 'org-agenda-mode)
  9002. (apply 'org-agenda-todo-yesterday arg)
  9003. (let* ((org-use-effective-time t)
  9004. (hour (nth 2 (decode-time (org-current-time))))
  9005. (org-extend-today-until (1+ hour)))
  9006. (org-todo arg))))
  9007. (defvar org-block-entry-blocking ""
  9008. "First entry preventing the TODO state change.")
  9009. (defun org-cancel-repeater ()
  9010. "Cancel a repeater by setting its numeric value to zero."
  9011. (interactive)
  9012. (save-excursion
  9013. (org-back-to-heading t)
  9014. (let ((bound1 (point))
  9015. (bound0 (save-excursion (outline-next-heading) (point))))
  9016. (when (and (re-search-forward
  9017. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  9018. org-deadline-time-regexp "\\)\\|\\("
  9019. org-ts-regexp "\\)")
  9020. bound0 t)
  9021. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  9022. bound1 t))
  9023. (replace-match "0" t nil nil 1)))))
  9024. (defvar org-state)
  9025. (defvar org-blocked-by-checkboxes)
  9026. (defun org-todo (&optional arg)
  9027. "Change the TODO state of an item.
  9028. The state of an item is given by a keyword at the start of the heading,
  9029. like
  9030. *** TODO Write paper
  9031. *** DONE Call mom
  9032. The different keywords are specified in the variable `org-todo-keywords'.
  9033. By default the available states are \"TODO\" and \"DONE\". So, for this
  9034. example: when the item starts with TODO, it is changed to DONE.
  9035. When it starts with DONE, the DONE is removed. And when neither TODO nor
  9036. DONE are present, add TODO at the beginning of the heading.
  9037. You can set up single-character keys to fast-select the new state. See the
  9038. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  9039. With `\\[universal-argument]' prefix ARG, force logging the state change \
  9040. and take a
  9041. logging note.
  9042. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  9043. next set of TODO \
  9044. keywords (nextset).
  9045. Another way to achieve this is `S-C-<right>'.
  9046. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9047. prefix, circumvent any state blocking.
  9048. With numeric prefix arg, switch to the Nth state.
  9049. With a numeric prefix arg of 0, inhibit note taking for the change.
  9050. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  9051. When called through ELisp, arg is also interpreted in the following way:
  9052. `none' -> empty state
  9053. \"\" -> switch to empty state
  9054. `done' -> switch to DONE
  9055. `nextset' -> switch to the next set of keywords
  9056. `previousset' -> switch to the previous set of keywords
  9057. \"WAITING\" -> switch to the specified keyword, but only if it
  9058. really is a member of `org-todo-keywords'."
  9059. (interactive "P")
  9060. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9061. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9062. 'region-start-level 'region))
  9063. org-loop-over-headlines-in-active-region)
  9064. (org-map-entries
  9065. `(org-todo ,arg)
  9066. org-loop-over-headlines-in-active-region
  9067. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  9068. (when (equal arg '(16)) (setq arg 'nextset))
  9069. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  9070. (let ((org-blocker-hook org-blocker-hook)
  9071. commentp
  9072. case-fold-search)
  9073. (when (equal arg '(64))
  9074. (setq arg nil org-blocker-hook nil))
  9075. (when (and org-blocker-hook
  9076. (or org-inhibit-blocking
  9077. (org-entry-get nil "NOBLOCKING")))
  9078. (setq org-blocker-hook nil))
  9079. (save-excursion
  9080. (catch 'exit
  9081. (org-back-to-heading t)
  9082. (when (org-in-commented-heading-p t)
  9083. (org-toggle-comment)
  9084. (setq commentp t))
  9085. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  9086. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  9087. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  9088. (let* ((match-data (match-data))
  9089. (startpos (copy-marker (line-beginning-position)))
  9090. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  9091. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  9092. (org-log-done org-log-done)
  9093. (org-log-repeat org-log-repeat)
  9094. (org-todo-log-states org-todo-log-states)
  9095. (org-inhibit-logging
  9096. (if (equal arg 0)
  9097. (progn (setq arg nil) 'note) org-inhibit-logging))
  9098. (this (match-string 1))
  9099. (hl-pos (match-beginning 0))
  9100. (head (org-get-todo-sequence-head this))
  9101. (ass (assoc head org-todo-kwd-alist))
  9102. (interpret (nth 1 ass))
  9103. (done-word (nth 3 ass))
  9104. (final-done-word (nth 4 ass))
  9105. (org-last-state (or this ""))
  9106. (completion-ignore-case t)
  9107. (member (member this org-todo-keywords-1))
  9108. (tail (cdr member))
  9109. (org-state (cond
  9110. ((eq arg 'right)
  9111. ;; Next state
  9112. (if this
  9113. (if tail (car tail) nil)
  9114. (car org-todo-keywords-1)))
  9115. ((eq arg 'left)
  9116. ;; Previous state
  9117. (unless (equal member org-todo-keywords-1)
  9118. (if this
  9119. (nth (- (length org-todo-keywords-1)
  9120. (length tail) 2)
  9121. org-todo-keywords-1)
  9122. (org-last org-todo-keywords-1))))
  9123. (arg
  9124. ;; User or caller requests a specific state.
  9125. (cond
  9126. ((equal arg "") nil)
  9127. ((eq arg 'none) nil)
  9128. ((eq arg 'done) (or done-word (car org-done-keywords)))
  9129. ((eq arg 'nextset)
  9130. (or (car (cdr (member head org-todo-heads)))
  9131. (car org-todo-heads)))
  9132. ((eq arg 'previousset)
  9133. (let ((org-todo-heads (reverse org-todo-heads)))
  9134. (or (car (cdr (member head org-todo-heads)))
  9135. (car org-todo-heads))))
  9136. ((car (member arg org-todo-keywords-1)))
  9137. ((stringp arg)
  9138. (user-error "State `%s' not valid in this file" arg))
  9139. ((nth (1- (prefix-numeric-value arg))
  9140. org-todo-keywords-1))))
  9141. ((and org-todo-key-trigger org-use-fast-todo-selection)
  9142. ;; Use fast selection.
  9143. (org-fast-todo-selection this))
  9144. ((null member) (or head (car org-todo-keywords-1)))
  9145. ((equal this final-done-word) nil) ;-> make empty
  9146. ((null tail) nil) ;-> first entry
  9147. ((memq interpret '(type priority))
  9148. (if (eq this-command last-command)
  9149. (car tail)
  9150. (if (> (length tail) 0)
  9151. (or done-word (car org-done-keywords))
  9152. nil)))
  9153. (t
  9154. (car tail))))
  9155. (org-state (or
  9156. (run-hook-with-args-until-success
  9157. 'org-todo-get-default-hook org-state org-last-state)
  9158. org-state))
  9159. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  9160. (change-plist (list :type 'todo-state-change :from this :to org-state
  9161. :position startpos))
  9162. dolog now-done-p)
  9163. (when org-blocker-hook
  9164. (let (org-blocked-by-checkboxes block-reason)
  9165. (setq org-last-todo-state-is-todo
  9166. (not (member this org-done-keywords)))
  9167. (unless (save-excursion
  9168. (save-match-data
  9169. (org-with-wide-buffer
  9170. (run-hook-with-args-until-failure
  9171. 'org-blocker-hook change-plist))))
  9172. (setq block-reason (if org-blocked-by-checkboxes
  9173. "contained checkboxes"
  9174. (format "\"%s\"" org-block-entry-blocking)))
  9175. (if (called-interactively-p 'interactive)
  9176. (user-error "TODO state change from %s to %s blocked (by %s)"
  9177. this org-state block-reason)
  9178. ;; Fail silently.
  9179. (message "TODO state change from %s to %s blocked (by %s)"
  9180. this org-state block-reason)
  9181. (throw 'exit nil)))))
  9182. (store-match-data match-data)
  9183. (replace-match next t t)
  9184. (cond ((and org-state (equal this org-state))
  9185. (message "TODO state was already %s" (org-trim next)))
  9186. ((not (pos-visible-in-window-p hl-pos))
  9187. (message "TODO state changed to %s" (org-trim next))))
  9188. (unless head
  9189. (setq head (org-get-todo-sequence-head org-state)
  9190. ass (assoc head org-todo-kwd-alist)
  9191. interpret (nth 1 ass)
  9192. done-word (nth 3 ass)
  9193. final-done-word (nth 4 ass)))
  9194. (when (memq arg '(nextset previousset))
  9195. (message "Keyword-Set %d/%d: %s"
  9196. (- (length org-todo-sets) -1
  9197. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  9198. (length org-todo-sets)
  9199. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  9200. (setq org-last-todo-state-is-todo
  9201. (not (member org-state org-done-keywords)))
  9202. (setq now-done-p (and (member org-state org-done-keywords)
  9203. (not (member this org-done-keywords))))
  9204. (and logging (org-local-logging logging))
  9205. (when (or (and (or org-todo-log-states org-log-done)
  9206. (not (eq org-inhibit-logging t))
  9207. (not (memq arg '(nextset previousset))))
  9208. force-log)
  9209. ;; We need to look at recording a time and note.
  9210. (setq dolog (or (if force-log 'note)
  9211. (nth 1 (assoc org-state org-todo-log-states))
  9212. (nth 2 (assoc this org-todo-log-states))))
  9213. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  9214. (setq dolog 'time))
  9215. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  9216. (and org-state
  9217. (member org-state org-not-done-keywords)
  9218. (not (member this org-not-done-keywords))))
  9219. ;; This is now a todo state and was not one before
  9220. ;; If there was a CLOSED time stamp, get rid of it.
  9221. (org-add-planning-info nil nil 'closed))
  9222. (when (and now-done-p org-log-done)
  9223. ;; It is now done, and it was not done before.
  9224. (org-add-planning-info 'closed (org-current-effective-time))
  9225. (when (and (not dolog) (eq 'note org-log-done))
  9226. (org-add-log-setup 'done org-state this 'note)))
  9227. (when (and org-state dolog)
  9228. ;; This is a non-nil state, and we need to log it.
  9229. (org-add-log-setup 'state org-state this dolog)))
  9230. ;; Fixup tag positioning.
  9231. (org-todo-trigger-tag-changes org-state)
  9232. (when org-auto-align-tags (org-align-tags))
  9233. (when org-provide-todo-statistics
  9234. (org-update-parent-todo-statistics))
  9235. (when (bound-and-true-p org-clock-out-when-done)
  9236. (org-clock-out-if-current))
  9237. (run-hooks 'org-after-todo-state-change-hook)
  9238. (when (and arg (not (member org-state org-done-keywords)))
  9239. (setq head (org-get-todo-sequence-head org-state)))
  9240. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  9241. ;; Do we need to trigger a repeat?
  9242. (when now-done-p
  9243. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  9244. ;; This is for the agenda, take a snapshot of the headline.
  9245. (save-match-data
  9246. (setq org-agenda-headline-snapshot-before-repeat
  9247. (org-get-heading))))
  9248. (org-auto-repeat-maybe org-state))
  9249. ;; Fixup cursor location if close to the keyword.
  9250. (when (and (outline-on-heading-p)
  9251. (not (bolp))
  9252. (save-excursion (beginning-of-line 1)
  9253. (looking-at org-todo-line-regexp))
  9254. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  9255. (goto-char (or (match-end 2) (match-end 1)))
  9256. (and (looking-at " ")
  9257. (not (looking-at " *:"))
  9258. (just-one-space)))
  9259. (when org-trigger-hook
  9260. (save-excursion
  9261. (run-hook-with-args 'org-trigger-hook change-plist)))
  9262. (when commentp (org-toggle-comment))))))))
  9263. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  9264. "Block turning an entry into a TODO, using the hierarchy.
  9265. This checks whether the current task should be blocked from state
  9266. changes. Such blocking occurs when:
  9267. 1. The task has children which are not all in a completed state.
  9268. 2. A task has a parent with the property :ORDERED:, and there
  9269. are siblings prior to the current task with incomplete
  9270. status.
  9271. 3. The parent of the task is blocked because it has siblings that should
  9272. be done first, or is child of a block grandparent TODO entry."
  9273. (if (not org-enforce-todo-dependencies)
  9274. t ; if locally turned off don't block
  9275. (catch 'dont-block
  9276. ;; If this is not a todo state change, or if this entry is already DONE,
  9277. ;; do not block
  9278. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9279. (member (plist-get change-plist :from)
  9280. (cons 'done org-done-keywords))
  9281. (member (plist-get change-plist :to)
  9282. (cons 'todo org-not-done-keywords))
  9283. (not (plist-get change-plist :to)))
  9284. (throw 'dont-block t))
  9285. ;; If this task has children, and any are undone, it's blocked
  9286. (save-excursion
  9287. (org-back-to-heading t)
  9288. (let ((this-level (funcall outline-level)))
  9289. (outline-next-heading)
  9290. (let ((child-level (funcall outline-level)))
  9291. (while (and (not (eobp))
  9292. (> child-level this-level))
  9293. ;; this todo has children, check whether they are all
  9294. ;; completed
  9295. (when (and (not (org-entry-is-done-p))
  9296. (org-entry-is-todo-p))
  9297. (setq org-block-entry-blocking (org-get-heading))
  9298. (throw 'dont-block nil))
  9299. (outline-next-heading)
  9300. (setq child-level (funcall outline-level))))))
  9301. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  9302. ;; any previous siblings are undone, it's blocked
  9303. (save-excursion
  9304. (org-back-to-heading t)
  9305. (let* ((pos (point))
  9306. (parent-pos (and (org-up-heading-safe) (point)))
  9307. (case-fold-search nil))
  9308. (unless parent-pos (throw 'dont-block t)) ; no parent
  9309. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9310. (forward-line 1)
  9311. (re-search-forward org-not-done-heading-regexp pos t))
  9312. (setq org-block-entry-blocking (match-string 0))
  9313. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  9314. ;; Search further up the hierarchy, to see if an ancestor is blocked
  9315. (while t
  9316. (goto-char parent-pos)
  9317. (unless (looking-at org-not-done-heading-regexp)
  9318. (throw 'dont-block t)) ; do not block, parent is not a TODO
  9319. (setq pos (point))
  9320. (setq parent-pos (and (org-up-heading-safe) (point)))
  9321. (unless parent-pos (throw 'dont-block t)) ; no parent
  9322. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9323. (forward-line 1)
  9324. (re-search-forward org-not-done-heading-regexp pos t)
  9325. (setq org-block-entry-blocking (org-get-heading)))
  9326. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  9327. (defcustom org-track-ordered-property-with-tag nil
  9328. "Should the ORDERED property also be shown as a tag?
  9329. The ORDERED property decides if an entry should require subtasks to be
  9330. completed in sequence. Since a property is not very visible, setting
  9331. this option means that toggling the ORDERED property with the command
  9332. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  9333. not relevant for the behavior, but it makes things more visible.
  9334. Note that toggling the tag with tags commands will not change the property
  9335. and therefore not influence behavior!
  9336. This can be t, meaning the tag ORDERED should be used. It can also be a
  9337. string to select a different tag for this task."
  9338. :group 'org-todo
  9339. :type '(choice
  9340. (const :tag "No tracking" nil)
  9341. (const :tag "Track with ORDERED tag" t)
  9342. (string :tag "Use other tag")))
  9343. (defun org-toggle-ordered-property ()
  9344. "Toggle the ORDERED property of the current entry.
  9345. For better visibility, you can track the value of this property with a tag.
  9346. See variable `org-track-ordered-property-with-tag'."
  9347. (interactive)
  9348. (let* ((t1 org-track-ordered-property-with-tag)
  9349. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  9350. (save-excursion
  9351. (org-back-to-heading)
  9352. (if (org-entry-get nil "ORDERED")
  9353. (progn
  9354. (org-delete-property "ORDERED")
  9355. (and tag (org-toggle-tag tag 'off))
  9356. (message "Subtasks can be completed in arbitrary order"))
  9357. (org-entry-put nil "ORDERED" "t")
  9358. (and tag (org-toggle-tag tag 'on))
  9359. (message "Subtasks must be completed in sequence")))))
  9360. (defun org-block-todo-from-checkboxes (change-plist)
  9361. "Block turning an entry into a TODO, using checkboxes.
  9362. This checks whether the current task should be blocked from state
  9363. changes because there are unchecked boxes in this entry."
  9364. (if (not org-enforce-todo-checkbox-dependencies)
  9365. t ; if locally turned off don't block
  9366. (catch 'dont-block
  9367. ;; If this is not a todo state change, or if this entry is already DONE,
  9368. ;; do not block
  9369. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9370. (member (plist-get change-plist :from)
  9371. (cons 'done org-done-keywords))
  9372. (member (plist-get change-plist :to)
  9373. (cons 'todo org-not-done-keywords))
  9374. (not (plist-get change-plist :to)))
  9375. (throw 'dont-block t))
  9376. ;; If this task has checkboxes that are not checked, it's blocked
  9377. (save-excursion
  9378. (org-back-to-heading t)
  9379. (let ((beg (point)) end)
  9380. (outline-next-heading)
  9381. (setq end (point))
  9382. (goto-char beg)
  9383. (when (org-list-search-forward
  9384. (concat (org-item-beginning-re)
  9385. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  9386. "\\[[- ]\\]")
  9387. end t)
  9388. (when (boundp 'org-blocked-by-checkboxes)
  9389. (setq org-blocked-by-checkboxes t))
  9390. (throw 'dont-block nil))))
  9391. t))) ; do not block
  9392. (defun org-entry-blocked-p ()
  9393. "Non-nil if entry at point is blocked."
  9394. (and (not (org-entry-get nil "NOBLOCKING"))
  9395. (member (org-entry-get nil "TODO") org-not-done-keywords)
  9396. (not (run-hook-with-args-until-failure
  9397. 'org-blocker-hook
  9398. (list :type 'todo-state-change
  9399. :position (point)
  9400. :from 'todo
  9401. :to 'done)))))
  9402. (defun org-update-statistics-cookies (all)
  9403. "Update the statistics cookie, either from TODO or from checkboxes.
  9404. This should be called with the cursor in a line with a statistics
  9405. cookie. When called with a \\[universal-argument] prefix, update
  9406. all statistics cookies in the buffer."
  9407. (interactive "P")
  9408. (if all
  9409. (progn
  9410. (org-update-checkbox-count 'all)
  9411. (org-map-entries 'org-update-parent-todo-statistics))
  9412. (if (not (org-at-heading-p))
  9413. (org-update-checkbox-count)
  9414. (let ((pos (point-marker))
  9415. end l1 l2)
  9416. (ignore-errors (org-back-to-heading t))
  9417. (if (not (org-at-heading-p))
  9418. (org-update-checkbox-count)
  9419. (setq l1 (org-outline-level))
  9420. (setq end (save-excursion
  9421. (outline-next-heading)
  9422. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  9423. (point)))
  9424. (if (and (save-excursion
  9425. (re-search-forward
  9426. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  9427. (not (save-excursion (re-search-forward
  9428. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  9429. (org-update-checkbox-count)
  9430. (if (and l2 (> l2 l1))
  9431. (progn
  9432. (goto-char end)
  9433. (org-update-parent-todo-statistics))
  9434. (goto-char pos)
  9435. (beginning-of-line 1)
  9436. (while (re-search-forward
  9437. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  9438. (point-at-eol) t)
  9439. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  9440. (goto-char pos)
  9441. (move-marker pos nil)))))
  9442. (defvar org-entry-property-inherited-from) ;; defined below
  9443. (defun org-update-parent-todo-statistics ()
  9444. "Update any statistics cookie in the parent of the current headline.
  9445. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  9446. the entire subtree and this will travel up the hierarchy and update
  9447. statistics everywhere."
  9448. (let* ((prop (save-excursion (org-up-heading-safe)
  9449. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  9450. (recursive (or (not org-hierarchical-todo-statistics)
  9451. (and prop (string-match "\\<recursive\\>" prop))))
  9452. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  9453. 0))
  9454. (first t)
  9455. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  9456. level ltoggle l1 new ndel
  9457. (cnt-all 0) (cnt-done 0) is-percent kwd
  9458. checkbox-beg cookie-present)
  9459. (catch 'exit
  9460. (save-excursion
  9461. (beginning-of-line 1)
  9462. (setq ltoggle (funcall outline-level))
  9463. ;; Three situations are to consider:
  9464. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  9465. ;; to the top-level ancestor on the headline;
  9466. ;; 2. If parent has "recursive" property, repeat up to the
  9467. ;; headline setting that property, taking inheritance into
  9468. ;; account;
  9469. ;; 3. Else, move up to direct parent and proceed only once.
  9470. (while (and (setq level (org-up-heading-safe))
  9471. (or recursive first)
  9472. (>= (point) lim))
  9473. (setq first nil cookie-present nil)
  9474. (unless (and level
  9475. (not (string-match
  9476. "\\<checkbox\\>"
  9477. (downcase (or (org-entry-get nil "COOKIE_DATA")
  9478. "")))))
  9479. (throw 'exit nil))
  9480. (while (re-search-forward box-re (point-at-eol) t)
  9481. (setq cnt-all 0 cnt-done 0 cookie-present t)
  9482. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  9483. (save-match-data
  9484. (unless (outline-next-heading) (throw 'exit nil))
  9485. (while (and (looking-at org-complex-heading-regexp)
  9486. (> (setq l1 (length (match-string 1))) level))
  9487. (setq kwd (and (or recursive (= l1 ltoggle))
  9488. (match-string 2)))
  9489. (if (or (eq org-provide-todo-statistics 'all-headlines)
  9490. (and (eq org-provide-todo-statistics t)
  9491. (or (member kwd org-done-keywords)))
  9492. (and (listp org-provide-todo-statistics)
  9493. (stringp (car org-provide-todo-statistics))
  9494. (or (member kwd org-provide-todo-statistics)
  9495. (member kwd org-done-keywords)))
  9496. (and (listp org-provide-todo-statistics)
  9497. (listp (car org-provide-todo-statistics))
  9498. (or (member kwd (car org-provide-todo-statistics))
  9499. (and (member kwd org-done-keywords)
  9500. (member kwd (cadr org-provide-todo-statistics))))))
  9501. (setq cnt-all (1+ cnt-all))
  9502. (and (eq org-provide-todo-statistics t)
  9503. kwd
  9504. (setq cnt-all (1+ cnt-all))))
  9505. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  9506. (member kwd org-done-keywords))
  9507. (and (listp org-provide-todo-statistics)
  9508. (listp (car org-provide-todo-statistics))
  9509. (member kwd org-done-keywords)
  9510. (member kwd (cadr org-provide-todo-statistics)))
  9511. (and (listp org-provide-todo-statistics)
  9512. (stringp (car org-provide-todo-statistics))
  9513. (member kwd org-done-keywords)))
  9514. (setq cnt-done (1+ cnt-done)))
  9515. (outline-next-heading)))
  9516. (setq new
  9517. (if is-percent
  9518. (format "[%d%%]" (floor (* 100.0 cnt-done)
  9519. (max 1 cnt-all)))
  9520. (format "[%d/%d]" cnt-done cnt-all))
  9521. ndel (- (match-end 0) checkbox-beg))
  9522. (goto-char checkbox-beg)
  9523. (insert new)
  9524. (delete-region (point) (+ (point) ndel))
  9525. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  9526. (when cookie-present
  9527. (run-hook-with-args 'org-after-todo-statistics-hook
  9528. cnt-done (- cnt-all cnt-done))))))
  9529. (run-hooks 'org-todo-statistics-hook)))
  9530. (defvar org-after-todo-statistics-hook nil
  9531. "Hook that is called after a TODO statistics cookie has been updated.
  9532. Each function is called with two arguments: the number of not-done entries
  9533. and the number of done entries.
  9534. For example, the following function, when added to this hook, will switch
  9535. an entry to DONE when all children are done, and back to TODO when new
  9536. entries are set to a TODO status. Note that this hook is only called
  9537. when there is a statistics cookie in the headline!
  9538. (defun org-summary-todo (n-done n-not-done)
  9539. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9540. (let (org-log-done org-log-states) ; turn off logging
  9541. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  9542. ")
  9543. (defvar org-todo-statistics-hook nil
  9544. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9545. This hook runs even if there is no statistics cookie present, in which case
  9546. `org-after-todo-statistics-hook' would not run.")
  9547. (defun org-todo-trigger-tag-changes (state)
  9548. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9549. (let ((l org-todo-state-tags-triggers)
  9550. changes)
  9551. (when (or (not state) (equal state ""))
  9552. (setq changes (append changes (cdr (assoc "" l)))))
  9553. (when (and (stringp state) (> (length state) 0))
  9554. (setq changes (append changes (cdr (assoc state l)))))
  9555. (when (member state org-not-done-keywords)
  9556. (setq changes (append changes (cdr (assq 'todo l)))))
  9557. (when (member state org-done-keywords)
  9558. (setq changes (append changes (cdr (assq 'done l)))))
  9559. (dolist (c changes)
  9560. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9561. (defun org-local-logging (value)
  9562. "Get logging settings from a property VALUE."
  9563. ;; Directly set the variables, they are already local.
  9564. (setq org-log-done nil
  9565. org-log-repeat nil
  9566. org-todo-log-states nil)
  9567. (dolist (w (split-string value))
  9568. (let (a)
  9569. (cond
  9570. ((setq a (assoc w org-startup-options))
  9571. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9572. (set (nth 1 a) (nth 2 a))))
  9573. ((setq a (org-extract-log-state-settings w))
  9574. (and (member (car a) org-todo-keywords-1)
  9575. (push a org-todo-log-states)))))))
  9576. (defun org-get-todo-sequence-head (kwd)
  9577. "Return the head of the TODO sequence to which KWD belongs.
  9578. If KWD is not set, check if there is a text property remembering the
  9579. right sequence."
  9580. (let (p)
  9581. (cond
  9582. ((not kwd)
  9583. (or (get-text-property (point-at-bol) 'org-todo-head)
  9584. (progn
  9585. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9586. nil (point-at-eol)))
  9587. (get-text-property p 'org-todo-head))))
  9588. ((not (member kwd org-todo-keywords-1))
  9589. (car org-todo-keywords-1))
  9590. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9591. (defun org-fast-todo-selection (&optional current-state)
  9592. "Fast TODO keyword selection with single keys.
  9593. Returns the new TODO keyword, or nil if no state change should occur.
  9594. When CURRENT-STATE is given and selection letters are not unique globally,
  9595. prefer a state in the current sequence over on in another sequence."
  9596. (let* ((fulltable org-todo-key-alist)
  9597. (head (org-get-todo-sequence-head current-state))
  9598. (done-keywords org-done-keywords) ;; needed for the faces.
  9599. (maxlen (apply 'max (mapcar
  9600. (lambda (x)
  9601. (if (stringp (car x)) (string-width (car x)) 0))
  9602. fulltable)))
  9603. (expert (equal org-use-fast-todo-selection 'expert))
  9604. (prompt "")
  9605. (fwidth (+ maxlen 3 1 3))
  9606. (ncol (/ (- (window-width) 4) fwidth))
  9607. tg cnt e c tbl subtable
  9608. groups ingroup in-current-sequence)
  9609. (save-excursion
  9610. (save-window-excursion
  9611. (if expert
  9612. (set-buffer (get-buffer-create " *Org todo*"))
  9613. (delete-other-windows)
  9614. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9615. (org-switch-to-buffer-other-window " *Org todo*"))
  9616. (erase-buffer)
  9617. (setq-local org-done-keywords done-keywords)
  9618. (setq tbl fulltable cnt 0)
  9619. (while (setq e (pop tbl))
  9620. (cond
  9621. ((equal e '(:startgroup))
  9622. (push '() groups) (setq ingroup t)
  9623. (unless (= cnt 0)
  9624. (setq cnt 0)
  9625. (insert "\n"))
  9626. (setq prompt (concat prompt "{"))
  9627. (insert "{ "))
  9628. ((equal e '(:endgroup))
  9629. (setq ingroup nil cnt 0 in-current-sequence nil)
  9630. (setq prompt (concat prompt "}"))
  9631. (insert "}\n"))
  9632. ((equal e '(:newline))
  9633. (unless (= cnt 0)
  9634. (setq cnt 0)
  9635. (insert "\n")
  9636. (setq e (car tbl))
  9637. (while (equal (car tbl) '(:newline))
  9638. (insert "\n")
  9639. (setq tbl (cdr tbl)))))
  9640. (t
  9641. (setq tg (car e) c (cdr e))
  9642. (if (equal tg head) (setq in-current-sequence t))
  9643. (when ingroup (push tg (car groups)))
  9644. (when in-current-sequence (push e subtable))
  9645. (setq tg (org-add-props tg nil 'face
  9646. (org-get-todo-face tg)))
  9647. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9648. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9649. (insert "[" c "] " tg (make-string
  9650. (- fwidth 4 (length tg)) ?\ ))
  9651. (when (and (= (setq cnt (1+ cnt)) ncol)
  9652. ;; Avoid lines with just a closing delimiter.
  9653. (not (equal (car tbl) '(:endgroup))))
  9654. (insert "\n")
  9655. (when ingroup (insert " "))
  9656. (setq cnt 0)))))
  9657. (insert "\n")
  9658. (goto-char (point-min))
  9659. (unless expert (org-fit-window-to-buffer))
  9660. (message (concat "[a-z..]:Set [SPC]:clear"
  9661. (if expert (concat "\n" prompt) "")))
  9662. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9663. (setq subtable (nreverse subtable))
  9664. (cond
  9665. ((or (= c ?\C-g)
  9666. (and (= c ?q) (not (rassoc c fulltable))))
  9667. (setq quit-flag t))
  9668. ((= c ?\ ) nil)
  9669. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9670. tg (car e))
  9671. tg)
  9672. (t (setq quit-flag t)))))))
  9673. (defun org-entry-is-todo-p ()
  9674. (member (org-get-todo-state) org-not-done-keywords))
  9675. (defun org-entry-is-done-p ()
  9676. (member (org-get-todo-state) org-done-keywords))
  9677. (defun org-get-todo-state ()
  9678. "Return the TODO keyword of the current subtree."
  9679. (save-excursion
  9680. (org-back-to-heading t)
  9681. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9682. (match-end 2)
  9683. (match-string 2))))
  9684. (defun org-at-date-range-p (&optional inactive-ok)
  9685. "Non-nil if point is inside a date range.
  9686. When optional argument INACTIVE-OK is non-nil, also consider
  9687. inactive time ranges.
  9688. When this function returns a non-nil value, match data is set
  9689. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9690. on INACTIVE-OK."
  9691. (interactive)
  9692. (save-excursion
  9693. (catch 'exit
  9694. (let ((pos (point)))
  9695. (skip-chars-backward "^[<\r\n")
  9696. (skip-chars-backward "<[")
  9697. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9698. (>= (match-end 0) pos)
  9699. (throw 'exit t))
  9700. (skip-chars-backward "^<[\r\n")
  9701. (skip-chars-backward "<[")
  9702. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9703. (>= (match-end 0) pos)
  9704. (throw 'exit t)))
  9705. nil)))
  9706. (defun org-get-repeat (&optional timestamp)
  9707. "Check if there is a time-stamp with repeater in this entry.
  9708. Return the repeater, as a string, or nil. Also return nil when
  9709. this function is called before first heading.
  9710. When optional argument TIMESTAMP is a string, extract the
  9711. repeater from there instead."
  9712. (save-match-data
  9713. (cond (timestamp
  9714. (and (string-match org-repeat-re timestamp)
  9715. (match-string-no-properties 1 timestamp)))
  9716. ((org-before-first-heading-p) nil)
  9717. (t
  9718. (save-excursion
  9719. (org-back-to-heading t)
  9720. (let ((end (org-entry-end-position)))
  9721. (catch :repeat
  9722. (while (re-search-forward org-repeat-re end t)
  9723. (when (save-match-data (org-at-timestamp-p 'agenda))
  9724. (throw :repeat (match-string-no-properties 1)))))))))))
  9725. (defvar org-last-changed-timestamp)
  9726. (defvar org-last-inserted-timestamp)
  9727. (defvar org-log-post-message)
  9728. (defvar org-log-note-purpose)
  9729. (defvar org-log-note-how nil)
  9730. (defvar org-log-note-extra)
  9731. (defun org-auto-repeat-maybe (done-word)
  9732. "Check if the current headline contains a repeated time-stamp.
  9733. If yes, set TODO state back to what it was and change the base date
  9734. of repeating deadline/scheduled time stamps to new date.
  9735. This function is run automatically after each state change to a DONE state."
  9736. (let* ((repeat (org-get-repeat))
  9737. (aa (assoc org-last-state org-todo-kwd-alist))
  9738. (interpret (nth 1 aa))
  9739. (head (nth 2 aa))
  9740. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9741. (msg "Entry repeats: ")
  9742. (org-log-done nil)
  9743. (org-todo-log-states nil)
  9744. (end (copy-marker (org-entry-end-position))))
  9745. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9746. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9747. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9748. (and (stringp org-todo-repeat-to-state)
  9749. org-todo-repeat-to-state)
  9750. (and org-todo-repeat-to-state org-last-state))))
  9751. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9752. to-state)
  9753. ((eq interpret 'type) org-last-state)
  9754. (head)
  9755. (t 'none))))
  9756. (org-back-to-heading t)
  9757. (org-add-planning-info nil nil 'closed)
  9758. ;; When `org-log-repeat' is non-nil or entry contains
  9759. ;; a clock, set LAST_REPEAT property.
  9760. (when (or org-log-repeat
  9761. (catch :clock
  9762. (save-excursion
  9763. (while (re-search-forward org-clock-line-re end t)
  9764. (when (org-at-clock-log-p) (throw :clock t))))))
  9765. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9766. (org-time-stamp-format t t))))
  9767. (when org-log-repeat
  9768. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  9769. (memq 'org-add-log-note post-command-hook))
  9770. ;; We are already setup for some record.
  9771. (when (eq org-log-repeat 'note)
  9772. ;; Make sure we take a note, not only a time stamp.
  9773. (setq org-log-note-how 'note))
  9774. ;; Set up for taking a record.
  9775. (org-add-log-setup 'state
  9776. (or done-word (car org-done-keywords))
  9777. org-last-state
  9778. org-log-repeat)))
  9779. ;; Time-stamps without a repeater are usually skipped. However,
  9780. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9781. ;; longer relevant.
  9782. (save-excursion
  9783. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9784. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9785. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9786. ;; Update every time-stamp with a repeater in the entry.
  9787. (let ((planning-re (regexp-opt
  9788. (list org-scheduled-string org-deadline-string))))
  9789. (while (re-search-forward org-repeat-re end t)
  9790. (let* ((ts (match-string 0))
  9791. (type (if (not (org-at-planning-p)) "Plain:"
  9792. (save-excursion
  9793. (re-search-backward
  9794. planning-re (line-beginning-position) t)
  9795. (match-string 0)))))
  9796. (when (and (org-at-timestamp-p 'agenda)
  9797. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9798. (let ((n (string-to-number (match-string 2 ts)))
  9799. (what (match-string 3 ts)))
  9800. (when (equal what "w") (setq n (* n 7) what "d"))
  9801. (when (and (equal what "h")
  9802. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9803. ts)))
  9804. (user-error
  9805. "Cannot repeat in %d hour(s) because no hour has been set"
  9806. n))
  9807. ;; Preparation, see if we need to modify the start
  9808. ;; date for the change.
  9809. (when (match-end 1)
  9810. (let ((time (save-match-data (org-time-string-to-time ts)))
  9811. (repeater-type (match-string 1 ts)))
  9812. (cond
  9813. ((equal "." repeater-type)
  9814. ;; Shift starting date to today.
  9815. (org-timestamp-change (- (org-today) (time-to-days time))
  9816. 'day))
  9817. ((equal "+" repeater-type)
  9818. (let ((nshiftmax 10)
  9819. (nshift 0))
  9820. (while (or (= nshift 0)
  9821. (not (org-time-less-p nil time)))
  9822. (when (= nshiftmax (cl-incf nshift))
  9823. (or (y-or-n-p
  9824. (format "%d repeater intervals were not \
  9825. enough to shift date past today. Continue? "
  9826. nshift))
  9827. (user-error "Abort")))
  9828. (org-timestamp-change n (cdr (assoc what whata)))
  9829. (org-in-regexp org-ts-regexp3)
  9830. (setq ts (match-string 1))
  9831. (setq time
  9832. (save-match-data
  9833. (org-time-string-to-time ts)))))
  9834. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9835. ;; Rematch, so that we have everything in place
  9836. ;; for the real shift.
  9837. (org-in-regexp org-ts-regexp3)
  9838. (setq ts (match-string 1))
  9839. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9840. ts)))))
  9841. (save-excursion
  9842. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9843. (setq msg
  9844. (concat msg type " " org-last-changed-timestamp " ")))))))
  9845. (run-hooks 'org-todo-repeat-hook)
  9846. (setq org-log-post-message msg)
  9847. (message msg))))
  9848. (defun org-show-todo-tree (arg)
  9849. "Make a compact tree which shows all headlines marked with TODO.
  9850. The tree will show the lines where the regexp matches, and all higher
  9851. headlines above the match.
  9852. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9853. With a numeric prefix N, construct a sparse tree for the Nth element
  9854. of `org-todo-keywords-1'."
  9855. (interactive "P")
  9856. (let ((case-fold-search nil)
  9857. (kwd-re
  9858. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9859. ((equal arg '(4))
  9860. (let ((kwd
  9861. (completing-read "Keyword (or KWD1|KWD2|...): "
  9862. (mapcar #'list org-todo-keywords-1))))
  9863. (concat "\\("
  9864. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9865. "\\)\\>")))
  9866. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9867. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9868. org-todo-keywords-1)))
  9869. (t (user-error "Invalid prefix argument: %s" arg)))))
  9870. (message "%d TODO entries found"
  9871. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9872. (defun org--deadline-or-schedule (arg type time)
  9873. "Insert DEADLINE or SCHEDULE information in current entry.
  9874. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9875. `org-schedule' for information about ARG and TIME arguments."
  9876. (let* ((deadline? (eq type 'deadline))
  9877. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9878. (log (if deadline? org-log-redeadline org-log-reschedule))
  9879. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9880. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9881. ;; Save repeater cookie from either TIME or current scheduled
  9882. ;; time stamp. We are going to insert it back at the end of
  9883. ;; the process.
  9884. (repeater (or (and (org-string-nw-p time)
  9885. ;; We use `org-repeat-re' because we need
  9886. ;; to tell the difference between a real
  9887. ;; repeater and a time delta, e.g. "+2d".
  9888. (string-match org-repeat-re time)
  9889. (match-string 1 time))
  9890. (and (org-string-nw-p old-date)
  9891. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9892. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9893. old-date)
  9894. (match-string 1 old-date)))))
  9895. (pcase arg
  9896. (`(4)
  9897. (if (not old-date)
  9898. (message (if deadline? "Entry had no deadline to remove"
  9899. "Entry was not scheduled"))
  9900. (when (and old-date log)
  9901. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9902. nil old-date log))
  9903. (org-remove-timestamp-with-keyword keyword)
  9904. (message (if deadline? "Entry no longer has a deadline."
  9905. "Entry is no longer scheduled."))))
  9906. (`(16)
  9907. (save-excursion
  9908. (org-back-to-heading t)
  9909. (let ((regexp (if deadline? org-deadline-time-regexp
  9910. org-scheduled-time-regexp)))
  9911. (if (not (re-search-forward regexp (line-end-position 2) t))
  9912. (user-error (if deadline? "No deadline information to update"
  9913. "No scheduled information to update"))
  9914. (let* ((rpl0 (match-string 1))
  9915. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9916. (msg (if deadline? "Warn starting from" "Delay until")))
  9917. (replace-match
  9918. (concat keyword
  9919. " <" rpl
  9920. (format " -%dd"
  9921. (abs (- (time-to-days
  9922. (save-match-data
  9923. (org-read-date
  9924. nil t nil msg old-date-time)))
  9925. (time-to-days old-date-time))))
  9926. ">") t t))))))
  9927. (_
  9928. (org-add-planning-info type time 'closed)
  9929. (when (and old-date
  9930. log
  9931. (not (equal old-date org-last-inserted-timestamp)))
  9932. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9933. org-last-inserted-timestamp
  9934. old-date
  9935. log))
  9936. (when repeater
  9937. (save-excursion
  9938. (org-back-to-heading t)
  9939. (when (re-search-forward
  9940. (concat keyword " " org-last-inserted-timestamp)
  9941. (line-end-position 2)
  9942. t)
  9943. (goto-char (1- (match-end 0)))
  9944. (insert " " repeater)
  9945. (setq org-last-inserted-timestamp
  9946. (concat (substring org-last-inserted-timestamp 0 -1)
  9947. " " repeater
  9948. (substring org-last-inserted-timestamp -1))))))
  9949. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9950. org-last-inserted-timestamp)))))
  9951. (defun org-deadline (arg &optional time)
  9952. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  9953. With one universal prefix argument, remove any deadline from the item.
  9954. With two universal prefix arguments, prompt for a warning delay.
  9955. With argument TIME, set the deadline at the corresponding date. TIME
  9956. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9957. (interactive "P")
  9958. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9959. (org-map-entries
  9960. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9961. nil
  9962. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9963. 'region-start-level
  9964. 'region)
  9965. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9966. (org--deadline-or-schedule arg 'deadline time)))
  9967. (defun org-schedule (arg &optional time)
  9968. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  9969. With one universal prefix argument, remove any scheduling date from the item.
  9970. With two universal prefix arguments, prompt for a delay cookie.
  9971. With argument TIME, scheduled at the corresponding date. TIME can
  9972. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9973. (interactive "P")
  9974. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9975. (org-map-entries
  9976. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9977. nil
  9978. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9979. 'region-start-level
  9980. 'region)
  9981. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9982. (org--deadline-or-schedule arg 'scheduled time)))
  9983. (defun org-get-scheduled-time (pom &optional inherit)
  9984. "Get the scheduled time as a time tuple, of a format suitable
  9985. for calling org-schedule with, or if there is no scheduling,
  9986. returns nil."
  9987. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9988. (when time
  9989. (org-time-string-to-time time))))
  9990. (defun org-get-deadline-time (pom &optional inherit)
  9991. "Get the deadline as a time tuple, of a format suitable for
  9992. calling org-deadline with, or if there is no scheduling, returns
  9993. nil."
  9994. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9995. (when time
  9996. (org-time-string-to-time time))))
  9997. (defun org-remove-timestamp-with-keyword (keyword)
  9998. "Remove all time stamps with KEYWORD in the current entry."
  9999. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  10000. beg)
  10001. (save-excursion
  10002. (org-back-to-heading t)
  10003. (setq beg (point))
  10004. (outline-next-heading)
  10005. (while (re-search-backward re beg t)
  10006. (replace-match "")
  10007. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  10008. (equal (char-before) ?\ ))
  10009. (backward-delete-char 1)
  10010. (when (string-match "^[ \t]*$" (buffer-substring
  10011. (point-at-bol) (point-at-eol)))
  10012. (delete-region (point-at-bol)
  10013. (min (point-max) (1+ (point-at-eol))))))))))
  10014. (defvar org-time-was-given) ; dynamically scoped parameter
  10015. (defvar org-end-time-was-given) ; dynamically scoped parameter
  10016. (defun org-at-planning-p ()
  10017. "Non-nil when point is on a planning info line."
  10018. ;; This is as accurate and faster than `org-element-at-point' since
  10019. ;; planning info location is fixed in the section.
  10020. (org-with-wide-buffer
  10021. (beginning-of-line)
  10022. (and (looking-at-p org-planning-line-re)
  10023. (eq (point)
  10024. (ignore-errors
  10025. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  10026. (org-back-to-heading t)
  10027. (org-with-limited-levels (org-back-to-heading t)))
  10028. (line-beginning-position 2))))))
  10029. (defun org-add-planning-info (what &optional time &rest remove)
  10030. "Insert new timestamp with keyword in the planning line.
  10031. WHAT indicates what kind of time stamp to add. It is a symbol
  10032. among `closed', `deadline', `scheduled' and nil. TIME indicates
  10033. the time to use. If none is given, the user is prompted for
  10034. a date. REMOVE indicates what kind of entries to remove. An old
  10035. WHAT entry will also be removed."
  10036. (let (org-time-was-given org-end-time-was-given default-time default-input)
  10037. (catch 'exit
  10038. (when (and (memq what '(scheduled deadline))
  10039. (or (not time)
  10040. (and (stringp time)
  10041. (string-match "^[-+]+[0-9]" time))))
  10042. ;; Try to get a default date/time from existing timestamp
  10043. (save-excursion
  10044. (org-back-to-heading t)
  10045. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  10046. (when (re-search-forward (if (eq what 'scheduled)
  10047. org-scheduled-time-regexp
  10048. org-deadline-time-regexp)
  10049. end t)
  10050. (setq ts (match-string 1)
  10051. default-time (org-time-string-to-time ts)
  10052. default-input (and ts (org-get-compact-tod ts)))))))
  10053. (when what
  10054. (setq time
  10055. (if (stringp time)
  10056. ;; This is a string (relative or absolute), set
  10057. ;; proper date.
  10058. (apply #'encode-time
  10059. (org-read-date-analyze
  10060. time default-time (decode-time default-time)))
  10061. ;; If necessary, get the time from the user
  10062. (or time (org-read-date nil 'to-time nil
  10063. (cl-case what
  10064. (deadline "DEADLINE")
  10065. (scheduled "SCHEDULED")
  10066. (otherwise nil))
  10067. default-time default-input)))))
  10068. (org-with-wide-buffer
  10069. (org-back-to-heading t)
  10070. (forward-line)
  10071. (unless (bolp) (insert "\n"))
  10072. (cond ((looking-at-p org-planning-line-re)
  10073. ;; Move to current indentation.
  10074. (skip-chars-forward " \t")
  10075. ;; Check if we have to remove something.
  10076. (dolist (type (if what (cons what remove) remove))
  10077. (save-excursion
  10078. (when (re-search-forward
  10079. (cl-case type
  10080. (closed org-closed-time-regexp)
  10081. (deadline org-deadline-time-regexp)
  10082. (scheduled org-scheduled-time-regexp)
  10083. (otherwise
  10084. (error "Invalid planning type: %s" type)))
  10085. (line-end-position) t)
  10086. ;; Delete until next keyword or end of line.
  10087. (delete-region
  10088. (match-beginning 0)
  10089. (if (re-search-forward org-keyword-time-not-clock-regexp
  10090. (line-end-position)
  10091. t)
  10092. (match-beginning 0)
  10093. (line-end-position))))))
  10094. ;; If there is nothing more to add and no more keyword
  10095. ;; is left, remove the line completely.
  10096. (if (and (looking-at-p "[ \t]*$") (not what))
  10097. (delete-region (line-beginning-position)
  10098. (line-beginning-position 2))
  10099. ;; If we removed last keyword, do not leave trailing
  10100. ;; white space at the end of line.
  10101. (let ((p (point)))
  10102. (save-excursion
  10103. (end-of-line)
  10104. (unless (= (skip-chars-backward " \t" p) 0)
  10105. (delete-region (point) (line-end-position)))))))
  10106. ((not what) (throw 'exit nil)) ; Nothing to do.
  10107. (t (insert-before-markers "\n")
  10108. (backward-char 1)
  10109. (when org-adapt-indentation
  10110. (indent-to-column (1+ (org-outline-level))))))
  10111. (when what
  10112. ;; Insert planning keyword.
  10113. (insert (cl-case what
  10114. (closed org-closed-string)
  10115. (deadline org-deadline-string)
  10116. (scheduled org-scheduled-string)
  10117. (otherwise (error "Invalid planning type: %s" what)))
  10118. " ")
  10119. ;; Insert associated timestamp.
  10120. (let ((ts (org-insert-time-stamp
  10121. time
  10122. (or org-time-was-given
  10123. (and (eq what 'closed) org-log-done-with-time))
  10124. (eq what 'closed)
  10125. nil nil (list org-end-time-was-given))))
  10126. (unless (eolp) (insert " "))
  10127. ts))))))
  10128. (defvar org-log-note-marker (make-marker)
  10129. "Marker pointing at the entry where the note is to be inserted.")
  10130. (defvar org-log-note-purpose nil)
  10131. (defvar org-log-note-state nil)
  10132. (defvar org-log-note-previous-state nil)
  10133. (defvar org-log-note-extra nil)
  10134. (defvar org-log-note-window-configuration nil)
  10135. (defvar org-log-note-return-to (make-marker))
  10136. (defvar org-log-note-effective-time nil
  10137. "Remembered current time so that dynamically scoped
  10138. `org-extend-today-until' affects timestamps in state change log")
  10139. (defvar org-log-post-message nil
  10140. "Message to be displayed after a log note has been stored.
  10141. The auto-repeater uses this.")
  10142. (defun org-add-note ()
  10143. "Add a note to the current entry.
  10144. This is done in the same way as adding a state change note."
  10145. (interactive)
  10146. (org-add-log-setup 'note))
  10147. (defun org-log-beginning (&optional create)
  10148. "Return expected start of log notes in current entry.
  10149. When optional argument CREATE is non-nil, the function creates
  10150. a drawer to store notes, if necessary. Returned position ignores
  10151. narrowing."
  10152. (org-with-wide-buffer
  10153. (let ((drawer (org-log-into-drawer)))
  10154. (cond
  10155. (drawer
  10156. (org-end-of-meta-data)
  10157. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  10158. (end (if (org-at-heading-p) (point)
  10159. (save-excursion (outline-next-heading) (point))))
  10160. (case-fold-search t))
  10161. (catch 'exit
  10162. ;; Try to find existing drawer.
  10163. (while (re-search-forward regexp end t)
  10164. (let ((element (org-element-at-point)))
  10165. (when (eq (org-element-type element) 'drawer)
  10166. (let ((cend (org-element-property :contents-end element)))
  10167. (when (and (not org-log-states-order-reversed) cend)
  10168. (goto-char cend)))
  10169. (throw 'exit nil))))
  10170. ;; No drawer found. Create one, if permitted.
  10171. (when create
  10172. (unless (bolp) (insert "\n"))
  10173. (let ((beg (point)))
  10174. (insert ":" drawer ":\n:END:\n")
  10175. (org-indent-region beg (point))
  10176. (org-flag-region
  10177. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  10178. (end-of-line -1)))))
  10179. (t
  10180. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  10181. (skip-chars-forward " \t\n")
  10182. (beginning-of-line)
  10183. (unless org-log-states-order-reversed
  10184. (org-skip-over-state-notes)
  10185. (skip-chars-backward " \t\n")
  10186. (forward-line)))))
  10187. (if (bolp) (point) (line-beginning-position 2))))
  10188. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  10189. "Set up the post command hook to take a note.
  10190. If this is about to TODO state change, the new state is expected in STATE.
  10191. HOW is an indicator what kind of note should be created.
  10192. EXTRA is additional text that will be inserted into the notes buffer."
  10193. (move-marker org-log-note-marker (point))
  10194. (setq org-log-note-purpose purpose
  10195. org-log-note-state state
  10196. org-log-note-previous-state prev-state
  10197. org-log-note-how how
  10198. org-log-note-extra extra
  10199. org-log-note-effective-time (org-current-effective-time))
  10200. (add-hook 'post-command-hook 'org-add-log-note 'append))
  10201. (defun org-skip-over-state-notes ()
  10202. "Skip past the list of State notes in an entry."
  10203. (when (ignore-errors (goto-char (org-in-item-p)))
  10204. (let* ((struct (org-list-struct))
  10205. (prevs (org-list-prevs-alist struct))
  10206. (regexp
  10207. (concat "[ \t]*- +"
  10208. (replace-regexp-in-string
  10209. " +" " +"
  10210. (org-replace-escapes
  10211. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  10212. `(("%d" . ,org-ts-regexp-inactive)
  10213. ("%D" . ,org-ts-regexp)
  10214. ("%s" . "\\(?:\"\\S-+\"\\)?")
  10215. ("%S" . "\\(?:\"\\S-+\"\\)?")
  10216. ("%t" . ,org-ts-regexp-inactive)
  10217. ("%T" . ,org-ts-regexp)
  10218. ("%u" . ".*?")
  10219. ("%U" . ".*?")))))))
  10220. (while (looking-at-p regexp)
  10221. (goto-char (or (org-list-get-next-item (point) struct prevs)
  10222. (org-list-get-item-end (point) struct)))))))
  10223. (defun org-add-log-note (&optional _purpose)
  10224. "Pop up a window for taking a note, and add this note later."
  10225. (remove-hook 'post-command-hook 'org-add-log-note)
  10226. (setq org-log-note-window-configuration (current-window-configuration))
  10227. (delete-other-windows)
  10228. (move-marker org-log-note-return-to (point))
  10229. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  10230. (goto-char org-log-note-marker)
  10231. (org-switch-to-buffer-other-window "*Org Note*")
  10232. (erase-buffer)
  10233. (if (memq org-log-note-how '(time state))
  10234. (org-store-log-note)
  10235. (let ((org-inhibit-startup t)) (org-mode))
  10236. (insert (format "# Insert note for %s.
  10237. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  10238. (cl-case org-log-note-purpose
  10239. (clock-out "stopped clock")
  10240. (done "closed todo item")
  10241. (reschedule "rescheduling")
  10242. (delschedule "no longer scheduled")
  10243. (redeadline "changing deadline")
  10244. (deldeadline "removing deadline")
  10245. (refile "refiling")
  10246. (note "this entry")
  10247. (state
  10248. (format "state change from \"%s\" to \"%s\""
  10249. (or org-log-note-previous-state "")
  10250. (or org-log-note-state "")))
  10251. (t (error "This should not happen")))))
  10252. (when org-log-note-extra (insert org-log-note-extra))
  10253. (setq-local org-finish-function 'org-store-log-note)
  10254. (run-hooks 'org-log-buffer-setup-hook)))
  10255. (defvar org-note-abort nil) ; dynamically scoped
  10256. (defun org-store-log-note ()
  10257. "Finish taking a log note, and insert it to where it belongs."
  10258. (let ((txt (prog1 (buffer-string)
  10259. (kill-buffer)))
  10260. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  10261. lines)
  10262. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  10263. (setq txt (replace-match "" t t txt)))
  10264. (when (string-match "\\s-+\\'" txt)
  10265. (setq txt (replace-match "" t t txt)))
  10266. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  10267. (when (org-string-nw-p note)
  10268. (setq note
  10269. (org-replace-escapes
  10270. note
  10271. (list (cons "%u" (user-login-name))
  10272. (cons "%U" user-full-name)
  10273. (cons "%t" (format-time-string
  10274. (org-time-stamp-format 'long 'inactive)
  10275. org-log-note-effective-time))
  10276. (cons "%T" (format-time-string
  10277. (org-time-stamp-format 'long nil)
  10278. org-log-note-effective-time))
  10279. (cons "%d" (format-time-string
  10280. (org-time-stamp-format nil 'inactive)
  10281. org-log-note-effective-time))
  10282. (cons "%D" (format-time-string
  10283. (org-time-stamp-format nil nil)
  10284. org-log-note-effective-time))
  10285. (cons "%s" (cond
  10286. ((not org-log-note-state) "")
  10287. ((string-match-p org-ts-regexp
  10288. org-log-note-state)
  10289. (format "\"[%s]\""
  10290. (substring org-log-note-state 1 -1)))
  10291. (t (format "\"%s\"" org-log-note-state))))
  10292. (cons "%S"
  10293. (cond
  10294. ((not org-log-note-previous-state) "")
  10295. ((string-match-p org-ts-regexp
  10296. org-log-note-previous-state)
  10297. (format "\"[%s]\""
  10298. (substring
  10299. org-log-note-previous-state 1 -1)))
  10300. (t (format "\"%s\""
  10301. org-log-note-previous-state)))))))
  10302. (when lines (setq note (concat note " \\\\")))
  10303. (push note lines))
  10304. (when (and lines (not org-note-abort))
  10305. (with-current-buffer (marker-buffer org-log-note-marker)
  10306. (org-with-wide-buffer
  10307. ;; Find location for the new note.
  10308. (goto-char org-log-note-marker)
  10309. (set-marker org-log-note-marker nil)
  10310. ;; Note associated to a clock is to be located right after
  10311. ;; the clock. Do not move point.
  10312. (unless (eq org-log-note-purpose 'clock-out)
  10313. (goto-char (org-log-beginning t)))
  10314. ;; Make sure point is at the beginning of an empty line.
  10315. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  10316. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  10317. ;; In an existing list, add a new item at the top level.
  10318. ;; Otherwise, indent line like a regular one.
  10319. (let ((itemp (org-in-item-p)))
  10320. (if itemp
  10321. (indent-line-to
  10322. (let ((struct (save-excursion
  10323. (goto-char itemp) (org-list-struct))))
  10324. (org-list-get-ind (org-list-get-top-point struct) struct)))
  10325. (org-indent-line)))
  10326. (insert (org-list-bullet-string "-") (pop lines))
  10327. (let ((ind (org-list-item-body-column (line-beginning-position))))
  10328. (dolist (line lines)
  10329. (insert "\n")
  10330. (indent-line-to ind)
  10331. (insert line)))
  10332. (message "Note stored")
  10333. (org-back-to-heading t))
  10334. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  10335. ;; from within `org-add-log-note' because `buffer-undo-list'
  10336. ;; is then modified outside of `org-with-remote-undo'.
  10337. (when (eq this-command 'org-agenda-todo)
  10338. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  10339. ;; Don't add undo information when called from `org-agenda-todo'.
  10340. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  10341. (set-window-configuration org-log-note-window-configuration)
  10342. (with-current-buffer (marker-buffer org-log-note-return-to)
  10343. (goto-char org-log-note-return-to))
  10344. (move-marker org-log-note-return-to nil)
  10345. (when org-log-post-message (message "%s" org-log-post-message))))
  10346. (defun org-remove-empty-drawer-at (pos)
  10347. "Remove an empty drawer at position POS.
  10348. POS may also be a marker."
  10349. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  10350. (org-with-wide-buffer
  10351. (goto-char pos)
  10352. (let ((drawer (org-element-at-point)))
  10353. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  10354. (not (org-element-property :contents-begin drawer)))
  10355. (delete-region (org-element-property :begin drawer)
  10356. (progn (goto-char (org-element-property :end drawer))
  10357. (skip-chars-backward " \r\t\n")
  10358. (forward-line)
  10359. (point))))))))
  10360. (defvar org-ts-type nil)
  10361. (defun org-sparse-tree (&optional arg type)
  10362. "Create a sparse tree, prompt for the details.
  10363. This command can create sparse trees. You first need to select the type
  10364. of match used to create the tree:
  10365. t Show all TODO entries.
  10366. T Show entries with a specific TODO keyword.
  10367. m Show entries selected by a tags/property match.
  10368. p Enter a property name and its value (both with completion on existing
  10369. names/values) and show entries with that property.
  10370. r Show entries matching a regular expression (`/' can be used as well).
  10371. b Show deadlines and scheduled items before a date.
  10372. a Show deadlines and scheduled items after a date.
  10373. d Show deadlines due within `org-deadline-warning-days'.
  10374. D Show deadlines and scheduled items between a date range."
  10375. (interactive "P")
  10376. (setq type (or type org-sparse-tree-default-date-type))
  10377. (setq org-ts-type type)
  10378. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  10379. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  10380. \[c]ycle through date types: %s"
  10381. (cl-case type
  10382. (all "all timestamps")
  10383. (scheduled "only scheduled")
  10384. (deadline "only deadline")
  10385. (active "only active timestamps")
  10386. (inactive "only inactive timestamps")
  10387. (closed "with a closed time-stamp")
  10388. (otherwise "scheduled/deadline")))
  10389. (let ((answer (read-char-exclusive)))
  10390. (cl-case answer
  10391. (?c
  10392. (org-sparse-tree
  10393. arg
  10394. (cadr
  10395. (memq type '(nil all scheduled deadline active inactive closed)))))
  10396. (?d (call-interactively 'org-check-deadlines))
  10397. (?b (call-interactively 'org-check-before-date))
  10398. (?a (call-interactively 'org-check-after-date))
  10399. (?D (call-interactively 'org-check-dates-range))
  10400. (?t (call-interactively 'org-show-todo-tree))
  10401. (?T (org-show-todo-tree '(4)))
  10402. (?m (call-interactively 'org-match-sparse-tree))
  10403. ((?p ?P)
  10404. (let* ((kwd (completing-read
  10405. "Property: " (mapcar #'list (org-buffer-property-keys))))
  10406. (value (completing-read
  10407. "Value: " (mapcar #'list (org-property-values kwd)))))
  10408. (unless (string-match "\\`{.*}\\'" value)
  10409. (setq value (concat "\"" value "\"")))
  10410. (org-match-sparse-tree arg (concat kwd "=" value))))
  10411. ((?r ?R ?/) (call-interactively 'org-occur))
  10412. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  10413. (defvar-local org-occur-highlights nil
  10414. "List of overlays used for occur matches.")
  10415. (defvar-local org-occur-parameters nil
  10416. "Parameters of the active org-occur calls.
  10417. This is a list, each call to org-occur pushes as cons cell,
  10418. containing the regular expression and the callback, onto the list.
  10419. The list can contain several entries if `org-occur' has been called
  10420. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  10421. will only contain one set of parameters. When the highlights are
  10422. removed (for example with `C-c C-c', or with the next edit (depending
  10423. on `org-remove-highlights-with-change'), this variable is emptied
  10424. as well.")
  10425. (defun org-occur (regexp &optional keep-previous callback)
  10426. "Make a compact tree which shows all matches of REGEXP.
  10427. The tree will show the lines where the regexp matches, and any other context
  10428. defined in `org-show-context-detail', which see.
  10429. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  10430. done by a previous call to `org-occur' will be kept, to allow stacking of
  10431. calls to this command.
  10432. Optional argument CALLBACK can be a function of no argument. In this case,
  10433. it is called with point at the end of the match, match data being set
  10434. accordingly. Current match is shown only if the return value is non-nil.
  10435. The function must neither move point nor alter narrowing."
  10436. (interactive "sRegexp: \nP")
  10437. (when (equal regexp "")
  10438. (user-error "Regexp cannot be empty"))
  10439. (unless keep-previous
  10440. (org-remove-occur-highlights nil nil t))
  10441. (push (cons regexp callback) org-occur-parameters)
  10442. (let ((cnt 0))
  10443. (save-excursion
  10444. (goto-char (point-min))
  10445. (when (or (not keep-previous) ; do not want to keep
  10446. (not org-occur-highlights)) ; no previous matches
  10447. ;; hide everything
  10448. (org-overview))
  10449. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  10450. (isearch-no-upper-case-p regexp t)
  10451. org-occur-case-fold-search)))
  10452. (while (re-search-forward regexp nil t)
  10453. (when (or (not callback)
  10454. (save-match-data (funcall callback)))
  10455. (setq cnt (1+ cnt))
  10456. (when org-highlight-sparse-tree-matches
  10457. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  10458. (org-show-context 'occur-tree)))))
  10459. (when org-remove-highlights-with-change
  10460. (add-hook 'before-change-functions 'org-remove-occur-highlights
  10461. nil 'local))
  10462. (unless org-sparse-tree-open-archived-trees
  10463. (org-hide-archived-subtrees (point-min) (point-max)))
  10464. (run-hooks 'org-occur-hook)
  10465. (when (called-interactively-p 'interactive)
  10466. (message "%d match(es) for regexp %s" cnt regexp))
  10467. cnt))
  10468. (defun org-occur-next-match (&optional n _reset)
  10469. "Function for `next-error-function' to find sparse tree matches.
  10470. N is the number of matches to move, when negative move backwards.
  10471. This function always goes back to the starting point when no
  10472. match is found."
  10473. (let* ((limit (if (< n 0) (point-min) (point-max)))
  10474. (search-func (if (< n 0)
  10475. 'previous-single-char-property-change
  10476. 'next-single-char-property-change))
  10477. (n (abs n))
  10478. (pos (point))
  10479. p1)
  10480. (catch 'exit
  10481. (while (setq p1 (funcall search-func (point) 'org-type))
  10482. (when (equal p1 limit)
  10483. (goto-char pos)
  10484. (user-error "No more matches"))
  10485. (when (equal (get-char-property p1 'org-type) 'org-occur)
  10486. (setq n (1- n))
  10487. (when (= n 0)
  10488. (goto-char p1)
  10489. (throw 'exit (point))))
  10490. (goto-char p1))
  10491. (goto-char p1)
  10492. (user-error "No more matches"))))
  10493. (defun org-highlight-new-match (beg end)
  10494. "Highlight from BEG to END and mark the highlight is an occur headline."
  10495. (let ((ov (make-overlay beg end)))
  10496. (overlay-put ov 'face 'secondary-selection)
  10497. (overlay-put ov 'org-type 'org-occur)
  10498. (push ov org-occur-highlights)))
  10499. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10500. "Remove the occur highlights from the buffer.
  10501. BEG and END are ignored. If NOREMOVE is nil, remove this function
  10502. from the `before-change-functions' in the current buffer."
  10503. (interactive)
  10504. (unless org-inhibit-highlight-removal
  10505. (mapc #'delete-overlay org-occur-highlights)
  10506. (setq org-occur-highlights nil)
  10507. (setq org-occur-parameters nil)
  10508. (unless noremove
  10509. (remove-hook 'before-change-functions
  10510. 'org-remove-occur-highlights 'local))))
  10511. ;;;; Priorities
  10512. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  10513. "Regular expression matching the priority indicator.")
  10514. (defun org-priority-up ()
  10515. "Increase the priority of the current item."
  10516. (interactive)
  10517. (org-priority 'up))
  10518. (defun org-priority-down ()
  10519. "Decrease the priority of the current item."
  10520. (interactive)
  10521. (org-priority 'down))
  10522. (defun org-priority (&optional action show)
  10523. "Change the priority of an item.
  10524. When called interactively with a `\\[universal-argument]' prefix,
  10525. show the priority in the minibuffer instead of changing it.
  10526. When called programmatically, ACTION can be `set', `up', `down',
  10527. or a character."
  10528. (interactive "P")
  10529. (when show
  10530. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10531. ;; passed the SHOW argument should be removed.
  10532. (warn "`org-priority' called with deprecated SHOW argument"))
  10533. (if (equal action '(4))
  10534. (org-priority-show)
  10535. (unless org-priority-enable-commands
  10536. (user-error "Priority commands are disabled"))
  10537. (setq action (or action 'set))
  10538. (let (current new news have remove)
  10539. (save-excursion
  10540. (org-back-to-heading t)
  10541. (when (looking-at org-priority-regexp)
  10542. (setq current (string-to-char (match-string 2))
  10543. have t))
  10544. (cond
  10545. ((eq action 'remove)
  10546. (setq remove t new ?\ ))
  10547. ((or (eq action 'set)
  10548. (integerp action))
  10549. (if (not (eq action 'set))
  10550. (setq new action)
  10551. (message "Priority %c-%c, SPC to remove: "
  10552. org-priority-highest org-priority-lowest)
  10553. (save-match-data
  10554. (setq new (read-char-exclusive))))
  10555. (when (and (= (upcase org-priority-highest) org-priority-highest)
  10556. (= (upcase org-priority-lowest) org-priority-lowest))
  10557. (setq new (upcase new)))
  10558. (cond ((equal new ?\s) (setq remove t))
  10559. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  10560. (user-error "Priority must be between `%c' and `%c'"
  10561. org-priority-highest org-priority-lowest))))
  10562. ((eq action 'up)
  10563. (setq new (if have
  10564. (1- current) ; normal cycling
  10565. ;; last priority was empty
  10566. (if (eq last-command this-command)
  10567. org-priority-lowest ; wrap around empty to lowest
  10568. ;; default
  10569. (if org-priority-start-cycle-with-default
  10570. org-priority-default
  10571. (1- org-priority-default))))))
  10572. ((eq action 'down)
  10573. (setq new (if have
  10574. (1+ current) ; normal cycling
  10575. ;; last priority was empty
  10576. (if (eq last-command this-command)
  10577. org-priority-highest ; wrap around empty to highest
  10578. ;; default
  10579. (if org-priority-start-cycle-with-default
  10580. org-priority-default
  10581. (1+ org-priority-default))))))
  10582. (t (user-error "Invalid action")))
  10583. (when (or (< (upcase new) org-priority-highest)
  10584. (> (upcase new) org-priority-lowest))
  10585. (if (and (memq action '(up down))
  10586. (not have) (not (eq last-command this-command)))
  10587. ;; `new' is from default priority
  10588. (error
  10589. "The default can not be set, see `org-priority-default' why")
  10590. ;; normal cycling: `new' is beyond highest/lowest priority
  10591. ;; and is wrapped around to the empty priority
  10592. (setq remove t)))
  10593. (setq news (format "%c" new))
  10594. (if have
  10595. (if remove
  10596. (replace-match "" t t nil 1)
  10597. (replace-match news t t nil 2))
  10598. (if remove
  10599. (user-error "No priority cookie found in line")
  10600. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10601. (if (match-end 2)
  10602. (progn
  10603. (goto-char (match-end 2))
  10604. (insert " [#" news "]"))
  10605. (goto-char (match-beginning 3))
  10606. (insert "[#" news "] "))))
  10607. (org-align-tags))
  10608. (if remove
  10609. (message "Priority removed")
  10610. (message "Priority of current item set to %s" news)))))
  10611. (defalias 'org-show-priority 'org-priority-show)
  10612. (defun org-priority-show ()
  10613. "Show the priority of the current item.
  10614. This priority is composed of the main priority given with the [#A] cookies,
  10615. and by additional input from the age of a schedules or deadline entry."
  10616. (interactive)
  10617. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10618. (org-get-at-bol 'priority)
  10619. (save-excursion
  10620. (save-match-data
  10621. (beginning-of-line)
  10622. (and (looking-at org-heading-regexp)
  10623. (org-get-priority (match-string 0))))))))
  10624. (message "Priority is %d" (if pri pri -1000))))
  10625. (defun org-get-priority (s)
  10626. "Find priority cookie and return priority."
  10627. (save-match-data
  10628. (if (functionp org-priority-get-priority-function)
  10629. (funcall org-priority-get-priority-function s)
  10630. (if (not (string-match org-priority-regexp s))
  10631. (* 1000 (- org-priority-lowest org-priority-default))
  10632. (* 1000 (- org-priority-lowest
  10633. (string-to-char (match-string 2 s))))))))
  10634. ;;;; Tags
  10635. (defvar org-agenda-archives-mode)
  10636. (defvar org-map-continue-from nil
  10637. "Position from where mapping should continue.
  10638. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10639. (defvar org-scanner-tags nil
  10640. "The current tag list while the tags scanner is running.")
  10641. (defvar org-trust-scanner-tags nil
  10642. "Should `org-get-tags' use the tags for the scanner.
  10643. This is for internal dynamical scoping only.
  10644. When this is non-nil, the function `org-get-tags' will return the value
  10645. of `org-scanner-tags' instead of building the list by itself. This
  10646. can lead to large speed-ups when the tags scanner is used in a file with
  10647. many entries, and when the list of tags is retrieved, for example to
  10648. obtain a list of properties. Building the tags list for each entry in such
  10649. a file becomes an N^2 operation - but with this variable set, it scales
  10650. as N.")
  10651. (defvar org--matcher-tags-todo-only nil)
  10652. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10653. "Scan headline tags with inheritance and produce output ACTION.
  10654. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10655. or `agenda' to produce an entry list for an agenda view. It can also be
  10656. a Lisp form or a function that should be called at each matched headline, in
  10657. this case the return value is a list of all return values from these calls.
  10658. MATCHER is a function accepting three arguments, returning
  10659. a non-nil value whenever a given set of tags qualifies a headline
  10660. for inclusion. See `org-make-tags-matcher' for more information.
  10661. As a special case, it can also be set to t (respectively nil) in
  10662. order to match all (respectively none) headline.
  10663. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10664. included in the output.
  10665. START-LEVEL can be a string with asterisks, reducing the scope to
  10666. headlines matching this string."
  10667. (require 'org-agenda)
  10668. (let* ((re (concat "^"
  10669. (if start-level
  10670. ;; Get the correct level to match
  10671. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10672. org-outline-regexp)
  10673. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10674. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10675. (props (list 'face 'default
  10676. 'done-face 'org-agenda-done
  10677. 'undone-face 'default
  10678. 'mouse-face 'highlight
  10679. 'org-not-done-regexp org-not-done-regexp
  10680. 'org-todo-regexp org-todo-regexp
  10681. 'org-complex-heading-regexp org-complex-heading-regexp
  10682. 'help-echo
  10683. (format "mouse-2 or RET jump to Org file %S"
  10684. (abbreviate-file-name
  10685. (or (buffer-file-name (buffer-base-buffer))
  10686. (buffer-name (buffer-base-buffer)))))))
  10687. (org-map-continue-from nil)
  10688. lspos tags tags-list
  10689. (tags-alist (list (cons 0 org-file-tags)))
  10690. (llast 0) rtn rtn1 level category i txt
  10691. todo marker entry priority
  10692. ts-date ts-date-type ts-date-pair)
  10693. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10694. (setq action (list 'lambda nil action)))
  10695. (save-excursion
  10696. (goto-char (point-min))
  10697. (when (eq action 'sparse-tree)
  10698. (org-overview)
  10699. (org-remove-occur-highlights))
  10700. (while (let (case-fold-search)
  10701. (re-search-forward re nil t))
  10702. (setq org-map-continue-from nil)
  10703. (catch :skip
  10704. ;; Ignore closing parts of inline tasks.
  10705. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10706. (throw :skip t))
  10707. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10708. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10709. (goto-char (setq lspos (match-beginning 0)))
  10710. (setq level (org-reduced-level (org-outline-level))
  10711. category (org-get-category))
  10712. (when (eq action 'agenda)
  10713. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10714. ts-date (car ts-date-pair)
  10715. ts-date-type (cdr ts-date-pair)))
  10716. (setq i llast llast level)
  10717. ;; remove tag lists from same and sublevels
  10718. (while (>= i level)
  10719. (when (setq entry (assoc i tags-alist))
  10720. (setq tags-alist (delete entry tags-alist)))
  10721. (setq i (1- i)))
  10722. ;; add the next tags
  10723. (when tags
  10724. (setq tags (org-split-string tags ":")
  10725. tags-alist
  10726. (cons (cons level tags) tags-alist)))
  10727. ;; compile tags for current headline
  10728. (setq tags-list
  10729. (if org-use-tag-inheritance
  10730. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10731. tags)
  10732. org-scanner-tags tags-list)
  10733. (when org-use-tag-inheritance
  10734. (setcdr (car tags-alist)
  10735. (mapcar (lambda (x)
  10736. (setq x (copy-sequence x))
  10737. (org-add-prop-inherited x))
  10738. (cdar tags-alist))))
  10739. (when (and tags org-use-tag-inheritance
  10740. (or (not (eq t org-use-tag-inheritance))
  10741. org-tags-exclude-from-inheritance))
  10742. ;; Selective inheritance, remove uninherited ones.
  10743. (setcdr (car tags-alist)
  10744. (org-remove-uninherited-tags (cdar tags-alist))))
  10745. (when (and
  10746. ;; eval matcher only when the todo condition is OK
  10747. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10748. (if (functionp matcher)
  10749. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10750. (funcall matcher todo tags-list level))
  10751. matcher))
  10752. ;; Call the skipper, but return t if it does not
  10753. ;; skip, so that the `and' form continues evaluating.
  10754. (progn
  10755. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10756. t)
  10757. ;; Check if timestamps are deselecting this entry
  10758. (or (not todo-only)
  10759. (and (member todo org-todo-keywords-1)
  10760. (or (not org-agenda-tags-todo-honor-ignore-options)
  10761. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10762. ;; select this headline
  10763. (cond
  10764. ((eq action 'sparse-tree)
  10765. (and org-highlight-sparse-tree-matches
  10766. (org-get-heading) (match-end 0)
  10767. (org-highlight-new-match
  10768. (match-beginning 1) (match-end 1)))
  10769. (org-show-context 'tags-tree))
  10770. ((eq action 'agenda)
  10771. (setq txt (org-agenda-format-item
  10772. ""
  10773. (concat
  10774. (if (eq org-tags-match-list-sublevels 'indented)
  10775. (make-string (1- level) ?.) "")
  10776. (org-get-heading))
  10777. (make-string level ?\s)
  10778. category
  10779. tags-list)
  10780. priority (org-get-priority txt))
  10781. (goto-char lspos)
  10782. (setq marker (org-agenda-new-marker))
  10783. (org-add-props txt props
  10784. 'org-marker marker 'org-hd-marker marker 'org-category category
  10785. 'todo-state todo
  10786. 'ts-date ts-date
  10787. 'priority priority
  10788. 'type (concat "tagsmatch" ts-date-type))
  10789. (push txt rtn))
  10790. ((functionp action)
  10791. (setq org-map-continue-from nil)
  10792. (save-excursion
  10793. (setq rtn1 (funcall action))
  10794. (push rtn1 rtn)))
  10795. (t (user-error "Invalid action")))
  10796. ;; if we are to skip sublevels, jump to end of subtree
  10797. (unless org-tags-match-list-sublevels
  10798. (org-end-of-subtree t)
  10799. (backward-char 1))))
  10800. ;; Get the correct position from where to continue
  10801. (if org-map-continue-from
  10802. (goto-char org-map-continue-from)
  10803. (and (= (point) lspos) (end-of-line 1)))))
  10804. (when (and (eq action 'sparse-tree)
  10805. (not org-sparse-tree-open-archived-trees))
  10806. (org-hide-archived-subtrees (point-min) (point-max)))
  10807. (nreverse rtn)))
  10808. (defun org-remove-uninherited-tags (tags)
  10809. "Remove all tags that are not inherited from the list TAGS."
  10810. (cond
  10811. ((eq org-use-tag-inheritance t)
  10812. (if org-tags-exclude-from-inheritance
  10813. (org-delete-all org-tags-exclude-from-inheritance tags)
  10814. tags))
  10815. ((not org-use-tag-inheritance) nil)
  10816. ((stringp org-use-tag-inheritance)
  10817. (delq nil (mapcar
  10818. (lambda (x)
  10819. (if (and (string-match org-use-tag-inheritance x)
  10820. (not (member x org-tags-exclude-from-inheritance)))
  10821. x nil))
  10822. tags)))
  10823. ((listp org-use-tag-inheritance)
  10824. (delq nil (mapcar
  10825. (lambda (x)
  10826. (if (member x org-use-tag-inheritance) x nil))
  10827. tags)))))
  10828. (defun org-match-sparse-tree (&optional todo-only match)
  10829. "Create a sparse tree according to tags string MATCH.
  10830. MATCH is a string with match syntax. It can contain a selection
  10831. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10832. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10833. those. See the manual for details.
  10834. If optional argument TODO-ONLY is non-nil, only select lines that
  10835. are also TODO tasks."
  10836. (interactive "P")
  10837. (org-agenda-prepare-buffers (list (current-buffer)))
  10838. (let ((org--matcher-tags-todo-only todo-only))
  10839. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  10840. org--matcher-tags-todo-only)))
  10841. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10842. (defvar org-cached-props nil)
  10843. (defun org-cached-entry-get (pom property)
  10844. (if (or (eq t org-use-property-inheritance)
  10845. (and (stringp org-use-property-inheritance)
  10846. (let ((case-fold-search t))
  10847. (string-match-p org-use-property-inheritance property)))
  10848. (and (listp org-use-property-inheritance)
  10849. (member-ignore-case property org-use-property-inheritance)))
  10850. ;; Caching is not possible, check it directly.
  10851. (org-entry-get pom property 'inherit)
  10852. ;; Get all properties, so we can do complicated checks easily.
  10853. (cdr (assoc-string property
  10854. (or org-cached-props
  10855. (setq org-cached-props (org-entry-properties pom)))
  10856. t))))
  10857. (defun org-global-tags-completion-table (&optional files)
  10858. "Return the list of all tags in all agenda buffer/files.
  10859. Optional FILES argument is a list of files which can be used
  10860. instead of the agenda files."
  10861. (save-excursion
  10862. (org-uniquify
  10863. (delq nil
  10864. (apply #'append
  10865. (mapcar
  10866. (lambda (file)
  10867. (set-buffer (find-file-noselect file))
  10868. (org--tag-add-to-alist
  10869. (org-get-buffer-tags)
  10870. (mapcar (lambda (x)
  10871. (and (stringp (car-safe x))
  10872. (list (car-safe x))))
  10873. org-current-tag-alist)))
  10874. (if (car-safe files) files
  10875. (org-agenda-files))))))))
  10876. (defun org-make-tags-matcher (match)
  10877. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10878. Returns a cons of the selection string MATCH and a function
  10879. implementing the matcher.
  10880. The matcher is to be called at an Org entry, with point on the
  10881. headline, and returns non-nil if the entry matches the selection
  10882. string MATCH. It must be called with three arguments: the TODO
  10883. keyword at the entry (or nil if none), the list of all tags at
  10884. the entry including inherited ones and the reduced level of the
  10885. headline. Additionally, the category of the entry, if any, must
  10886. be specified as the text property `org-category' on the headline.
  10887. This function sets the variable `org--matcher-tags-todo-only' to
  10888. a non-nil value if the matcher restricts matching to TODO
  10889. entries, otherwise it is not touched.
  10890. See also `org-scan-tags'."
  10891. (unless match
  10892. ;; Get a new match request, with completion against the global
  10893. ;; tags table and the local tags in current buffer.
  10894. (let ((org-last-tags-completion-table
  10895. (org--tag-add-to-alist
  10896. (org-get-buffer-tags)
  10897. (org-global-tags-completion-table))))
  10898. (setq match
  10899. (completing-read
  10900. "Match: "
  10901. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10902. (let ((match0 match)
  10903. (re (concat
  10904. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10905. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10906. "\\([<>=]\\{1,2\\}\\)"
  10907. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10908. "\\|" org-tag-re "\\)"))
  10909. (start 0)
  10910. tagsmatch todomatch tagsmatcher todomatcher)
  10911. ;; Expand group tags.
  10912. (setq match (org-tags-expand match))
  10913. ;; Check if there is a TODO part of this match, which would be the
  10914. ;; part after a "/". To make sure that this slash is not part of
  10915. ;; a property value to be matched against, we also check that
  10916. ;; there is no / after that slash. First, find the last slash.
  10917. (let ((s 0))
  10918. (while (string-match "/+" match s)
  10919. (setq start (match-beginning 0))
  10920. (setq s (match-end 0))))
  10921. (if (and (string-match "/+" match start)
  10922. (not (string-match-p "\"" match start)))
  10923. ;; Match contains also a TODO-matching request.
  10924. (progn
  10925. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10926. (setq todomatch (substring match (match-end 0)))
  10927. (when (string-prefix-p "!" todomatch)
  10928. (setq org--matcher-tags-todo-only t)
  10929. (setq todomatch (substring todomatch 1)))
  10930. (when (string-match "\\`\\s-*\\'" todomatch)
  10931. (setq todomatch nil)))
  10932. ;; Only matching tags.
  10933. (setq tagsmatch match)
  10934. (setq todomatch nil))
  10935. ;; Make the tags matcher.
  10936. (when (org-string-nw-p tagsmatch)
  10937. (let ((orlist nil)
  10938. (orterms (org-split-string tagsmatch "|"))
  10939. term)
  10940. (while (setq term (pop orterms))
  10941. (while (and (equal (substring term -1) "\\") orterms)
  10942. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10943. (while (string-match re term)
  10944. (let* ((rest (substring term (match-end 0)))
  10945. (minus (and (match-end 1)
  10946. (equal (match-string 1 term) "-")))
  10947. (tag (save-match-data
  10948. (replace-regexp-in-string
  10949. "\\\\-" "-" (match-string 2 term))))
  10950. (regexp (eq (string-to-char tag) ?{))
  10951. (levelp (match-end 4))
  10952. (propp (match-end 5))
  10953. (mm
  10954. (cond
  10955. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10956. (levelp
  10957. `(,(org-op-to-function (match-string 3 term))
  10958. level
  10959. ,(string-to-number (match-string 4 term))))
  10960. (propp
  10961. (let* ((gv (pcase (upcase (match-string 5 term))
  10962. ("CATEGORY"
  10963. '(get-text-property (point) 'org-category))
  10964. ("TODO" 'todo)
  10965. (p `(org-cached-entry-get nil ,p))))
  10966. (pv (match-string 7 term))
  10967. (regexp (eq (string-to-char pv) ?{))
  10968. (strp (eq (string-to-char pv) ?\"))
  10969. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10970. (po (org-op-to-function (match-string 6 term)
  10971. (if timep 'time strp))))
  10972. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10973. (when timep (setq pv (org-matcher-time pv)))
  10974. (cond ((and regexp (eq po '/=))
  10975. `(not (string-match ,pv (or ,gv ""))))
  10976. (regexp `(string-match ,pv (or ,gv "")))
  10977. (strp `(,po (or ,gv "") ,pv))
  10978. (t
  10979. `(,po
  10980. (string-to-number (or ,gv ""))
  10981. ,(string-to-number pv))))))
  10982. (t `(member ,tag tags-list)))))
  10983. (push (if minus `(not ,mm) mm) tagsmatcher)
  10984. (setq term rest)))
  10985. (push `(and ,@tagsmatcher) orlist)
  10986. (setq tagsmatcher nil))
  10987. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10988. ;; Make the TODO matcher.
  10989. (when (org-string-nw-p todomatch)
  10990. (let ((orlist nil))
  10991. (dolist (term (org-split-string todomatch "|"))
  10992. (while (string-match re term)
  10993. (let* ((minus (and (match-end 1)
  10994. (equal (match-string 1 term) "-")))
  10995. (kwd (match-string 2 term))
  10996. (regexp (eq (string-to-char kwd) ?{))
  10997. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10998. `(equal todo ,kwd))))
  10999. (push (if minus `(not ,mm) mm) todomatcher))
  11000. (setq term (substring term (match-end 0))))
  11001. (push (if (> (length todomatcher) 1)
  11002. (cons 'and todomatcher)
  11003. (car todomatcher))
  11004. orlist)
  11005. (setq todomatcher nil))
  11006. (setq todomatcher (cons 'or orlist))))
  11007. ;; Return the string and function of the matcher. If no
  11008. ;; tags-specific or todo-specific matcher exists, match
  11009. ;; everything.
  11010. (let ((matcher (if (and tagsmatcher todomatcher)
  11011. `(and ,tagsmatcher ,todomatcher)
  11012. (or tagsmatcher todomatcher t))))
  11013. (when org--matcher-tags-todo-only
  11014. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  11015. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  11016. (defun org--tags-expand-group (group tag-groups expanded)
  11017. "Recursively Expand all tags in GROUP, according to TAG-GROUPS.
  11018. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  11019. an accumulator used in recursive calls."
  11020. (dolist (tag group)
  11021. (unless (member tag expanded)
  11022. (let ((group (assoc tag tag-groups)))
  11023. (push tag expanded)
  11024. (when group
  11025. (setq expanded
  11026. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  11027. expanded)
  11028. (defun org-tags-expand (match &optional single-as-list downcased)
  11029. "Expand group tags in MATCH.
  11030. This replaces every group tag in MATCH with a regexp tag search.
  11031. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  11032. will be replaced like this:
  11033. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  11034. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  11035. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  11036. Replacing by a regexp preserves the structure of the match.
  11037. E.g., this expansion
  11038. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  11039. will match anything tagged with \"Lab\" and \"Home\", or tagged
  11040. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  11041. A group tag in MATCH can contain regular expressions of its own.
  11042. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  11043. will be replaced like this:
  11044. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  11045. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  11046. assumed to be a single group tag, and the function will return
  11047. the list of tags in this group.
  11048. When DOWNCASED is non-nil, expand downcased TAGS."
  11049. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  11050. (let ((tag-groups
  11051. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  11052. (if (not downcased) g
  11053. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  11054. (cond
  11055. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  11056. (org-group-tags
  11057. (let* ((case-fold-search t)
  11058. (tag-syntax org-mode-syntax-table)
  11059. (group-keys (mapcar #'car tag-groups))
  11060. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  11061. (return-match (if downcased (downcase match) match)))
  11062. ;; Mark regexp-expressions in the match-expression so that we
  11063. ;; do not replace them later on.
  11064. (let ((s 0))
  11065. (while (string-match "{.+?}" return-match s)
  11066. (setq s (match-end 0))
  11067. (add-text-properties
  11068. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  11069. ;; @ and _ are allowed as word-components in tags.
  11070. (modify-syntax-entry ?@ "w" tag-syntax)
  11071. (modify-syntax-entry ?_ "w" tag-syntax)
  11072. ;; For each tag token found in MATCH, compute a regexp and it
  11073. (with-syntax-table tag-syntax
  11074. (replace-regexp-in-string
  11075. key-regexp
  11076. (lambda (m)
  11077. (if (get-text-property (match-beginning 2) 'regexp m)
  11078. m ;regexp tag: ignore
  11079. (let* ((operator (match-string 1 m))
  11080. (tag-token (let ((tag (match-string 2 m)))
  11081. (list (if downcased (downcase tag) tag))))
  11082. regexp-tags regular-tags)
  11083. ;; Partition tags between regexp and regular tags.
  11084. ;; Remove curly bracket syntax from regexp tags.
  11085. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  11086. (save-match-data
  11087. (if (string-match "{\\(.+?\\)}" tag)
  11088. (push (match-string 1 tag) regexp-tags)
  11089. (push tag regular-tags))))
  11090. ;; Replace tag token by the appropriate regexp.
  11091. ;; Regular tags need to be regexp-quoted, whereas
  11092. ;; regexp-tags are inserted as-is.
  11093. (let ((regular (regexp-opt regular-tags))
  11094. (regexp (mapconcat #'identity regexp-tags "\\|")))
  11095. (concat operator
  11096. (cond
  11097. ((null regular-tags) (format "{%s}" regexp))
  11098. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  11099. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  11100. return-match
  11101. t t))))
  11102. (t match))))
  11103. (defun org-op-to-function (op &optional stringp)
  11104. "Turn an operator into the appropriate function."
  11105. (setq op
  11106. (cond
  11107. ((equal op "<" ) '(< org-string< org-time<))
  11108. ((equal op ">" ) '(> org-string> org-time>))
  11109. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  11110. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  11111. ((member op '("=" "==")) '(= string= org-time=))
  11112. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  11113. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  11114. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  11115. (defvar org-tags-overlay (make-overlay 1 1))
  11116. (delete-overlay org-tags-overlay)
  11117. (defun org-add-prop-inherited (s)
  11118. (add-text-properties 0 (length s) '(inherited t) s)
  11119. s)
  11120. (defun org-toggle-tag (tag &optional onoff)
  11121. "Toggle the tag TAG for the current line.
  11122. If ONOFF is `on' or `off', don't toggle but set to this state."
  11123. (save-excursion
  11124. (org-back-to-heading t)
  11125. (let ((current
  11126. ;; Reverse the tags list so any new tag is appended to the
  11127. ;; current list of tags.
  11128. (nreverse (org-get-tags nil t)))
  11129. res)
  11130. (pcase onoff
  11131. (`off (setq current (delete tag current)))
  11132. ((or `on (guard (not (member tag current))))
  11133. (setq res t)
  11134. (cl-pushnew tag current :test #'equal))
  11135. (_ (setq current (delete tag current))))
  11136. (org-set-tags (nreverse current))
  11137. res)))
  11138. (defun org--align-tags-here (to-col)
  11139. "Align tags on the current headline to TO-COL.
  11140. Assume point is on a headline. Preserve point when aligning
  11141. tags."
  11142. (when (org-match-line org-tag-line-re)
  11143. (let* ((tags-start (match-beginning 1))
  11144. (blank-start (save-excursion
  11145. (goto-char tags-start)
  11146. (skip-chars-backward " \t")
  11147. (point)))
  11148. (new (max (if (>= to-col 0) to-col
  11149. (- (abs to-col) (string-width (match-string 1))))
  11150. ;; Introduce at least one space after the heading
  11151. ;; or the stars.
  11152. (save-excursion
  11153. (goto-char blank-start)
  11154. (1+ (current-column)))))
  11155. (current
  11156. (save-excursion (goto-char tags-start) (current-column)))
  11157. (origin (point-marker))
  11158. (column (current-column))
  11159. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  11160. (when (/= new current)
  11161. (delete-region blank-start tags-start)
  11162. (goto-char blank-start)
  11163. (let ((indent-tabs-mode nil)) (indent-to new))
  11164. ;; Try to move back to original position. If point was in the
  11165. ;; blanks before the tags, ORIGIN marker is of no use because
  11166. ;; it now points to BLANK-START. Use COLUMN instead.
  11167. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  11168. (defun org-set-tags-command (&optional arg)
  11169. "Set the tags for the current visible entry.
  11170. When called with `\\[universal-argument]' prefix argument ARG, \
  11171. realign all tags
  11172. in the current buffer.
  11173. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  11174. unconditionally do not
  11175. offer the fast tag selection interface.
  11176. If a region is active, set tags in the region according to the
  11177. setting of `org-loop-over-headlines-in-active-region'.
  11178. This function is for interactive use only;
  11179. in Lisp code use `org-set-tags' instead."
  11180. (interactive "P")
  11181. (let ((org-use-fast-tag-selection
  11182. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  11183. (cond
  11184. ((equal '(4) arg) (org-align-tags t))
  11185. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11186. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  11187. (org-map-entries
  11188. #'org-set-tags-command
  11189. nil
  11190. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11191. 'region-start-level
  11192. 'region)
  11193. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  11194. (t
  11195. (save-excursion
  11196. (org-back-to-heading)
  11197. (let* ((all-tags (org-get-tags))
  11198. (table (setq org-last-tags-completion-table
  11199. (org--tag-add-to-alist
  11200. (and org-complete-tags-always-offer-all-agenda-tags
  11201. (org-global-tags-completion-table
  11202. (org-agenda-files)))
  11203. (or org-current-tag-alist (org-get-buffer-tags)))))
  11204. (current-tags
  11205. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  11206. all-tags))
  11207. (inherited-tags
  11208. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  11209. all-tags))
  11210. (tags
  11211. (replace-regexp-in-string
  11212. ;; Ignore all forbidden characters in tags.
  11213. "[^[:alnum:]_@#%]+" ":"
  11214. (if (or (eq t org-use-fast-tag-selection)
  11215. (and org-use-fast-tag-selection
  11216. (delq nil (mapcar #'cdr table))))
  11217. (org-fast-tag-selection
  11218. current-tags
  11219. inherited-tags
  11220. table
  11221. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  11222. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  11223. (org-trim (completing-read
  11224. "Tags: "
  11225. #'org-tags-completion-function
  11226. nil nil (org-make-tag-string current-tags)
  11227. 'org-tags-history)))))))
  11228. (org-set-tags tags)))))))
  11229. (defun org-align-tags (&optional all)
  11230. "Align tags in current entry.
  11231. When optional argument ALL is non-nil, align all tags in the
  11232. visible part of the buffer."
  11233. (let ((get-indent-column
  11234. (lambda ()
  11235. (let ((offset (if (bound-and-true-p org-indent-mode)
  11236. (* (1- org-indent-indentation-per-level)
  11237. (1- (org-current-level)))
  11238. 0)))
  11239. (+ org-tags-column
  11240. (if (> org-tags-column 0) (- offset) offset))))))
  11241. (if (and (not all) (org-at-heading-p))
  11242. (org--align-tags-here (funcall get-indent-column))
  11243. (save-excursion
  11244. (if all
  11245. (progn
  11246. (goto-char (point-min))
  11247. (while (re-search-forward org-tag-line-re nil t)
  11248. (org--align-tags-here (funcall get-indent-column))))
  11249. (org-back-to-heading t)
  11250. (org--align-tags-here (funcall get-indent-column)))))))
  11251. (defun org-set-tags (tags)
  11252. "Set the tags of the current entry to TAGS, replacing current tags.
  11253. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  11254. If TAGS is nil or the empty string, all tags are removed.
  11255. This function assumes point is on a headline."
  11256. (org-with-wide-buffer
  11257. (let ((tags (pcase tags
  11258. ((pred listp) tags)
  11259. ((pred stringp) (split-string (org-trim tags) ":" t))
  11260. (_ (error "Invalid tag specification: %S" tags))))
  11261. (old-tags (org-get-tags nil t))
  11262. (tags-change? nil))
  11263. (when (functionp org-tags-sort-function)
  11264. (setq tags (sort tags org-tags-sort-function)))
  11265. (setq tags-change? (not (equal tags old-tags)))
  11266. (when tags-change?
  11267. ;; Delete previous tags and any trailing white space.
  11268. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  11269. (line-end-position)))
  11270. (skip-chars-backward " \t")
  11271. (delete-region (point) (line-end-position))
  11272. ;; Deleting white spaces may break an otherwise empty headline.
  11273. ;; Re-introduce one space in this case.
  11274. (unless (org-at-heading-p) (insert " "))
  11275. (when tags
  11276. (save-excursion (insert " " (org-make-tag-string tags)))
  11277. ;; When text is being inserted on an invisible region
  11278. ;; boundary, it can be inadvertently sucked into
  11279. ;; invisibility.
  11280. (unless (org-invisible-p (line-beginning-position))
  11281. (org-flag-region (point) (line-end-position) nil 'outline))))
  11282. ;; Align tags, if any.
  11283. (when tags (org-align-tags))
  11284. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  11285. (defun org-change-tag-in-region (beg end tag off)
  11286. "Add or remove TAG for each entry in the region.
  11287. This works in the agenda, and also in an Org buffer."
  11288. (interactive
  11289. (list (region-beginning) (region-end)
  11290. (let ((org-last-tags-completion-table
  11291. (if (derived-mode-p 'org-mode)
  11292. (org--tag-add-to-alist
  11293. (org-get-buffer-tags)
  11294. (org-global-tags-completion-table))
  11295. (org-global-tags-completion-table))))
  11296. (completing-read
  11297. "Tag: " 'org-tags-completion-function nil nil nil
  11298. 'org-tags-history))
  11299. (progn
  11300. (message "[s]et or [r]emove? ")
  11301. (equal (read-char-exclusive) ?r))))
  11302. (when (fboundp 'deactivate-mark) (deactivate-mark))
  11303. (let ((agendap (equal major-mode 'org-agenda-mode))
  11304. l1 l2 m buf pos newhead (cnt 0))
  11305. (goto-char end)
  11306. (setq l2 (1- (org-current-line)))
  11307. (goto-char beg)
  11308. (setq l1 (org-current-line))
  11309. (cl-loop for l from l1 to l2 do
  11310. (org-goto-line l)
  11311. (setq m (get-text-property (point) 'org-hd-marker))
  11312. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  11313. (and agendap m))
  11314. (setq buf (if agendap (marker-buffer m) (current-buffer))
  11315. pos (if agendap m (point)))
  11316. (with-current-buffer buf
  11317. (save-excursion
  11318. (save-restriction
  11319. (goto-char pos)
  11320. (setq cnt (1+ cnt))
  11321. (org-toggle-tag tag (if off 'off 'on))
  11322. (setq newhead (org-get-heading)))))
  11323. (and agendap (org-agenda-change-all-lines newhead m))))
  11324. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  11325. (defun org-tags-completion-function (string _predicate &optional flag)
  11326. "Complete tag STRING.
  11327. FLAG specifies the type of completion operation to perform. This
  11328. function is passed as a collection function to `completing-read',
  11329. which see."
  11330. (let ((completion-ignore-case nil) ;tags are case-sensitive
  11331. (confirm (lambda (x) (stringp (car x))))
  11332. (prefix ""))
  11333. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  11334. (setq prefix (match-string 1 string))
  11335. (setq string (match-string 2 string)))
  11336. (pcase flag
  11337. (`t (all-completions string org-last-tags-completion-table confirm))
  11338. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  11339. (`nil
  11340. (pcase (try-completion string org-last-tags-completion-table confirm)
  11341. ((and completion (pred stringp))
  11342. (concat prefix
  11343. completion
  11344. (if (and org-add-colon-after-tag-completion
  11345. (assoc completion org-last-tags-completion-table))
  11346. ":"
  11347. "")))
  11348. (completion completion)))
  11349. (_ nil))))
  11350. (defun org-fast-tag-insert (kwd tags face &optional end)
  11351. "Insert KWD, and the TAGS, the latter with face FACE.
  11352. Also insert END."
  11353. (insert (format "%-12s" (concat kwd ":"))
  11354. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  11355. (or end "")))
  11356. (defun org-fast-tag-show-exit (flag)
  11357. (save-excursion
  11358. (org-goto-line 3)
  11359. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  11360. (replace-match ""))
  11361. (when flag
  11362. (end-of-line 1)
  11363. (org-move-to-column (- (window-width) 19) t)
  11364. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  11365. (defun org-set-current-tags-overlay (current prefix)
  11366. "Add an overlay to CURRENT tag with PREFIX."
  11367. (let ((s (org-make-tag-string current)))
  11368. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  11369. (org-overlay-display org-tags-overlay (concat prefix s))))
  11370. (defvar org-last-tag-selection-key nil)
  11371. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  11372. "Fast tag selection with single keys.
  11373. CURRENT is the current list of tags in the headline, INHERITED is the
  11374. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  11375. possibly with grouping information. TODO-TABLE is a similar table with
  11376. TODO keywords, should these have keys assigned to them.
  11377. If the keys are nil, a-z are automatically assigned.
  11378. Returns the new tags string, or nil to not change the current settings."
  11379. (let* ((fulltable (append table todo-table))
  11380. (maxlen (if (null fulltable) 0
  11381. (apply #'max
  11382. (mapcar (lambda (x)
  11383. (if (stringp (car x)) (string-width (car x))
  11384. 0))
  11385. fulltable))))
  11386. (buf (current-buffer))
  11387. (expert (eq org-fast-tag-selection-single-key 'expert))
  11388. (buffer-tags nil)
  11389. (fwidth (+ maxlen 3 1 3))
  11390. (ncol (/ (- (window-width) 4) fwidth))
  11391. (i-face 'org-done)
  11392. (c-face 'org-todo)
  11393. tg cnt e c char c1 c2 ntable tbl rtn
  11394. ov-start ov-end ov-prefix
  11395. (exit-after-next org-fast-tag-selection-single-key)
  11396. (done-keywords org-done-keywords)
  11397. groups ingroup intaggroup)
  11398. (save-excursion
  11399. (beginning-of-line)
  11400. (if (looking-at org-tag-line-re)
  11401. (setq ov-start (match-beginning 1)
  11402. ov-end (match-end 1)
  11403. ov-prefix "")
  11404. (setq ov-start (1- (point-at-eol))
  11405. ov-end (1+ ov-start))
  11406. (skip-chars-forward "^\n\r")
  11407. (setq ov-prefix
  11408. (concat
  11409. (buffer-substring (1- (point)) (point))
  11410. (if (> (current-column) org-tags-column)
  11411. " "
  11412. (make-string (- org-tags-column (current-column)) ?\ ))))))
  11413. (move-overlay org-tags-overlay ov-start ov-end)
  11414. (save-excursion
  11415. (save-window-excursion
  11416. (if expert
  11417. (set-buffer (get-buffer-create " *Org tags*"))
  11418. (delete-other-windows)
  11419. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  11420. (org-switch-to-buffer-other-window " *Org tags*"))
  11421. (erase-buffer)
  11422. (setq-local org-done-keywords done-keywords)
  11423. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  11424. (org-fast-tag-insert "Current" current c-face "\n\n")
  11425. (org-fast-tag-show-exit exit-after-next)
  11426. (org-set-current-tags-overlay current ov-prefix)
  11427. (setq tbl fulltable char ?a cnt 0)
  11428. (while (setq e (pop tbl))
  11429. (cond
  11430. ((eq (car e) :startgroup)
  11431. (push '() groups) (setq ingroup t)
  11432. (unless (zerop cnt)
  11433. (setq cnt 0)
  11434. (insert "\n"))
  11435. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11436. ((eq (car e) :endgroup)
  11437. (setq ingroup nil cnt 0)
  11438. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11439. ((eq (car e) :startgrouptag)
  11440. (setq intaggroup t)
  11441. (unless (zerop cnt)
  11442. (setq cnt 0)
  11443. (insert "\n"))
  11444. (insert "[ "))
  11445. ((eq (car e) :endgrouptag)
  11446. (setq intaggroup nil cnt 0)
  11447. (insert "]\n"))
  11448. ((equal e '(:newline))
  11449. (unless (zerop cnt)
  11450. (setq cnt 0)
  11451. (insert "\n")
  11452. (setq e (car tbl))
  11453. (while (equal (car tbl) '(:newline))
  11454. (insert "\n")
  11455. (setq tbl (cdr tbl)))))
  11456. ((equal e '(:grouptags)) (insert " : "))
  11457. (t
  11458. (setq tg (copy-sequence (car e)) c2 nil)
  11459. (if (cdr e)
  11460. (setq c (cdr e))
  11461. ;; automatically assign a character.
  11462. (setq c1 (string-to-char
  11463. (downcase (substring
  11464. tg (if (= (string-to-char tg) ?@) 1 0)))))
  11465. (if (or (rassoc c1 ntable) (rassoc c1 table))
  11466. (while (or (rassoc char ntable) (rassoc char table))
  11467. (setq char (1+ char)))
  11468. (setq c2 c1))
  11469. (setq c (or c2 char)))
  11470. (when ingroup (push tg (car groups)))
  11471. (setq tg (org-add-props tg nil 'face
  11472. (cond
  11473. ((not (assoc tg table))
  11474. (org-get-todo-face tg))
  11475. ((member tg current) c-face)
  11476. ((member tg inherited) i-face))))
  11477. (when (equal (caar tbl) :grouptags)
  11478. (org-add-props tg nil 'face 'org-tag-group))
  11479. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  11480. (insert "[" c "] " tg (make-string
  11481. (- fwidth 4 (length tg)) ?\ ))
  11482. (push (cons tg c) ntable)
  11483. (when (= (cl-incf cnt) ncol)
  11484. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11485. (insert "\n")
  11486. (when (or ingroup intaggroup) (insert " ")))
  11487. (setq cnt 0)))))
  11488. (setq ntable (nreverse ntable))
  11489. (insert "\n")
  11490. (goto-char (point-min))
  11491. (unless expert (org-fit-window-to-buffer))
  11492. (setq rtn
  11493. (catch 'exit
  11494. (while t
  11495. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11496. (if (not groups) "no " "")
  11497. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11498. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11499. (setq org-last-tag-selection-key c)
  11500. (cond
  11501. ((= c ?\r) (throw 'exit t))
  11502. ((= c ?!)
  11503. (setq groups (not groups))
  11504. (goto-char (point-min))
  11505. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11506. ((= c ?\C-c)
  11507. (if (not expert)
  11508. (org-fast-tag-show-exit
  11509. (setq exit-after-next (not exit-after-next)))
  11510. (setq expert nil)
  11511. (delete-other-windows)
  11512. (set-window-buffer (split-window-vertically) " *Org tags*")
  11513. (org-switch-to-buffer-other-window " *Org tags*")
  11514. (org-fit-window-to-buffer)))
  11515. ((or (= c ?\C-g)
  11516. (and (= c ?q) (not (rassoc c ntable))))
  11517. (delete-overlay org-tags-overlay)
  11518. (setq quit-flag t))
  11519. ((= c ?\ )
  11520. (setq current nil)
  11521. (when exit-after-next (setq exit-after-next 'now)))
  11522. ((= c ?\t)
  11523. (condition-case nil
  11524. (setq tg (completing-read
  11525. "Tag: "
  11526. (or buffer-tags
  11527. (with-current-buffer buf
  11528. (setq buffer-tags
  11529. (org-get-buffer-tags))))))
  11530. (quit (setq tg "")))
  11531. (when (string-match "\\S-" tg)
  11532. (cl-pushnew (list tg) buffer-tags :test #'equal)
  11533. (if (member tg current)
  11534. (setq current (delete tg current))
  11535. (push tg current)))
  11536. (when exit-after-next (setq exit-after-next 'now)))
  11537. ((setq e (rassoc c todo-table) tg (car e))
  11538. (with-current-buffer buf
  11539. (save-excursion (org-todo tg)))
  11540. (when exit-after-next (setq exit-after-next 'now)))
  11541. ((setq e (rassoc c ntable) tg (car e))
  11542. (if (member tg current)
  11543. (setq current (delete tg current))
  11544. (cl-loop for g in groups do
  11545. (when (member tg g)
  11546. (dolist (x g) (setq current (delete x current)))))
  11547. (push tg current))
  11548. (when exit-after-next (setq exit-after-next 'now))))
  11549. ;; Create a sorted list
  11550. (setq current
  11551. (sort current
  11552. (lambda (a b)
  11553. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11554. (when (eq exit-after-next 'now) (throw 'exit t))
  11555. (goto-char (point-min))
  11556. (beginning-of-line 2)
  11557. (delete-region (point) (point-at-eol))
  11558. (org-fast-tag-insert "Current" current c-face)
  11559. (org-set-current-tags-overlay current ov-prefix)
  11560. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11561. (while (re-search-forward tag-re nil t)
  11562. (let ((tag (match-string 1)))
  11563. (add-text-properties
  11564. (match-beginning 1) (match-end 1)
  11565. (list 'face
  11566. (cond
  11567. ((member tag current) c-face)
  11568. ((member tag inherited) i-face)
  11569. (t (get-text-property (match-beginning 1) '
  11570. face))))))))
  11571. (goto-char (point-min)))))
  11572. (delete-overlay org-tags-overlay)
  11573. (if rtn
  11574. (mapconcat 'identity current ":")
  11575. nil)))))
  11576. (defun org-make-tag-string (tags)
  11577. "Return string associated to TAGS.
  11578. TAGS is a list of strings."
  11579. (if (null tags) ""
  11580. (format ":%s:" (mapconcat #'identity tags ":"))))
  11581. (defun org--get-local-tags ()
  11582. "Return list of tags for the current headline.
  11583. Assume point is at the beginning of the headline."
  11584. (and (looking-at org-tag-line-re)
  11585. (split-string (match-string-no-properties 2) ":" t)))
  11586. (defun org-get-tags (&optional pos local)
  11587. "Get the list of tags specified in the current headline.
  11588. When argument POS is non-nil, retrieve tags for headline at POS.
  11589. According to `org-use-tag-inheritance', tags may be inherited
  11590. from parent headlines, and from the whole document, through
  11591. `org-file-tags'. In this case, the returned list of tags
  11592. contains tags in this order: file tags, tags inherited from
  11593. parent headlines, local tags.
  11594. However, when optional argument LOCAL is non-nil, only return
  11595. tags specified at the headline.
  11596. Inherited tags have the `inherited' text property."
  11597. (if (and org-trust-scanner-tags
  11598. (or (not pos) (eq pos (point)))
  11599. (not local))
  11600. org-scanner-tags
  11601. (org-with-point-at (or pos (point))
  11602. (unless (org-before-first-heading-p)
  11603. (org-back-to-heading t)
  11604. (let ((ltags (org--get-local-tags)) itags)
  11605. (if (or local (not org-use-tag-inheritance)) ltags
  11606. (while (org-up-heading-safe)
  11607. (setq itags (append (mapcar #'org-add-prop-inherited
  11608. (org--get-local-tags))
  11609. itags)))
  11610. (setq itags (append org-file-tags itags))
  11611. (delete-dups
  11612. (append (org-remove-uninherited-tags itags) ltags))))))))
  11613. (defun org-get-buffer-tags ()
  11614. "Get a table of all tags used in the buffer, for completion."
  11615. (org-with-point-at 1
  11616. (let (tags)
  11617. (while (re-search-forward org-tag-line-re nil t)
  11618. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11619. tags)))
  11620. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11621. ;;;; The mapping API
  11622. (defvar org-agenda-skip-comment-trees)
  11623. (defvar org-agenda-skip-function)
  11624. (defun org-map-entries (func &optional match scope &rest skip)
  11625. "Call FUNC at each headline selected by MATCH in SCOPE.
  11626. FUNC is a function or a lisp form. The function will be called without
  11627. arguments, with the cursor positioned at the beginning of the headline.
  11628. The return values of all calls to the function will be collected and
  11629. returned as a list.
  11630. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  11631. does not need to preserve point. After evaluation, the cursor will be
  11632. moved to the end of the line (presumably of the headline of the
  11633. processed entry) and search continues from there. Under some
  11634. circumstances, this may not produce the wanted results. For example,
  11635. if you have removed (e.g. archived) the current (sub)tree it could
  11636. mean that the next entry will be skipped entirely. In such cases, you
  11637. can specify the position from where search should continue by making
  11638. FUNC set the variable `org-map-continue-from' to the desired buffer
  11639. position.
  11640. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11641. Only headlines that are matched by this query will be considered during
  11642. the iteration. When MATCH is nil or t, all headlines will be
  11643. visited by the iteration.
  11644. SCOPE determines the scope of this command. It can be any of:
  11645. nil The current buffer, respecting the restriction if any
  11646. tree The subtree started with the entry at point
  11647. region The entries within the active region, if any
  11648. region-start-level
  11649. The entries within the active region, but only those at
  11650. the same level than the first one.
  11651. file The current buffer, without restriction
  11652. file-with-archives
  11653. The current buffer, and any archives associated with it
  11654. agenda All agenda files
  11655. agenda-with-archives
  11656. All agenda files with any archive files associated with them
  11657. \(file1 file2 ...)
  11658. If this is a list, all files in the list will be scanned
  11659. The remaining args are treated as settings for the skipping facilities of
  11660. the scanner. The following items can be given here:
  11661. archive skip trees with the archive tag
  11662. comment skip trees with the COMMENT keyword
  11663. function or Emacs Lisp form:
  11664. will be used as value for `org-agenda-skip-function', so
  11665. whenever the function returns a position, FUNC will not be
  11666. called for that entry and search will continue from the
  11667. position returned
  11668. If your function needs to retrieve the tags including inherited tags
  11669. at the *current* entry, you can use the value of the variable
  11670. `org-scanner-tags' which will be much faster than getting the value
  11671. with `org-get-tags'. If your function gets properties with
  11672. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11673. to t around the call to `org-entry-properties' to get the same speedup.
  11674. Note that if your function moves around to retrieve tags and properties at
  11675. a *different* entry, you cannot use these techniques."
  11676. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11677. (not (org-region-active-p)))
  11678. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11679. (org-agenda-skip-archived-trees (memq 'archive skip))
  11680. (org-agenda-skip-comment-trees (memq 'comment skip))
  11681. (org-agenda-skip-function
  11682. (car (org-delete-all '(comment archive) skip)))
  11683. (org-tags-match-list-sublevels t)
  11684. (start-level (eq scope 'region-start-level))
  11685. matcher res
  11686. org-todo-keywords-for-agenda
  11687. org-done-keywords-for-agenda
  11688. org-todo-keyword-alist-for-agenda
  11689. org-tag-alist-for-agenda
  11690. org--matcher-tags-todo-only)
  11691. (cond
  11692. ((eq match t) (setq matcher t))
  11693. ((eq match nil) (setq matcher t))
  11694. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11695. (save-excursion
  11696. (save-restriction
  11697. (cond ((eq scope 'tree)
  11698. (org-back-to-heading t)
  11699. (org-narrow-to-subtree)
  11700. (setq scope nil))
  11701. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11702. (org-region-active-p))
  11703. ;; If needed, set start-level to a string like "2"
  11704. (when start-level
  11705. (save-excursion
  11706. (goto-char (region-beginning))
  11707. (unless (org-at-heading-p) (outline-next-heading))
  11708. (setq start-level (org-current-level))))
  11709. (narrow-to-region (region-beginning)
  11710. (save-excursion
  11711. (goto-char (region-end))
  11712. (unless (and (bolp) (org-at-heading-p))
  11713. (outline-next-heading))
  11714. (point)))
  11715. (setq scope nil)))
  11716. (if (not scope)
  11717. (progn
  11718. (org-agenda-prepare-buffers
  11719. (and buffer-file-name (list buffer-file-name)))
  11720. (setq res
  11721. (org-scan-tags
  11722. func matcher org--matcher-tags-todo-only start-level)))
  11723. ;; Get the right scope
  11724. (cond
  11725. ((and scope (listp scope) (symbolp (car scope)))
  11726. (setq scope (eval scope)))
  11727. ((eq scope 'agenda)
  11728. (setq scope (org-agenda-files t)))
  11729. ((eq scope 'agenda-with-archives)
  11730. (setq scope (org-agenda-files t))
  11731. (setq scope (org-add-archive-files scope)))
  11732. ((eq scope 'file)
  11733. (setq scope (and buffer-file-name (list buffer-file-name))))
  11734. ((eq scope 'file-with-archives)
  11735. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11736. (org-agenda-prepare-buffers scope)
  11737. (dolist (file scope)
  11738. (with-current-buffer (org-find-base-buffer-visiting file)
  11739. (org-with-wide-buffer
  11740. (goto-char (point-min))
  11741. (setq res
  11742. (append
  11743. res
  11744. (org-scan-tags
  11745. func matcher org--matcher-tags-todo-only)))))))))
  11746. res)))
  11747. ;;; Properties API
  11748. (defconst org-special-properties
  11749. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11750. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11751. "The special properties valid in Org mode.
  11752. These are properties that are not defined in the property drawer,
  11753. but in some other way.")
  11754. (defconst org-default-properties
  11755. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11756. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11757. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11758. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11759. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11760. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11761. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11762. "Some properties that are used by Org mode for various purposes.
  11763. Being in this list makes sure that they are offered for completion.")
  11764. (defun org--valid-property-p (property)
  11765. "Non-nil when string PROPERTY is a valid property name."
  11766. (not
  11767. (or (equal property "")
  11768. (string-match-p "\\s-" property))))
  11769. (defun org--update-property-plist (key val props)
  11770. "Associate KEY to VAL in alist PROPS.
  11771. Modifications are made by side-effect. Return new alist."
  11772. (let* ((appending (string= (substring key -1) "+"))
  11773. (key (if appending (substring key 0 -1) key))
  11774. (old (assoc-string key props t)))
  11775. (if (not old) (cons (cons key val) props)
  11776. (setcdr old (if appending (concat (cdr old) " " val) val))
  11777. props)))
  11778. (defun org-get-property-block (&optional beg force)
  11779. "Return the (beg . end) range of the body of the property drawer.
  11780. BEG is the beginning of the current subtree or the beginning of
  11781. the document if before the first headline. If it is not given,
  11782. it will be found. If the drawer does not exist, create it if
  11783. FORCE is non-nil, or return nil."
  11784. (org-with-wide-buffer
  11785. (let ((beg (cond (beg (goto-char beg))
  11786. ((or (not (featurep 'org-inlinetask))
  11787. (org-inlinetask-in-task-p))
  11788. (org-back-to-heading-or-point-min t) (point))
  11789. (t (org-with-limited-levels
  11790. (org-back-to-heading-or-point-min t))
  11791. (point)))))
  11792. ;; Move point to its position according to its positional rules.
  11793. (cond ((org-before-first-heading-p)
  11794. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11795. (t (forward-line)
  11796. (when (looking-at-p org-planning-line-re) (forward-line))))
  11797. (cond ((looking-at org-property-drawer-re)
  11798. (forward-line)
  11799. (cons (point) (progn (goto-char (match-end 0))
  11800. (line-beginning-position))))
  11801. (force
  11802. (goto-char beg)
  11803. (org-insert-property-drawer)
  11804. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11805. (line-beginning-position))))
  11806. (cons pos pos)))))))
  11807. (defun org-at-property-block-p ()
  11808. "Return t when point is at the first line of a property drawer.
  11809. The property drawer is validated according to its positional
  11810. rules using `org-get-property-block'."
  11811. (save-excursion
  11812. (beginning-of-line)
  11813. (and (looking-at org-property-start-re)
  11814. (forward-line)
  11815. (let ((property-drawer (org-get-property-block)))
  11816. (and property-drawer
  11817. (= (point) (car property-drawer)))))))
  11818. (defun org-at-property-p ()
  11819. "Non-nil when point is inside a property drawer.
  11820. See `org-property-re' for match data, if applicable."
  11821. (save-excursion
  11822. (beginning-of-line)
  11823. (and (looking-at org-property-re)
  11824. (let ((property-drawer (save-match-data (org-get-property-block))))
  11825. (and property-drawer
  11826. (>= (point) (car property-drawer))
  11827. (< (point) (cdr property-drawer)))))))
  11828. (defun org-property-action ()
  11829. "Do an action on properties."
  11830. (interactive)
  11831. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11832. (let ((c (read-char-exclusive)))
  11833. (cl-case c
  11834. (?s (call-interactively #'org-set-property))
  11835. (?d (call-interactively #'org-delete-property))
  11836. (?D (call-interactively #'org-delete-property-globally))
  11837. (?c (call-interactively #'org-compute-property-at-point))
  11838. (otherwise (user-error "No such property action %c" c)))))
  11839. (defun org-inc-effort ()
  11840. "Increment the value of the effort property in the current entry."
  11841. (interactive)
  11842. (org-set-effort t))
  11843. (defvar org-clock-effort) ; Defined in org-clock.el.
  11844. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11845. (defun org-set-effort (&optional increment value)
  11846. "Set the effort property of the current entry.
  11847. If INCREMENT is non-nil, set the property to the next allowed
  11848. value. Otherwise, if optional argument VALUE is provided, use
  11849. it. Eventually, prompt for the new value if none of the previous
  11850. variables is set."
  11851. (interactive "P")
  11852. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11853. (current (org-entry-get nil org-effort-property))
  11854. (value
  11855. (cond
  11856. (increment
  11857. (unless allowed (user-error "Allowed effort values are not set"))
  11858. (or (cl-caadr (member (list current) allowed))
  11859. (user-error "Unknown value %S among allowed values" current)))
  11860. (value
  11861. (if (stringp value) value
  11862. (error "Invalid effort value: %S" value)))
  11863. (t
  11864. (let ((must-match
  11865. (and allowed
  11866. (not (get-text-property 0 'org-unrestricted
  11867. (caar allowed))))))
  11868. (completing-read "Effort: " allowed nil must-match))))))
  11869. (unless (equal current value)
  11870. (org-entry-put nil org-effort-property value))
  11871. (org-refresh-property '((effort . identity)
  11872. (effort-minutes . org-duration-to-minutes))
  11873. value)
  11874. (when (equal (org-get-heading t t t t)
  11875. (bound-and-true-p org-clock-current-task))
  11876. (setq org-clock-effort value)
  11877. (org-clock-update-mode-line))
  11878. (message "%s is now %s" org-effort-property value)))
  11879. (defun org-entry-properties (&optional pom which)
  11880. "Get all properties of the current entry.
  11881. When POM is a buffer position, get all properties from the entry
  11882. there instead.
  11883. This includes the TODO keyword, the tags, time strings for
  11884. deadline, scheduled, and clocking, and any additional properties
  11885. defined in the entry.
  11886. If WHICH is nil or `all', get all properties. If WHICH is
  11887. `special' or `standard', only get that subclass. If WHICH is
  11888. a string, only get that property.
  11889. Return value is an alist. Keys are properties, as upcased
  11890. strings."
  11891. (org-with-point-at pom
  11892. (when (and (derived-mode-p 'org-mode)
  11893. (org-back-to-heading-or-point-min t))
  11894. (catch 'exit
  11895. (let* ((beg (point))
  11896. (specific (and (stringp which) (upcase which)))
  11897. (which (cond ((not specific) which)
  11898. ((member specific org-special-properties) 'special)
  11899. (t 'standard)))
  11900. props)
  11901. ;; Get the special properties, like TODO and TAGS.
  11902. (when (memq which '(nil all special))
  11903. (when (or (not specific) (string= specific "CLOCKSUM"))
  11904. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11905. (when clocksum
  11906. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11907. props)))
  11908. (when specific (throw 'exit props)))
  11909. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11910. (let ((clocksumt (get-text-property (point)
  11911. :org-clock-minutes-today)))
  11912. (when clocksumt
  11913. (push (cons "CLOCKSUM_T"
  11914. (org-duration-from-minutes clocksumt))
  11915. props)))
  11916. (when specific (throw 'exit props)))
  11917. (when (or (not specific) (string= specific "ITEM"))
  11918. (let ((case-fold-search nil))
  11919. (when (looking-at org-complex-heading-regexp)
  11920. (push (cons "ITEM"
  11921. (let ((title (match-string-no-properties 4)))
  11922. (if (org-string-nw-p title)
  11923. (org-remove-tabs title)
  11924. "")))
  11925. props)))
  11926. (when specific (throw 'exit props)))
  11927. (when (or (not specific) (string= specific "TODO"))
  11928. (let ((case-fold-search nil))
  11929. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11930. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11931. (when specific (throw 'exit props)))
  11932. (when (or (not specific) (string= specific "PRIORITY"))
  11933. (push (cons "PRIORITY"
  11934. (if (looking-at org-priority-regexp)
  11935. (match-string-no-properties 2)
  11936. (char-to-string org-priority-default)))
  11937. props)
  11938. (when specific (throw 'exit props)))
  11939. (when (or (not specific) (string= specific "FILE"))
  11940. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11941. props)
  11942. (when specific (throw 'exit props)))
  11943. (when (or (not specific) (string= specific "TAGS"))
  11944. (let ((tags (org-get-tags nil t)))
  11945. (when tags
  11946. (push (cons "TAGS" (org-make-tag-string tags))
  11947. props)))
  11948. (when specific (throw 'exit props)))
  11949. (when (or (not specific) (string= specific "ALLTAGS"))
  11950. (let ((tags (org-get-tags)))
  11951. (when tags
  11952. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11953. props)))
  11954. (when specific (throw 'exit props)))
  11955. (when (or (not specific) (string= specific "BLOCKED"))
  11956. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11957. (when specific (throw 'exit props)))
  11958. (when (or (not specific)
  11959. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11960. (forward-line)
  11961. (when (looking-at-p org-planning-line-re)
  11962. (end-of-line)
  11963. (let ((bol (line-beginning-position))
  11964. ;; Backward compatibility: time keywords used to
  11965. ;; be configurable (before 8.3). Make sure we
  11966. ;; get the correct keyword.
  11967. (key-assoc `(("CLOSED" . ,org-closed-string)
  11968. ("DEADLINE" . ,org-deadline-string)
  11969. ("SCHEDULED" . ,org-scheduled-string))))
  11970. (dolist (pair (if specific (list (assoc specific key-assoc))
  11971. key-assoc))
  11972. (save-excursion
  11973. (when (search-backward (cdr pair) bol t)
  11974. (goto-char (match-end 0))
  11975. (skip-chars-forward " \t")
  11976. (and (looking-at org-ts-regexp-both)
  11977. (push (cons (car pair)
  11978. (match-string-no-properties 0))
  11979. props)))))))
  11980. (when specific (throw 'exit props)))
  11981. (when (or (not specific)
  11982. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11983. (let ((find-ts
  11984. (lambda (end ts)
  11985. ;; Fix next time-stamp before END. TS is the
  11986. ;; list of time-stamps found so far.
  11987. (let ((ts ts)
  11988. (regexp (cond
  11989. ((string= specific "TIMESTAMP")
  11990. org-ts-regexp)
  11991. ((string= specific "TIMESTAMP_IA")
  11992. org-ts-regexp-inactive)
  11993. ((assoc "TIMESTAMP_IA" ts)
  11994. org-ts-regexp)
  11995. ((assoc "TIMESTAMP" ts)
  11996. org-ts-regexp-inactive)
  11997. (t org-ts-regexp-both))))
  11998. (catch 'next
  11999. (while (re-search-forward regexp end t)
  12000. (backward-char)
  12001. (let ((object (org-element-context)))
  12002. ;; Accept to match timestamps in node
  12003. ;; properties, too.
  12004. (when (memq (org-element-type object)
  12005. '(node-property timestamp))
  12006. (let ((type
  12007. (org-element-property :type object)))
  12008. (cond
  12009. ((and (memq type '(active active-range))
  12010. (not (equal specific "TIMESTAMP_IA")))
  12011. (unless (assoc "TIMESTAMP" ts)
  12012. (push (cons "TIMESTAMP"
  12013. (org-element-property
  12014. :raw-value object))
  12015. ts)
  12016. (when specific (throw 'exit ts))))
  12017. ((and (memq type '(inactive inactive-range))
  12018. (not (string= specific "TIMESTAMP")))
  12019. (unless (assoc "TIMESTAMP_IA" ts)
  12020. (push (cons "TIMESTAMP_IA"
  12021. (org-element-property
  12022. :raw-value object))
  12023. ts)
  12024. (when specific (throw 'exit ts))))))
  12025. ;; Both timestamp types are found,
  12026. ;; move to next part.
  12027. (when (= (length ts) 2) (throw 'next ts)))))
  12028. ts)))))
  12029. (goto-char beg)
  12030. ;; First look for timestamps within headline.
  12031. (let ((ts (funcall find-ts (line-end-position) nil)))
  12032. (if (= (length ts) 2) (setq props (nconc ts props))
  12033. ;; Then find timestamps in the section, skipping
  12034. ;; planning line.
  12035. (let ((end (save-excursion (outline-next-heading))))
  12036. (forward-line)
  12037. (when (looking-at-p org-planning-line-re) (forward-line))
  12038. (setq props (nconc (funcall find-ts end ts) props))))))))
  12039. ;; Get the standard properties, like :PROP:.
  12040. (when (memq which '(nil all standard))
  12041. ;; If we are looking after a specific property, delegate
  12042. ;; to `org-entry-get', which is faster. However, make an
  12043. ;; exception for "CATEGORY", since it can be also set
  12044. ;; through keywords (i.e. #+CATEGORY).
  12045. (if (and specific (not (equal specific "CATEGORY")))
  12046. (let ((value (org-entry-get beg specific nil t)))
  12047. (throw 'exit (and value (list (cons specific value)))))
  12048. (let ((range (org-get-property-block beg)))
  12049. (when range
  12050. (let ((end (cdr range)) seen-base)
  12051. (goto-char (car range))
  12052. ;; Unlike to `org--update-property-plist', we
  12053. ;; handle the case where base values is found
  12054. ;; after its extension. We also forbid standard
  12055. ;; properties to be named as special properties.
  12056. (while (re-search-forward org-property-re end t)
  12057. (let* ((key (upcase (match-string-no-properties 2)))
  12058. (extendp (string-match-p "\\+\\'" key))
  12059. (key-base (if extendp (substring key 0 -1) key))
  12060. (value (match-string-no-properties 3)))
  12061. (cond
  12062. ((member-ignore-case key-base org-special-properties))
  12063. (extendp
  12064. (setq props
  12065. (org--update-property-plist key value props)))
  12066. ((member key seen-base))
  12067. (t (push key seen-base)
  12068. (let ((p (assoc-string key props t)))
  12069. (if p (setcdr p (concat value " " (cdr p)))
  12070. (push (cons key value) props))))))))))))
  12071. (unless (assoc "CATEGORY" props)
  12072. (push (cons "CATEGORY" (org-get-category beg)) props)
  12073. (when (string= specific "CATEGORY") (throw 'exit props)))
  12074. ;; Return value.
  12075. props)))))
  12076. (defun org--property-local-values (property literal-nil)
  12077. "Return value for PROPERTY in current entry.
  12078. Value is a list whose car is the base value for PROPERTY and cdr
  12079. a list of accumulated values. Return nil if neither is found in
  12080. the entry. Also return nil when PROPERTY is set to \"nil\",
  12081. unless LITERAL-NIL is non-nil."
  12082. (let ((range (org-get-property-block)))
  12083. (when range
  12084. (goto-char (car range))
  12085. (let* ((case-fold-search t)
  12086. (end (cdr range))
  12087. (value
  12088. ;; Base value.
  12089. (save-excursion
  12090. (let ((v (and (re-search-forward
  12091. (org-re-property property nil t) end t)
  12092. (match-string-no-properties 3))))
  12093. (list (if literal-nil v (org-not-nil v)))))))
  12094. ;; Find additional values.
  12095. (let* ((property+ (org-re-property (concat property "+") nil t)))
  12096. (while (re-search-forward property+ end t)
  12097. (push (match-string-no-properties 3) value)))
  12098. ;; Return final values.
  12099. (and (not (equal value '(nil))) (nreverse value))))))
  12100. (defun org--property-global-or-keyword-value (property literal-nil)
  12101. "Return value for PROPERTY as defined by global properties or by keyword.
  12102. Return value is a string. Return nil if property is not set
  12103. globally or by keyword. Also return nil when PROPERTY is set to
  12104. \"nil\", unless LITERAL-NIL is non-nil."
  12105. (let ((global
  12106. (cdr (or (assoc-string property org-keyword-properties t)
  12107. (assoc-string property org-global-properties t)
  12108. (assoc-string property org-global-properties-fixed t)))))
  12109. (if literal-nil global (org-not-nil global))))
  12110. (defun org-entry-get (pom property &optional inherit literal-nil)
  12111. "Get value of PROPERTY for entry or content at point-or-marker POM.
  12112. If INHERIT is non-nil and the entry does not have the property,
  12113. then also check higher levels of the hierarchy. If INHERIT is
  12114. the symbol `selective', use inheritance only if the setting in
  12115. `org-use-property-inheritance' selects PROPERTY for inheritance.
  12116. If the property is present but empty, the return value is the
  12117. empty string. If the property is not present at all, nil is
  12118. returned. In any other case, return the value as a string.
  12119. Search is case-insensitive.
  12120. If LITERAL-NIL is set, return the string value \"nil\" as
  12121. a string, do not interpret it as the list atom nil. This is used
  12122. for inheritance when a \"nil\" value can supersede a non-nil
  12123. value higher up the hierarchy."
  12124. (org-with-point-at pom
  12125. (cond
  12126. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  12127. ;; We need a special property. Use `org-entry-properties' to
  12128. ;; retrieve it, but specify the wanted property.
  12129. (cdr (assoc-string property (org-entry-properties nil property))))
  12130. ((and inherit
  12131. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  12132. (org-entry-get-with-inheritance property literal-nil))
  12133. (t
  12134. (let* ((local (org--property-local-values property literal-nil))
  12135. (value (and local (mapconcat #'identity (delq nil local) " "))))
  12136. (if literal-nil value (org-not-nil value)))))))
  12137. (defun org-property-or-variable-value (var &optional inherit)
  12138. "Check if there is a property fixing the value of VAR.
  12139. If yes, return this value. If not, return the current value of the variable."
  12140. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  12141. (if (and prop (stringp prop) (string-match "\\S-" prop))
  12142. (read prop)
  12143. (symbol-value var))))
  12144. (defun org-entry-delete (pom property)
  12145. "Delete PROPERTY from entry at point-or-marker POM.
  12146. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  12147. non-nil when a property was removed."
  12148. (org-with-point-at pom
  12149. (pcase (org-get-property-block)
  12150. (`(,begin . ,origin)
  12151. (let* ((end (copy-marker origin))
  12152. (re (org-re-property
  12153. (concat (regexp-quote property) "\\+?") t t)))
  12154. (goto-char begin)
  12155. (while (re-search-forward re end t)
  12156. (delete-region (match-beginning 0) (line-beginning-position 2)))
  12157. ;; If drawer is empty, remove it altogether.
  12158. (when (= begin end)
  12159. (delete-region (line-beginning-position 0)
  12160. (line-beginning-position 2)))
  12161. ;; Return non-nil if some property was removed.
  12162. (prog1 (/= end origin) (set-marker end nil))))
  12163. (_ nil))))
  12164. ;; Multi-values properties are properties that contain multiple values
  12165. ;; These values are assumed to be single words, separated by whitespace.
  12166. (defun org-entry-add-to-multivalued-property (pom property value)
  12167. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  12168. (let* ((old (org-entry-get pom property))
  12169. (values (and old (split-string old))))
  12170. (setq value (org-entry-protect-space value))
  12171. (unless (member value values)
  12172. (setq values (append values (list value)))
  12173. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12174. (defun org-entry-remove-from-multivalued-property (pom property value)
  12175. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  12176. (let* ((old (org-entry-get pom property))
  12177. (values (and old (split-string old))))
  12178. (setq value (org-entry-protect-space value))
  12179. (when (member value values)
  12180. (setq values (delete value values))
  12181. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12182. (defun org-entry-member-in-multivalued-property (pom property value)
  12183. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  12184. (let* ((old (org-entry-get pom property))
  12185. (values (and old (split-string old))))
  12186. (setq value (org-entry-protect-space value))
  12187. (member value values)))
  12188. (defun org-entry-get-multivalued-property (pom property)
  12189. "Return a list of values in a multivalued property."
  12190. (let* ((value (org-entry-get pom property))
  12191. (values (and value (split-string value))))
  12192. (mapcar #'org-entry-restore-space values)))
  12193. (defun org-entry-put-multivalued-property (pom property &rest values)
  12194. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  12195. VALUES should be a list of strings. Spaces will be protected."
  12196. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  12197. (let* ((value (org-entry-get pom property))
  12198. (values (and value (split-string value))))
  12199. (mapcar #'org-entry-restore-space values)))
  12200. (defun org-entry-protect-space (s)
  12201. "Protect spaces and newline in string S."
  12202. (while (string-match " " s)
  12203. (setq s (replace-match "%20" t t s)))
  12204. (while (string-match "\n" s)
  12205. (setq s (replace-match "%0A" t t s)))
  12206. s)
  12207. (defun org-entry-restore-space (s)
  12208. "Restore spaces and newline in string S."
  12209. (while (string-match "%20" s)
  12210. (setq s (replace-match " " t t s)))
  12211. (while (string-match "%0A" s)
  12212. (setq s (replace-match "\n" t t s)))
  12213. s)
  12214. (defvar org-entry-property-inherited-from (make-marker)
  12215. "Marker pointing to the entry from where a property was inherited.
  12216. Each call to `org-entry-get-with-inheritance' will set this marker to the
  12217. location of the entry where the inheritance search matched. If there was
  12218. no match, the marker will point nowhere.
  12219. Note that also `org-entry-get' calls this function, if the INHERIT flag
  12220. is set.")
  12221. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  12222. "Get PROPERTY of entry or content at point, search higher levels if needed.
  12223. The search will stop at the first ancestor which has the property defined.
  12224. If the value found is \"nil\", return nil to show that the property
  12225. should be considered as undefined (this is the meaning of nil here).
  12226. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  12227. (move-marker org-entry-property-inherited-from nil)
  12228. (org-with-wide-buffer
  12229. (let (value)
  12230. (catch 'exit
  12231. (while t
  12232. (let ((v (org--property-local-values property literal-nil)))
  12233. (when v
  12234. (setq value
  12235. (concat (mapconcat #'identity (delq nil v) " ")
  12236. (and value " ")
  12237. value)))
  12238. (cond
  12239. ((car v)
  12240. (org-back-to-heading-or-point-min t)
  12241. (move-marker org-entry-property-inherited-from (point))
  12242. (throw 'exit nil))
  12243. ((org-up-heading-or-point-min))
  12244. (t
  12245. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  12246. (cond ((not global))
  12247. (value (setq value (concat global " " value)))
  12248. (t (setq value global))))
  12249. (throw 'exit nil))))))
  12250. (if literal-nil value (org-not-nil value)))))
  12251. (defvar org-property-changed-functions nil
  12252. "Hook called when the value of a property has changed.
  12253. Each hook function should accept two arguments, the name of the property
  12254. and the new value.")
  12255. (defun org-entry-put (pom property value)
  12256. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  12257. If the value is nil, it is converted to the empty string. If it
  12258. is not a string, an error is raised. Also raise an error on
  12259. invalid property names.
  12260. PROPERTY can be any regular property (see
  12261. `org-special-properties'). It can also be \"TODO\",
  12262. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  12263. For the last two properties, VALUE may have any of the special
  12264. values \"earlier\" and \"later\". The function then increases or
  12265. decreases scheduled or deadline date by one day."
  12266. (cond ((null value) (setq value ""))
  12267. ((not (stringp value)) (error "Properties values should be strings"))
  12268. ((not (org--valid-property-p property))
  12269. (user-error "Invalid property name: \"%s\"" property)))
  12270. (org-with-point-at pom
  12271. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12272. (org-back-to-heading-or-point-min t)
  12273. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12274. (let ((beg (point)))
  12275. (cond
  12276. ((equal property "TODO")
  12277. (cond ((not (org-string-nw-p value)) (setq value 'none))
  12278. ((not (member value org-todo-keywords-1))
  12279. (user-error "\"%s\" is not a valid TODO state" value)))
  12280. (org-todo value)
  12281. (org-align-tags))
  12282. ((equal property "PRIORITY")
  12283. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  12284. (org-align-tags))
  12285. ((equal property "SCHEDULED")
  12286. (forward-line)
  12287. (if (and (looking-at-p org-planning-line-re)
  12288. (re-search-forward
  12289. org-scheduled-time-regexp (line-end-position) t))
  12290. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12291. ((string= value "later") (org-timestamp-change 1 'day))
  12292. ((string= value "") (org-schedule '(4)))
  12293. (t (org-schedule nil value)))
  12294. (if (member value '("earlier" "later" ""))
  12295. (call-interactively #'org-schedule)
  12296. (org-schedule nil value))))
  12297. ((equal property "DEADLINE")
  12298. (forward-line)
  12299. (if (and (looking-at-p org-planning-line-re)
  12300. (re-search-forward
  12301. org-deadline-time-regexp (line-end-position) t))
  12302. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12303. ((string= value "later") (org-timestamp-change 1 'day))
  12304. ((string= value "") (org-deadline '(4)))
  12305. (t (org-deadline nil value)))
  12306. (if (member value '("earlier" "later" ""))
  12307. (call-interactively #'org-deadline)
  12308. (org-deadline nil value))))
  12309. ((member property org-special-properties)
  12310. (error "The %s property cannot be set with `org-entry-put'" property))
  12311. (t
  12312. (let* ((range (org-get-property-block beg 'force))
  12313. (end (cdr range))
  12314. (case-fold-search t))
  12315. (goto-char (car range))
  12316. (if (re-search-forward (org-re-property property nil t) end t)
  12317. (progn (delete-region (match-beginning 0) (match-end 0))
  12318. (goto-char (match-beginning 0)))
  12319. (goto-char end)
  12320. (insert "\n")
  12321. (backward-char))
  12322. (insert ":" property ":")
  12323. (when value (insert " " value))
  12324. (org-indent-line)))))
  12325. (run-hook-with-args 'org-property-changed-functions property value)))
  12326. (defun org-buffer-property-keys (&optional specials defaults columns)
  12327. "Get all property keys in the current buffer.
  12328. When SPECIALS is non-nil, also list the special properties that
  12329. reflect things like tags and TODO state.
  12330. When DEFAULTS is non-nil, also include properties that has
  12331. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  12332. DESCRIPTION, LOCATION, and LOGGING and others.
  12333. When COLUMNS in non-nil, also include property names given in
  12334. COLUMN formats in the current buffer."
  12335. (let ((case-fold-search t)
  12336. (props (append
  12337. (and specials org-special-properties)
  12338. (and defaults (cons org-effort-property org-default-properties))
  12339. nil)))
  12340. (org-with-wide-buffer
  12341. (goto-char (point-min))
  12342. (while (re-search-forward org-property-start-re nil t)
  12343. (catch :skip
  12344. (let ((range (org-get-property-block)))
  12345. (unless range (throw :skip nil))
  12346. (goto-char (car range))
  12347. (let ((begin (car range))
  12348. (end (cdr range)))
  12349. ;; Make sure that found property block is not located
  12350. ;; before current point, as it would generate an infloop.
  12351. ;; It can happen, for example, in the following
  12352. ;; situation:
  12353. ;;
  12354. ;; * Headline
  12355. ;; :PROPERTIES:
  12356. ;; ...
  12357. ;; :END:
  12358. ;; *************** Inlinetask
  12359. ;; #+BEGIN_EXAMPLE
  12360. ;; :PROPERTIES:
  12361. ;; #+END_EXAMPLE
  12362. ;;
  12363. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  12364. (while (< (point) end)
  12365. (let ((p (progn (looking-at org-property-re)
  12366. (match-string-no-properties 2))))
  12367. ;; Only add true property name, not extension symbol.
  12368. (push (if (not (string-match-p "\\+\\'" p)) p
  12369. (substring p 0 -1))
  12370. props))
  12371. (forward-line))))
  12372. (outline-next-heading)))
  12373. (when columns
  12374. (goto-char (point-min))
  12375. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  12376. (let ((element (org-element-at-point)))
  12377. (when (memq (org-element-type element) '(keyword node-property))
  12378. (let ((value (org-element-property :value element))
  12379. (start 0))
  12380. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  12381. \\(?:{[^}]+}\\)?"
  12382. value start)
  12383. (setq start (match-end 0))
  12384. (let ((p (match-string-no-properties 1 value)))
  12385. (unless (member-ignore-case p org-special-properties)
  12386. (push p props))))))))))
  12387. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  12388. (defun org-property-values (key)
  12389. "List all non-nil values of property KEY in current buffer."
  12390. (org-with-wide-buffer
  12391. (goto-char (point-min))
  12392. (let ((case-fold-search t)
  12393. (re (org-re-property key))
  12394. values)
  12395. (while (re-search-forward re nil t)
  12396. (push (org-entry-get (point) key) values))
  12397. (delete-dups values))))
  12398. (defun org-insert-property-drawer ()
  12399. "Insert a property drawer into the current entry.
  12400. Do nothing if the drawer already exists. The newly created
  12401. drawer is immediately hidden."
  12402. (org-with-wide-buffer
  12403. ;; Set point to the position where the drawer should be inserted.
  12404. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12405. (org-back-to-heading-or-point-min t)
  12406. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12407. (if (org-before-first-heading-p)
  12408. (while (and (org-at-comment-p) (bolp)) (forward-line))
  12409. (progn
  12410. (forward-line)
  12411. (when (looking-at-p org-planning-line-re) (forward-line))))
  12412. (unless (looking-at-p org-property-drawer-re)
  12413. ;; Make sure we start editing a line from current entry, not from
  12414. ;; next one. It prevents extending text properties or overlays
  12415. ;; belonging to the latter.
  12416. (when (and (bolp) (> (point) (point-min))) (backward-char))
  12417. (let ((begin (if (bobp) (point) (1+ (point))))
  12418. (inhibit-read-only t))
  12419. (unless (bobp) (insert "\n"))
  12420. (insert ":PROPERTIES:\n:END:")
  12421. (org-flag-drawer t nil (line-end-position 0) (point))
  12422. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  12423. (org-indent-region begin (point))))))
  12424. (defun org-insert-drawer (&optional arg drawer)
  12425. "Insert a drawer at point.
  12426. When optional argument ARG is non-nil, insert a property drawer.
  12427. Optional argument DRAWER, when non-nil, is a string representing
  12428. drawer's name. Otherwise, the user is prompted for a name.
  12429. If a region is active, insert the drawer around that region
  12430. instead.
  12431. Point is left between drawer's boundaries."
  12432. (interactive "P")
  12433. (let* ((drawer (if arg "PROPERTIES"
  12434. (or drawer (read-from-minibuffer "Drawer: ")))))
  12435. (cond
  12436. ;; With C-u, fall back on `org-insert-property-drawer'
  12437. (arg (org-insert-property-drawer))
  12438. ;; Check validity of suggested drawer's name.
  12439. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  12440. (user-error "Invalid drawer name"))
  12441. ;; With an active region, insert a drawer at point.
  12442. ((not (org-region-active-p))
  12443. (progn
  12444. (unless (bolp) (insert "\n"))
  12445. (insert (format ":%s:\n\n:END:\n" drawer))
  12446. (forward-line -2)))
  12447. ;; Otherwise, insert the drawer at point
  12448. (t
  12449. (let ((rbeg (region-beginning))
  12450. (rend (copy-marker (region-end))))
  12451. (unwind-protect
  12452. (progn
  12453. (goto-char rbeg)
  12454. (beginning-of-line)
  12455. (when (save-excursion
  12456. (re-search-forward org-outline-regexp-bol rend t))
  12457. (user-error "Drawers cannot contain headlines"))
  12458. ;; Position point at the beginning of the first
  12459. ;; non-blank line in region. Insert drawer's opening
  12460. ;; there, then indent it.
  12461. (org-skip-whitespace)
  12462. (beginning-of-line)
  12463. (insert ":" drawer ":\n")
  12464. (forward-line -1)
  12465. (indent-for-tab-command)
  12466. ;; Move point to the beginning of the first blank line
  12467. ;; after the last non-blank line in region. Insert
  12468. ;; drawer's closing, then indent it.
  12469. (goto-char rend)
  12470. (skip-chars-backward " \r\t\n")
  12471. (insert "\n:END:")
  12472. (deactivate-mark t)
  12473. (indent-for-tab-command)
  12474. (unless (eolp) (insert "\n")))
  12475. ;; Clear marker, whatever the outcome of insertion is.
  12476. (set-marker rend nil)))))))
  12477. (defvar org-property-set-functions-alist nil
  12478. "Property set function alist.
  12479. Each entry should have the following format:
  12480. (PROPERTY . READ-FUNCTION)
  12481. The read function will be called with the same argument as
  12482. `org-completing-read'.")
  12483. (defun org-set-property-function (property)
  12484. "Get the function that should be used to set PROPERTY.
  12485. This is computed according to `org-property-set-functions-alist'."
  12486. (or (cdr (assoc property org-property-set-functions-alist))
  12487. 'org-completing-read))
  12488. (defun org-read-property-value (property &optional pom)
  12489. "Read value for PROPERTY, as a string.
  12490. When optional argument POM is non-nil, completion uses additional
  12491. information, i.e., allowed or existing values at point or marker
  12492. POM."
  12493. (let* ((completion-ignore-case t)
  12494. (allowed
  12495. (or (org-property-get-allowed-values nil property 'table)
  12496. (and pom (org-property-get-allowed-values pom property 'table))))
  12497. (current (org-entry-get nil property))
  12498. (prompt (format "%s value%s: "
  12499. property
  12500. (if (org-string-nw-p current)
  12501. (format " [%s]" current)
  12502. "")))
  12503. (set-function (org-set-property-function property)))
  12504. (org-trim
  12505. (if allowed
  12506. (funcall set-function
  12507. prompt allowed nil
  12508. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  12509. (let ((all (mapcar #'list
  12510. (append (org-property-values property)
  12511. (and pom
  12512. (org-with-point-at pom
  12513. (org-property-values property)))))))
  12514. (funcall set-function prompt all nil nil "" nil current))))))
  12515. (defvar org-last-set-property nil)
  12516. (defvar org-last-set-property-value nil)
  12517. (defun org-read-property-name ()
  12518. "Read a property name."
  12519. (let ((completion-ignore-case t)
  12520. (default-prop (or (and (org-at-property-p)
  12521. (match-string-no-properties 2))
  12522. org-last-set-property)))
  12523. (org-completing-read
  12524. (concat "Property"
  12525. (if default-prop (concat " [" default-prop "]") "")
  12526. ": ")
  12527. (mapcar #'list (org-buffer-property-keys nil t t))
  12528. nil nil nil nil default-prop)))
  12529. (defun org-set-property-and-value (use-last)
  12530. "Allow to set [PROPERTY]: [value] direction from prompt.
  12531. When use-default, don't even ask, just use the last
  12532. \"[PROPERTY]: [value]\" string from the history."
  12533. (interactive "P")
  12534. (let* ((completion-ignore-case t)
  12535. (pv (or (and use-last org-last-set-property-value)
  12536. (org-completing-read
  12537. "Enter a \"[Property]: [value]\" pair: "
  12538. nil nil nil nil nil
  12539. org-last-set-property-value)))
  12540. prop val)
  12541. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12542. (setq prop (match-string 1 pv)
  12543. val (match-string 2 pv))
  12544. (org-set-property prop val))))
  12545. (defun org-set-property (property value)
  12546. "In the current entry, set PROPERTY to VALUE.
  12547. When called interactively, this will prompt for a property name, offering
  12548. completion on existing and default properties. And then it will prompt
  12549. for a value, offering completion either on allowed values (via an inherited
  12550. xxx_ALL property) or on existing values in other instances of this property
  12551. in the current file.
  12552. Throw an error when trying to set a property with an invalid name."
  12553. (interactive (list nil nil))
  12554. (let ((property (or property (org-read-property-name))))
  12555. ;; `org-entry-put' also makes the following check, but this one
  12556. ;; avoids polluting `org-last-set-property' and
  12557. ;; `org-last-set-property-value' needlessly.
  12558. (unless (org--valid-property-p property)
  12559. (user-error "Invalid property name: \"%s\"" property))
  12560. (let ((value (or value (org-read-property-value property)))
  12561. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12562. (setq org-last-set-property property)
  12563. (setq org-last-set-property-value (concat property ": " value))
  12564. ;; Possibly postprocess the inserted value:
  12565. (when fn (setq value (funcall fn value)))
  12566. (unless (equal (org-entry-get nil property) value)
  12567. (org-entry-put nil property value)))))
  12568. (defun org-find-property (property &optional value)
  12569. "Find first entry in buffer that sets PROPERTY.
  12570. When optional argument VALUE is non-nil, only consider an entry
  12571. if it contains PROPERTY set to this value. If PROPERTY should be
  12572. explicitly set to nil, use string \"nil\" for VALUE.
  12573. Return position where the entry begins, or nil if there is no
  12574. such entry. If narrowing is in effect, only search the visible
  12575. part of the buffer."
  12576. (save-excursion
  12577. (goto-char (point-min))
  12578. (let ((case-fold-search t)
  12579. (re (org-re-property property nil (not value) value)))
  12580. (catch 'exit
  12581. (while (re-search-forward re nil t)
  12582. (when (if value (org-at-property-p)
  12583. (org-entry-get (point) property nil t))
  12584. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  12585. (defun org-delete-property (property)
  12586. "In the current entry, delete PROPERTY."
  12587. (interactive
  12588. (let* ((completion-ignore-case t)
  12589. (cat (org-entry-get (point) "CATEGORY"))
  12590. (props0 (org-entry-properties nil 'standard))
  12591. (props (if cat props0
  12592. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12593. (prop (if (< 1 (length props))
  12594. (completing-read "Property: " props nil t)
  12595. (caar props))))
  12596. (list prop)))
  12597. (if (not property)
  12598. (message "No property to delete in this entry")
  12599. (org-entry-delete nil property)
  12600. (message "Property \"%s\" deleted" property)))
  12601. (defun org-delete-property-globally (property)
  12602. "Remove PROPERTY globally, from all entries.
  12603. This function ignores narrowing, if any."
  12604. (interactive
  12605. (let* ((completion-ignore-case t)
  12606. (prop (completing-read
  12607. "Globally remove property: "
  12608. (mapcar #'list (org-buffer-property-keys)))))
  12609. (list prop)))
  12610. (org-with-wide-buffer
  12611. (goto-char (point-min))
  12612. (let ((count 0)
  12613. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12614. (while (re-search-forward re nil t)
  12615. (when (org-entry-delete (point) property) (cl-incf count)))
  12616. (message "Property \"%s\" removed from %d entries" property count))))
  12617. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12618. (defun org-compute-property-at-point ()
  12619. "Compute the property at point.
  12620. This looks for an enclosing column format, extracts the operator and
  12621. then applies it to the property in the column format's scope."
  12622. (interactive)
  12623. (unless (org-at-property-p)
  12624. (user-error "Not at a property"))
  12625. (let ((prop (match-string-no-properties 2)))
  12626. (org-columns-get-format-and-top-level)
  12627. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12628. (user-error "No operator defined for property %s" prop))
  12629. (org-columns-compute prop)))
  12630. (defvar org-property-allowed-value-functions nil
  12631. "Hook for functions supplying allowed values for a specific property.
  12632. The functions must take a single argument, the name of the property, and
  12633. return a flat list of allowed values. If \":ETC\" is one of
  12634. the values, this means that these values are intended as defaults for
  12635. completion, but that other values should be allowed too.
  12636. The functions must return nil if they are not responsible for this
  12637. property.")
  12638. (defun org-property-get-allowed-values (pom property &optional table)
  12639. "Get allowed values for the property PROPERTY.
  12640. When TABLE is non-nil, return an alist that can directly be used for
  12641. completion."
  12642. (let (vals)
  12643. (cond
  12644. ((equal property "TODO")
  12645. (setq vals (org-with-point-at pom
  12646. (append org-todo-keywords-1 '("")))))
  12647. ((equal property "PRIORITY")
  12648. (let ((n org-priority-lowest))
  12649. (while (>= n org-priority-highest)
  12650. (push (char-to-string n) vals)
  12651. (setq n (1- n)))))
  12652. ((equal property "CATEGORY"))
  12653. ((member property org-special-properties))
  12654. ((setq vals (run-hook-with-args-until-success
  12655. 'org-property-allowed-value-functions property)))
  12656. (t
  12657. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12658. (when (and vals (string-match "\\S-" vals))
  12659. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12660. (setq vals (mapcar (lambda (x)
  12661. (cond ((stringp x) x)
  12662. ((numberp x) (number-to-string x))
  12663. ((symbolp x) (symbol-name x))
  12664. (t "???")))
  12665. vals)))))
  12666. (when (member ":ETC" vals)
  12667. (setq vals (remove ":ETC" vals))
  12668. (org-add-props (car vals) '(org-unrestricted t)))
  12669. (if table (mapcar 'list vals) vals)))
  12670. (defun org-property-previous-allowed-value (&optional _previous)
  12671. "Switch to the next allowed value for this property."
  12672. (interactive)
  12673. (org-property-next-allowed-value t))
  12674. (defun org-property-next-allowed-value (&optional previous)
  12675. "Switch to the next allowed value for this property."
  12676. (interactive)
  12677. (unless (org-at-property-p)
  12678. (user-error "Not at a property"))
  12679. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12680. (key (match-string 2))
  12681. (value (match-string 3))
  12682. (allowed (or (org-property-get-allowed-values (point) key)
  12683. (and (member value '("[ ]" "[-]" "[X]"))
  12684. '("[ ]" "[X]"))))
  12685. (heading (save-match-data (nth 4 (org-heading-components))))
  12686. nval)
  12687. (unless allowed
  12688. (user-error "Allowed values for this property have not been defined"))
  12689. (when previous (setq allowed (reverse allowed)))
  12690. (when (member value allowed)
  12691. (setq nval (car (cdr (member value allowed)))))
  12692. (setq nval (or nval (car allowed)))
  12693. (when (equal nval value)
  12694. (user-error "Only one allowed value for this property"))
  12695. (org-at-property-p)
  12696. (replace-match (concat " :" key ": " nval) t t)
  12697. (org-indent-line)
  12698. (beginning-of-line 1)
  12699. (skip-chars-forward " \t")
  12700. (when (equal prop org-effort-property)
  12701. (org-refresh-property
  12702. '((effort . identity)
  12703. (effort-minutes . org-duration-to-minutes))
  12704. nval)
  12705. (when (string= org-clock-current-task heading)
  12706. (setq org-clock-effort nval)
  12707. (org-clock-update-mode-line)))
  12708. (run-hook-with-args 'org-property-changed-functions key nval)))
  12709. (defun org-find-olp (path &optional this-buffer)
  12710. "Return a marker pointing to the entry at outline path OLP.
  12711. If anything goes wrong, throw an error.
  12712. You can wrap this call to catch the error like this:
  12713. (condition-case msg
  12714. (org-mobile-locate-entry (match-string 4))
  12715. (error (nth 1 msg)))
  12716. The return value will then be either a string with the error message,
  12717. or a marker if everything is OK.
  12718. If THIS-BUFFER is set, the outline path does not contain a file,
  12719. only headings."
  12720. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12721. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12722. (level 1)
  12723. (lmin 1)
  12724. (lmax 1)
  12725. end found flevel)
  12726. (unless buffer (error "File not found :%s" file))
  12727. (with-current-buffer buffer
  12728. (unless (derived-mode-p 'org-mode)
  12729. (error "Buffer %s needs to be in Org mode" buffer))
  12730. (org-with-wide-buffer
  12731. (goto-char (point-min))
  12732. (dolist (heading path)
  12733. (let ((re (format org-complex-heading-regexp-format
  12734. (regexp-quote heading)))
  12735. (cnt 0))
  12736. (while (re-search-forward re end t)
  12737. (setq level (- (match-end 1) (match-beginning 1)))
  12738. (when (and (>= level lmin) (<= level lmax))
  12739. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12740. (when (= cnt 0)
  12741. (error "Heading not found on level %d: %s" lmax heading))
  12742. (when (> cnt 1)
  12743. (error "Heading not unique on level %d: %s" lmax heading))
  12744. (goto-char found)
  12745. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12746. (setq end (save-excursion (org-end-of-subtree t t)))))
  12747. (when (org-at-heading-p)
  12748. (point-marker))))))
  12749. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12750. "Find node HEADING in BUFFER.
  12751. Return a marker to the heading if it was found, or nil if not.
  12752. If POS-ONLY is set, return just the position instead of a marker.
  12753. The heading text must match exact, but it may have a TODO keyword,
  12754. a priority cookie and tags in the standard locations."
  12755. (with-current-buffer (or buffer (current-buffer))
  12756. (org-with-wide-buffer
  12757. (goto-char (point-min))
  12758. (let (case-fold-search)
  12759. (when (re-search-forward
  12760. (format org-complex-heading-regexp-format
  12761. (regexp-quote heading)) nil t)
  12762. (if pos-only
  12763. (match-beginning 0)
  12764. (move-marker (make-marker) (match-beginning 0))))))))
  12765. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12766. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12767. When the target headline is found, return a marker to this location."
  12768. (let ((files (directory-files (or dir default-directory)
  12769. t "\\`[^.#].*\\.org\\'"))
  12770. visiting m buffer)
  12771. (catch 'found
  12772. (dolist (file files)
  12773. (message "trying %s" file)
  12774. (setq visiting (org-find-base-buffer-visiting file))
  12775. (setq buffer (or visiting (find-file-noselect file)))
  12776. (setq m (org-find-exact-headline-in-buffer
  12777. heading buffer))
  12778. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12779. (and m (throw 'found m))))))
  12780. (defun org-find-entry-with-id (ident)
  12781. "Locate the entry that contains the ID property with exact value IDENT.
  12782. IDENT can be a string, a symbol or a number, this function will search for
  12783. the string representation of it.
  12784. Return the position where this entry starts, or nil if there is no such entry."
  12785. (interactive "sID: ")
  12786. (let ((id (cond
  12787. ((stringp ident) ident)
  12788. ((symbolp ident) (symbol-name ident))
  12789. ((numberp ident) (number-to-string ident))
  12790. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12791. (org-with-wide-buffer (org-find-property "ID" id))))
  12792. ;;;; Timestamps
  12793. (defvar org-last-changed-timestamp nil)
  12794. (defvar org-last-inserted-timestamp nil
  12795. "The last time stamp inserted with `org-insert-time-stamp'.")
  12796. (defun org-time-stamp (arg &optional inactive)
  12797. "Prompt for a date/time and insert a time stamp.
  12798. If the user specifies a time like HH:MM or if this command is
  12799. called with at least one prefix argument, the time stamp contains
  12800. the date and the time. Otherwise, only the date is included.
  12801. All parts of a date not specified by the user are filled in from
  12802. the timestamp at point, if any, or the current date/time
  12803. otherwise.
  12804. If there is already a timestamp at the cursor, it is replaced.
  12805. With two universal prefix arguments, insert an active timestamp
  12806. with the current time without prompting the user.
  12807. When called from lisp, the timestamp is inactive if INACTIVE is
  12808. non-nil."
  12809. (interactive "P")
  12810. (let* ((ts (cond
  12811. ((org-at-date-range-p t)
  12812. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12813. ((org-at-timestamp-p 'lax) (match-string 0))))
  12814. ;; Default time is either the timestamp at point or today.
  12815. ;; When entering a range, only the range start is considered.
  12816. (default-time (and ts (org-time-string-to-time ts)))
  12817. (default-input (and ts (org-get-compact-tod ts)))
  12818. (repeater (and ts
  12819. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12820. (match-string 0 ts)))
  12821. org-time-was-given
  12822. org-end-time-was-given
  12823. (time
  12824. (if (equal arg '(16)) (current-time)
  12825. ;; Preserve `this-command' and `last-command'.
  12826. (let ((this-command this-command)
  12827. (last-command last-command))
  12828. (org-read-date
  12829. arg 'totime nil nil default-time default-input
  12830. inactive)))))
  12831. (cond
  12832. ((and ts
  12833. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12834. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12835. (insert "--")
  12836. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12837. (ts
  12838. ;; Make sure we're on a timestamp. When in the middle of a date
  12839. ;; range, move arbitrarily to range end.
  12840. (unless (org-at-timestamp-p 'lax)
  12841. (skip-chars-forward "-")
  12842. (org-at-timestamp-p 'lax))
  12843. (replace-match "")
  12844. (setq org-last-changed-timestamp
  12845. (org-insert-time-stamp
  12846. time (or org-time-was-given arg)
  12847. inactive nil nil (list org-end-time-was-given)))
  12848. (when repeater
  12849. (backward-char)
  12850. (insert " " repeater)
  12851. (setq org-last-changed-timestamp
  12852. (concat (substring org-last-inserted-timestamp 0 -1)
  12853. " " repeater ">")))
  12854. (message "Timestamp updated"))
  12855. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12856. (t (org-insert-time-stamp
  12857. time (or org-time-was-given arg) inactive nil nil
  12858. (list org-end-time-was-given))))))
  12859. ;; FIXME: can we use this for something else, like computing time differences?
  12860. (defun org-get-compact-tod (s)
  12861. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12862. (let* ((t1 (match-string 1 s))
  12863. (h1 (string-to-number (match-string 2 s)))
  12864. (m1 (string-to-number (match-string 3 s)))
  12865. (t2 (and (match-end 4) (match-string 5 s)))
  12866. (h2 (and t2 (string-to-number (match-string 6 s))))
  12867. (m2 (and t2 (string-to-number (match-string 7 s))))
  12868. dh dm)
  12869. (if (not t2)
  12870. t1
  12871. (setq dh (- h2 h1) dm (- m2 m1))
  12872. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12873. (concat t1 "+" (number-to-string dh)
  12874. (and (/= 0 dm) (format ":%02d" dm)))))))
  12875. (defun org-time-stamp-inactive (&optional arg)
  12876. "Insert an inactive time stamp.
  12877. An inactive time stamp is enclosed in square brackets instead of angle
  12878. brackets. It is inactive in the sense that it does not trigger agenda entries,
  12879. does not link to the calendar and cannot be changed with the S-cursor keys.
  12880. So these are more for recording a certain time/date.
  12881. If the user specifies a time like HH:MM or if this command is called with
  12882. at least one prefix argument, the time stamp contains the date and the time.
  12883. Otherwise, only the date is included.
  12884. When called with two universal prefix arguments, insert an active time stamp
  12885. with the current time without prompting the user."
  12886. (interactive "P")
  12887. (org-time-stamp arg 'inactive))
  12888. (defvar org-date-ovl (make-overlay 1 1))
  12889. (overlay-put org-date-ovl 'face 'org-date-selected)
  12890. (delete-overlay org-date-ovl)
  12891. (defvar org-ans1) ; dynamically scoped parameter
  12892. (defvar org-ans2) ; dynamically scoped parameter
  12893. (defvar org-plain-time-of-day-regexp) ; defined below
  12894. (defvar org-overriding-default-time nil) ; dynamically scoped
  12895. (defvar org-read-date-overlay nil)
  12896. (defvar org-read-date-history nil)
  12897. (defvar org-read-date-final-answer nil)
  12898. (defvar org-read-date-analyze-futurep nil)
  12899. (defvar org-read-date-analyze-forced-year nil)
  12900. (defvar org-read-date-inactive)
  12901. (defvar org-def)
  12902. (defvar org-defdecode)
  12903. (defvar org-with-time)
  12904. (defvar calendar-setup) ; Dynamically scoped.
  12905. (defun org-read-date (&optional with-time to-time from-string prompt
  12906. default-time default-input inactive)
  12907. "Read a date, possibly a time, and make things smooth for the user.
  12908. The prompt will suggest to enter an ISO date, but you can also enter anything
  12909. which will at least partially be understood by `parse-time-string'.
  12910. Unrecognized parts of the date will default to the current day, month, year,
  12911. hour and minute. If this command is called to replace a timestamp at point,
  12912. or to enter the second timestamp of a range, the default time is taken
  12913. from the existing stamp. Furthermore, the command prefers the future,
  12914. so if you are giving a date where the year is not given, and the day-month
  12915. combination is already past in the current year, it will assume you
  12916. mean next year. For details, see the manual. A few examples:
  12917. 3-2-5 --> 2003-02-05
  12918. feb 15 --> currentyear-02-15
  12919. 2/15 --> currentyear-02-15
  12920. sep 12 9 --> 2009-09-12
  12921. 12:45 --> today 12:45
  12922. 22 sept 0:34 --> currentyear-09-22 0:34
  12923. 12 --> currentyear-currentmonth-12
  12924. Fri --> nearest Friday after today
  12925. -Tue --> last Tuesday
  12926. etc.
  12927. Furthermore you can specify a relative date by giving, as the *first* thing
  12928. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12929. change in days weeks, months, years.
  12930. With a single plus or minus, the date is relative to today. With a double
  12931. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12932. +4d --> four days from today
  12933. +4 --> same as above
  12934. +2w --> two weeks from today
  12935. ++5 --> five days from default date
  12936. The function understands only English month and weekday abbreviations.
  12937. While prompting, a calendar is popped up - you can also select the
  12938. date with the mouse (button 1). The calendar shows a period of three
  12939. months. To scroll it to other months, use the keys `>' and `<'.
  12940. If you don't like the calendar, turn it off with
  12941. (setq org-read-date-popup-calendar nil)
  12942. With optional argument TO-TIME, the date will immediately be converted
  12943. to an internal time.
  12944. With an optional argument WITH-TIME, the prompt will suggest to
  12945. also insert a time. Note that when WITH-TIME is not set, you can
  12946. still enter a time, and this function will inform the calling routine
  12947. about this change. The calling routine may then choose to change the
  12948. format used to insert the time stamp into the buffer to include the time.
  12949. With optional argument FROM-STRING, read from this string instead from
  12950. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12951. the time/date that is used for everything that is not specified by the
  12952. user."
  12953. (require 'parse-time)
  12954. (let* ((org-with-time with-time)
  12955. (org-time-stamp-rounding-minutes
  12956. (if (equal org-with-time '(16))
  12957. '(0 0)
  12958. org-time-stamp-rounding-minutes))
  12959. (ct (org-current-time))
  12960. (org-def (or org-overriding-default-time default-time ct))
  12961. (org-defdecode (decode-time org-def))
  12962. (cur-frame (selected-frame))
  12963. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12964. (calendar-setup
  12965. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12966. (calendar-move-hook nil)
  12967. (calendar-view-diary-initially-flag nil)
  12968. (calendar-view-holidays-initially-flag nil)
  12969. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12970. ;; Rationalize `org-def' and `org-defdecode', if required.
  12971. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12972. (setf (nth 2 org-defdecode) -1)
  12973. (setf (nth 1 org-defdecode) 59)
  12974. (setq org-def (apply #'encode-time org-defdecode))
  12975. (setq org-defdecode (decode-time org-def)))
  12976. (let* ((timestr (format-time-string
  12977. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12978. org-def))
  12979. (prompt (concat (if prompt (concat prompt " ") "")
  12980. (format "Date+time [%s]: " timestr))))
  12981. (cond
  12982. (from-string (setq ans from-string))
  12983. (org-read-date-popup-calendar
  12984. (save-excursion
  12985. (save-window-excursion
  12986. (calendar)
  12987. (when (eq calendar-setup 'calendar-only)
  12988. (setq cal-frame
  12989. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12990. (select-frame cal-frame))
  12991. (org-eval-in-calendar '(setq cursor-type nil) t)
  12992. (unwind-protect
  12993. (progn
  12994. (calendar-forward-day (- (time-to-days org-def)
  12995. (calendar-absolute-from-gregorian
  12996. (calendar-current-date))))
  12997. (org-eval-in-calendar nil t)
  12998. (let* ((old-map (current-local-map))
  12999. (map (copy-keymap calendar-mode-map))
  13000. (minibuffer-local-map
  13001. (copy-keymap org-read-date-minibuffer-local-map)))
  13002. (org-defkey map (kbd "RET") 'org-calendar-select)
  13003. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  13004. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  13005. (unwind-protect
  13006. (progn
  13007. (use-local-map map)
  13008. (setq org-read-date-inactive inactive)
  13009. (add-hook 'post-command-hook 'org-read-date-display)
  13010. (setq org-ans0
  13011. (read-string prompt
  13012. default-input
  13013. 'org-read-date-history
  13014. nil))
  13015. ;; org-ans0: from prompt
  13016. ;; org-ans1: from mouse click
  13017. ;; org-ans2: from calendar motion
  13018. (setq ans
  13019. (concat org-ans0 " " (or org-ans1 org-ans2))))
  13020. (remove-hook 'post-command-hook 'org-read-date-display)
  13021. (use-local-map old-map)
  13022. (when org-read-date-overlay
  13023. (delete-overlay org-read-date-overlay)
  13024. (setq org-read-date-overlay nil)))))
  13025. (bury-buffer "*Calendar*")
  13026. (when cal-frame
  13027. (delete-frame cal-frame)
  13028. (select-frame-set-input-focus cur-frame))))))
  13029. (t ; Naked prompt only
  13030. (unwind-protect
  13031. (setq ans (read-string prompt default-input
  13032. 'org-read-date-history timestr))
  13033. (when org-read-date-overlay
  13034. (delete-overlay org-read-date-overlay)
  13035. (setq org-read-date-overlay nil))))))
  13036. (setq final (org-read-date-analyze ans org-def org-defdecode))
  13037. (when org-read-date-analyze-forced-year
  13038. (message "Year was forced into %s"
  13039. (if org-read-date-force-compatible-dates
  13040. "compatible range (1970-2037)"
  13041. "range representable on this machine"))
  13042. (ding))
  13043. (setq final (apply #'encode-time final))
  13044. (setq org-read-date-final-answer ans)
  13045. (if to-time
  13046. final
  13047. ;; This round-trip gets rid of 34th of August and stuff like that....
  13048. (setq final (decode-time final))
  13049. (if (and (boundp 'org-time-was-given) org-time-was-given)
  13050. (format "%04d-%02d-%02d %02d:%02d"
  13051. (nth 5 final) (nth 4 final) (nth 3 final)
  13052. (nth 2 final) (nth 1 final))
  13053. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  13054. (defun org-read-date-display ()
  13055. "Display the current date prompt interpretation in the minibuffer."
  13056. (when org-read-date-display-live
  13057. (when org-read-date-overlay
  13058. (delete-overlay org-read-date-overlay))
  13059. (when (minibufferp (current-buffer))
  13060. (save-excursion
  13061. (end-of-line 1)
  13062. (while (not (equal (buffer-substring
  13063. (max (point-min) (- (point) 4)) (point))
  13064. " "))
  13065. (insert " ")))
  13066. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  13067. " " (or org-ans1 org-ans2)))
  13068. (org-end-time-was-given nil)
  13069. (f (org-read-date-analyze ans org-def org-defdecode))
  13070. (fmts (if org-display-custom-times
  13071. org-time-stamp-custom-formats
  13072. org-time-stamp-formats))
  13073. (fmt (if (or org-with-time
  13074. (and (boundp 'org-time-was-given) org-time-was-given))
  13075. (cdr fmts)
  13076. (car fmts)))
  13077. (txt (format-time-string fmt (apply #'encode-time f)))
  13078. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  13079. (txt (concat "=> " txt)))
  13080. (when (and org-end-time-was-given
  13081. (string-match org-plain-time-of-day-regexp txt))
  13082. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  13083. org-end-time-was-given
  13084. (substring txt (match-end 0)))))
  13085. (when org-read-date-analyze-futurep
  13086. (setq txt (concat txt " (=>F)")))
  13087. (setq org-read-date-overlay
  13088. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  13089. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  13090. (defun org-read-date-analyze (ans def defdecode)
  13091. "Analyze the combined answer of the date prompt."
  13092. ;; FIXME: cleanup and comment
  13093. (let ((org-def def)
  13094. (org-defdecode defdecode)
  13095. (nowdecode (decode-time))
  13096. delta deltan deltaw deltadef year month day
  13097. hour minute second wday pm h2 m2 tl wday1
  13098. iso-year iso-weekday iso-week iso-date futurep kill-year)
  13099. (setq org-read-date-analyze-futurep nil
  13100. org-read-date-analyze-forced-year nil)
  13101. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  13102. (setq ans "+0"))
  13103. (when (setq delta (org-read-date-get-relative ans nil org-def))
  13104. (setq ans (replace-match "" t t ans)
  13105. deltan (car delta)
  13106. deltaw (nth 1 delta)
  13107. deltadef (nth 2 delta)))
  13108. ;; Check if there is an iso week date in there. If yes, store the
  13109. ;; info and postpone interpreting it until the rest of the parsing
  13110. ;; is done.
  13111. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  13112. (setq iso-year (when (match-end 1)
  13113. (org-small-year-to-year
  13114. (string-to-number (match-string 1 ans))))
  13115. iso-weekday (when (match-end 3)
  13116. (string-to-number (match-string 3 ans)))
  13117. iso-week (string-to-number (match-string 2 ans)))
  13118. (setq ans (replace-match "" t t ans)))
  13119. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  13120. (when (string-match
  13121. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  13122. (setq year (if (match-end 2)
  13123. (string-to-number (match-string 2 ans))
  13124. (progn (setq kill-year t)
  13125. (string-to-number (format-time-string "%Y"))))
  13126. month (string-to-number (match-string 3 ans))
  13127. day (string-to-number (match-string 4 ans)))
  13128. (setq year (org-small-year-to-year year))
  13129. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13130. t nil ans)))
  13131. ;; Help matching dotted european dates
  13132. (when (string-match
  13133. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  13134. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  13135. (setq kill-year t)
  13136. (string-to-number (format-time-string "%Y")))
  13137. day (string-to-number (match-string 1 ans))
  13138. month (string-to-number (match-string 2 ans))
  13139. ans (replace-match (format "%04d-%02d-%02d" year month day)
  13140. t nil ans)))
  13141. ;; Help matching american dates, like 5/30 or 5/30/7
  13142. (when (string-match
  13143. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  13144. (setq year (if (match-end 4)
  13145. (string-to-number (match-string 4 ans))
  13146. (progn (setq kill-year t)
  13147. (string-to-number (format-time-string "%Y"))))
  13148. month (string-to-number (match-string 1 ans))
  13149. day (string-to-number (match-string 2 ans)))
  13150. (setq year (org-small-year-to-year year))
  13151. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13152. t nil ans)))
  13153. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  13154. ;; If there is a time with am/pm, and *no* time without it, we convert
  13155. ;; so that matching will be successful.
  13156. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  13157. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  13158. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  13159. (setq hour (string-to-number (match-string 1 ans))
  13160. minute (if (match-end 3)
  13161. (string-to-number (match-string 3 ans))
  13162. 0)
  13163. pm (equal ?p
  13164. (string-to-char (downcase (match-string 4 ans)))))
  13165. (if (and (= hour 12) (not pm))
  13166. (setq hour 0)
  13167. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  13168. (setq ans (replace-match (format "%02d:%02d" hour minute)
  13169. t t ans))))
  13170. ;; Check if a time range is given as a duration
  13171. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  13172. (setq hour (string-to-number (match-string 1 ans))
  13173. h2 (+ hour (string-to-number (match-string 3 ans)))
  13174. minute (string-to-number (match-string 2 ans))
  13175. m2 (+ minute (if (match-end 5) (string-to-number
  13176. (match-string 5 ans))0)))
  13177. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  13178. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  13179. t t ans)))
  13180. ;; Check if there is a time range
  13181. (when (boundp 'org-end-time-was-given)
  13182. (setq org-time-was-given nil)
  13183. (when (and (string-match org-plain-time-of-day-regexp ans)
  13184. (match-end 8))
  13185. (setq org-end-time-was-given (match-string 8 ans))
  13186. (setq ans (concat (substring ans 0 (match-beginning 7))
  13187. (substring ans (match-end 7))))))
  13188. (setq tl (parse-time-string ans)
  13189. day (or (nth 3 tl) (nth 3 org-defdecode))
  13190. month
  13191. (cond ((nth 4 tl))
  13192. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  13193. ;; Day was specified. Make sure DAY+MONTH
  13194. ;; combination happens in the future.
  13195. ((nth 3 tl)
  13196. (setq futurep t)
  13197. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  13198. (nth 4 nowdecode)))
  13199. (t (nth 4 org-defdecode)))
  13200. year
  13201. (cond ((and (not kill-year) (nth 5 tl)))
  13202. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  13203. ;; Month was guessed in the future and is at least
  13204. ;; equal to NOWDECODE's. Fix year accordingly.
  13205. (futurep
  13206. (if (or (> month (nth 4 nowdecode))
  13207. (>= day (nth 3 nowdecode)))
  13208. (nth 5 nowdecode)
  13209. (1+ (nth 5 nowdecode))))
  13210. ;; Month was specified. Make sure MONTH+YEAR
  13211. ;; combination happens in the future.
  13212. ((nth 4 tl)
  13213. (setq futurep t)
  13214. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  13215. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  13216. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  13217. (t (nth 5 nowdecode))))
  13218. (t (nth 5 org-defdecode)))
  13219. hour (or (nth 2 tl) (nth 2 org-defdecode))
  13220. minute (or (nth 1 tl) (nth 1 org-defdecode))
  13221. second (or (nth 0 tl) 0)
  13222. wday (nth 6 tl))
  13223. (when (and (eq org-read-date-prefer-future 'time)
  13224. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  13225. (equal day (nth 3 nowdecode))
  13226. (equal month (nth 4 nowdecode))
  13227. (equal year (nth 5 nowdecode))
  13228. (nth 2 tl)
  13229. (or (< (nth 2 tl) (nth 2 nowdecode))
  13230. (and (= (nth 2 tl) (nth 2 nowdecode))
  13231. (nth 1 tl)
  13232. (< (nth 1 tl) (nth 1 nowdecode)))))
  13233. (setq day (1+ day)
  13234. futurep t))
  13235. ;; Special date definitions below
  13236. (cond
  13237. (iso-week
  13238. ;; There was an iso week
  13239. (require 'cal-iso)
  13240. (setq futurep nil)
  13241. (setq year (or iso-year year)
  13242. day (or iso-weekday wday 1)
  13243. wday nil ; to make sure that the trigger below does not match
  13244. iso-date (calendar-gregorian-from-absolute
  13245. (calendar-iso-to-absolute
  13246. (list iso-week day year))))
  13247. ; FIXME: Should we also push ISO weeks into the future?
  13248. ; (when (and org-read-date-prefer-future
  13249. ; (not iso-year)
  13250. ; (< (calendar-absolute-from-gregorian iso-date)
  13251. ; (time-to-days nil)))
  13252. ; (setq year (1+ year)
  13253. ; iso-date (calendar-gregorian-from-absolute
  13254. ; (calendar-iso-to-absolute
  13255. ; (list iso-week day year)))))
  13256. (setq month (car iso-date)
  13257. year (nth 2 iso-date)
  13258. day (nth 1 iso-date)))
  13259. (deltan
  13260. (setq futurep nil)
  13261. (unless deltadef
  13262. (let ((now (decode-time)))
  13263. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  13264. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  13265. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  13266. ((equal deltaw "m") (setq month (+ month deltan)))
  13267. ((equal deltaw "y") (setq year (+ year deltan)))))
  13268. ((and wday (not (nth 3 tl)))
  13269. ;; Weekday was given, but no day, so pick that day in the week
  13270. ;; on or after the derived date.
  13271. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  13272. (unless (equal wday wday1)
  13273. (setq day (+ day (% (- wday wday1 -7) 7))))))
  13274. (when (and (boundp 'org-time-was-given)
  13275. (nth 2 tl))
  13276. (setq org-time-was-given t))
  13277. (when (< year 100) (setq year (+ 2000 year)))
  13278. ;; Check of the date is representable
  13279. (if org-read-date-force-compatible-dates
  13280. (progn
  13281. (when (< year 1970)
  13282. (setq year 1970 org-read-date-analyze-forced-year t))
  13283. (when (> year 2037)
  13284. (setq year 2037 org-read-date-analyze-forced-year t)))
  13285. (condition-case nil
  13286. (ignore (encode-time second minute hour day month year))
  13287. (error
  13288. (setq year (nth 5 org-defdecode))
  13289. (setq org-read-date-analyze-forced-year t))))
  13290. (setq org-read-date-analyze-futurep futurep)
  13291. (list second minute hour day month year)))
  13292. (defvar parse-time-weekdays)
  13293. (defun org-read-date-get-relative (s today default)
  13294. "Check string S for special relative date string.
  13295. TODAY and DEFAULT are internal times, for today and for a default.
  13296. Return shift list (N what def-flag)
  13297. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  13298. N is the number of WHATs to shift.
  13299. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  13300. the DEFAULT date rather than TODAY."
  13301. (require 'parse-time)
  13302. (when (and
  13303. (string-match
  13304. (concat
  13305. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  13306. "\\([0-9]+\\)?"
  13307. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  13308. "\\([ \t]\\|$\\)") s)
  13309. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  13310. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  13311. (string-to-char (substring (match-string 1 s) -1))
  13312. ?+))
  13313. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  13314. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  13315. (what (if (match-end 3) (match-string 3 s) "d"))
  13316. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  13317. (date (if rel default today))
  13318. (wday (nth 6 (decode-time date)))
  13319. delta)
  13320. (if wday1
  13321. (progn
  13322. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  13323. (when (= delta 0) (setq delta 7))
  13324. (when (= dir ?-)
  13325. (setq delta (- delta 7))
  13326. (when (= delta 0) (setq delta -7)))
  13327. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  13328. (list delta "d" rel))
  13329. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  13330. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  13331. "Turn a user-specified date into the internal representation.
  13332. The internal representation needed by the calendar is (month day year).
  13333. This is a wrapper to handle the brain-dead convention in calendar that
  13334. user function argument order change dependent on argument order."
  13335. (pcase calendar-date-style
  13336. (`american (list arg1 arg2 arg3))
  13337. (`european (list arg2 arg1 arg3))
  13338. (`iso (list arg2 arg3 arg1))))
  13339. (defun org-eval-in-calendar (form &optional keepdate)
  13340. "Eval FORM in the calendar window and return to current window.
  13341. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  13342. (let ((sf (selected-frame))
  13343. (sw (selected-window)))
  13344. (select-window (get-buffer-window "*Calendar*" t))
  13345. (eval form)
  13346. (when (and (not keepdate) (calendar-cursor-to-date))
  13347. (let* ((date (calendar-cursor-to-date))
  13348. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13349. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  13350. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  13351. (select-window sw)
  13352. (select-frame-set-input-focus sf)))
  13353. (defun org-calendar-select ()
  13354. "Return to `org-read-date' with the date currently selected.
  13355. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13356. (interactive)
  13357. (when (calendar-cursor-to-date)
  13358. (let* ((date (calendar-cursor-to-date))
  13359. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13360. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13361. (when (active-minibuffer-window) (exit-minibuffer))))
  13362. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  13363. "Insert a date stamp for the date given by the internal TIME.
  13364. See `format-time-string' for the format of TIME.
  13365. WITH-HM means use the stamp format that includes the time of the day.
  13366. INACTIVE means use square brackets instead of angular ones, so that the
  13367. stamp will not contribute to the agenda.
  13368. PRE and POST are optional strings to be inserted before and after the
  13369. stamp.
  13370. The command returns the inserted time stamp."
  13371. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  13372. stamp)
  13373. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  13374. (insert-before-markers (or pre ""))
  13375. (when (listp extra)
  13376. (setq extra (car extra))
  13377. (if (and (stringp extra)
  13378. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  13379. (setq extra (format "-%02d:%02d"
  13380. (string-to-number (match-string 1 extra))
  13381. (string-to-number (match-string 2 extra))))
  13382. (setq extra nil)))
  13383. (when extra
  13384. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  13385. (insert-before-markers (setq stamp (format-time-string fmt time)))
  13386. (insert-before-markers (or post ""))
  13387. (setq org-last-inserted-timestamp stamp)))
  13388. (defun org-toggle-time-stamp-overlays ()
  13389. "Toggle the use of custom time stamp formats."
  13390. (interactive)
  13391. (setq org-display-custom-times (not org-display-custom-times))
  13392. (unless org-display-custom-times
  13393. (let ((p (point-min)) (bmp (buffer-modified-p)))
  13394. (while (setq p (next-single-property-change p 'display))
  13395. (when (and (get-text-property p 'display)
  13396. (eq (get-text-property p 'face) 'org-date))
  13397. (remove-text-properties
  13398. p (setq p (next-single-property-change p 'display))
  13399. '(display t))))
  13400. (set-buffer-modified-p bmp)))
  13401. (org-restart-font-lock)
  13402. (setq org-table-may-need-update t)
  13403. (if org-display-custom-times
  13404. (message "Time stamps are overlaid with custom format")
  13405. (message "Time stamp overlays removed")))
  13406. (defun org-display-custom-time (beg end)
  13407. "Overlay modified time stamp format over timestamp between BEG and END."
  13408. (let* ((ts (buffer-substring beg end))
  13409. t1 with-hm tf time str (off 0))
  13410. (save-match-data
  13411. (setq t1 (org-parse-time-string ts t))
  13412. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  13413. (setq off (- (match-end 0) (match-beginning 0)))))
  13414. (setq end (- end off))
  13415. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  13416. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  13417. time (org-fix-decoded-time t1)
  13418. str (org-add-props
  13419. (format-time-string
  13420. (substring tf 1 -1) (apply 'encode-time time))
  13421. nil 'mouse-face 'highlight))
  13422. (put-text-property beg end 'display str)))
  13423. (defun org-fix-decoded-time (time)
  13424. "Set 0 instead of nil for the first 6 elements of time.
  13425. Don't touch the rest."
  13426. (let ((n 0))
  13427. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  13428. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  13429. "Difference between TIMESTAMP-STRING and now in days.
  13430. If SECONDS is non-nil, return the difference in seconds."
  13431. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  13432. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  13433. (funcall fdiff nil))))
  13434. (defun org-deadline-close-p (timestamp-string &optional ndays)
  13435. "Is the time in TIMESTAMP-STRING close to the current date?"
  13436. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  13437. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  13438. (not (org-entry-is-done-p))))
  13439. (defun org-get-wdays (ts &optional delay zero-delay)
  13440. "Get the deadline lead time appropriate for timestring TS.
  13441. When DELAY is non-nil, get the delay time for scheduled items
  13442. instead of the deadline lead time. When ZERO-DELAY is non-nil
  13443. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  13444. don't try to find the delay cookie in the scheduled timestamp."
  13445. (let ((tv (if delay org-scheduled-delay-days
  13446. org-deadline-warning-days)))
  13447. (cond
  13448. ((or (and delay (< tv 0))
  13449. (and delay zero-delay (<= tv 0))
  13450. (and (not delay) (<= tv 0)))
  13451. ;; Enforce this value no matter what
  13452. (- tv))
  13453. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  13454. ;; lead time is specified.
  13455. (floor (* (string-to-number (match-string 1 ts))
  13456. (cdr (assoc (match-string 2 ts)
  13457. '(("d" . 1) ("w" . 7)
  13458. ("m" . 30.4) ("y" . 365.25)
  13459. ("h" . 0.041667)))))))
  13460. ;; go for the default.
  13461. (t tv))))
  13462. (defun org-calendar-select-mouse (ev)
  13463. "Return to `org-read-date' with the date currently selected.
  13464. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13465. (interactive "e")
  13466. (mouse-set-point ev)
  13467. (when (calendar-cursor-to-date)
  13468. (let* ((date (calendar-cursor-to-date))
  13469. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13470. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13471. (when (active-minibuffer-window) (exit-minibuffer))))
  13472. (defun org-check-deadlines (ndays)
  13473. "Check if there are any deadlines due or past due.
  13474. A deadline is considered due if it happens within `org-deadline-warning-days'
  13475. days from today's date. If the deadline appears in an entry marked DONE,
  13476. it is not shown. A numeric prefix argument NDAYS can be used to test that
  13477. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  13478. are shown."
  13479. (interactive "P")
  13480. (let* ((org-warn-days
  13481. (cond
  13482. ((equal ndays '(4)) 100000)
  13483. (ndays (prefix-numeric-value ndays))
  13484. (t (abs org-deadline-warning-days))))
  13485. (case-fold-search nil)
  13486. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  13487. (callback
  13488. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  13489. (message "%d deadlines past-due or due within %d days"
  13490. (org-occur regexp nil callback)
  13491. org-warn-days)))
  13492. (defsubst org-re-timestamp (type)
  13493. "Return a regexp for timestamp TYPE.
  13494. Allowed values for TYPE are:
  13495. all: all timestamps
  13496. active: only active timestamps (<...>)
  13497. inactive: only inactive timestamps ([...])
  13498. scheduled: only scheduled timestamps
  13499. deadline: only deadline timestamps
  13500. closed: only closed time-stamps
  13501. When TYPE is nil, fall back on returning a regexp that matches
  13502. both scheduled and deadline timestamps."
  13503. (cl-case type
  13504. (all org-ts-regexp-both)
  13505. (active org-ts-regexp)
  13506. (inactive org-ts-regexp-inactive)
  13507. (scheduled org-scheduled-time-regexp)
  13508. (deadline org-deadline-time-regexp)
  13509. (closed org-closed-time-regexp)
  13510. (otherwise
  13511. (concat "\\<"
  13512. (regexp-opt (list org-deadline-string org-scheduled-string))
  13513. " *<\\([^>]+\\)>"))))
  13514. (defun org-check-before-date (d)
  13515. "Check if there are deadlines or scheduled entries before date D."
  13516. (interactive (list (org-read-date)))
  13517. (let* ((case-fold-search nil)
  13518. (regexp (org-re-timestamp org-ts-type))
  13519. (ts-type org-ts-type)
  13520. (callback
  13521. (lambda ()
  13522. (let ((match (match-string 1)))
  13523. (and (if (memq ts-type '(active inactive all))
  13524. (eq (org-element-type (save-excursion
  13525. (backward-char)
  13526. (org-element-context)))
  13527. 'timestamp)
  13528. (org-at-planning-p))
  13529. (time-less-p
  13530. (org-time-string-to-time match)
  13531. (org-time-string-to-time d)))))))
  13532. (message "%d entries before %s"
  13533. (org-occur regexp nil callback)
  13534. d)))
  13535. (defun org-check-after-date (d)
  13536. "Check if there are deadlines or scheduled entries after date D."
  13537. (interactive (list (org-read-date)))
  13538. (let* ((case-fold-search nil)
  13539. (regexp (org-re-timestamp org-ts-type))
  13540. (ts-type org-ts-type)
  13541. (callback
  13542. (lambda ()
  13543. (let ((match (match-string 1)))
  13544. (and (if (memq ts-type '(active inactive all))
  13545. (eq (org-element-type (save-excursion
  13546. (backward-char)
  13547. (org-element-context)))
  13548. 'timestamp)
  13549. (org-at-planning-p))
  13550. (not (time-less-p
  13551. (org-time-string-to-time match)
  13552. (org-time-string-to-time d))))))))
  13553. (message "%d entries after %s"
  13554. (org-occur regexp nil callback)
  13555. d)))
  13556. (defun org-check-dates-range (start-date end-date)
  13557. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13558. (interactive (list (org-read-date nil nil nil "Range starts")
  13559. (org-read-date nil nil nil "Range end")))
  13560. (let ((case-fold-search nil)
  13561. (regexp (org-re-timestamp org-ts-type))
  13562. (callback
  13563. (let ((type org-ts-type))
  13564. (lambda ()
  13565. (let ((match (match-string 1)))
  13566. (and
  13567. (if (memq type '(active inactive all))
  13568. (eq (org-element-type (save-excursion
  13569. (backward-char)
  13570. (org-element-context)))
  13571. 'timestamp)
  13572. (org-at-planning-p))
  13573. (not (time-less-p
  13574. (org-time-string-to-time match)
  13575. (org-time-string-to-time start-date)))
  13576. (time-less-p
  13577. (org-time-string-to-time match)
  13578. (org-time-string-to-time end-date))))))))
  13579. (message "%d entries between %s and %s"
  13580. (org-occur regexp nil callback) start-date end-date)))
  13581. (defun org-evaluate-time-range (&optional to-buffer)
  13582. "Evaluate a time range by computing the difference between start and end.
  13583. Normally the result is just printed in the echo area, but with prefix arg
  13584. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13585. If the time range is actually in a table, the result is inserted into the
  13586. next column.
  13587. For time difference computation, a year is assumed to be exactly 365
  13588. days in order to avoid rounding problems."
  13589. (interactive "P")
  13590. (or
  13591. (org-clock-update-time-maybe)
  13592. (save-excursion
  13593. (unless (org-at-date-range-p t)
  13594. (goto-char (point-at-bol))
  13595. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13596. (unless (org-at-date-range-p t)
  13597. (user-error "Not at a time-stamp range, and none found in current line")))
  13598. (let* ((ts1 (match-string 1))
  13599. (ts2 (match-string 2))
  13600. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13601. (match-end (match-end 0))
  13602. (time1 (org-time-string-to-time ts1))
  13603. (time2 (org-time-string-to-time ts2))
  13604. (diff (abs (float-time (time-subtract time2 time1))))
  13605. (negative (time-less-p time2 time1))
  13606. ;; (ys (floor (* 365 24 60 60)))
  13607. (ds (* 24 60 60))
  13608. (hs (* 60 60))
  13609. (fy "%dy %dd %02d:%02d")
  13610. (fy1 "%dy %dd")
  13611. (fd "%dd %02d:%02d")
  13612. (fd1 "%dd")
  13613. (fh "%02d:%02d")
  13614. y d h m align)
  13615. (if havetime
  13616. (setq ; y (floor diff ys) diff (mod diff ys)
  13617. y 0
  13618. d (floor diff ds) diff (mod diff ds)
  13619. h (floor diff hs) diff (mod diff hs)
  13620. m (floor diff 60))
  13621. (setq ; y (floor diff ys) diff (mod diff ys)
  13622. y 0
  13623. d (round diff ds)
  13624. h 0 m 0))
  13625. (if (not to-buffer)
  13626. (message "%s" (org-make-tdiff-string y d h m))
  13627. (if (org-at-table-p)
  13628. (progn
  13629. (goto-char match-end)
  13630. (setq align t)
  13631. (and (looking-at " *|") (goto-char (match-end 0))))
  13632. (goto-char match-end))
  13633. (when (looking-at
  13634. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13635. (replace-match ""))
  13636. (when negative (insert " -"))
  13637. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13638. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13639. (insert " " (format fh h m))))
  13640. (when align (org-table-align))
  13641. (message "Time difference inserted")))))
  13642. (defun org-make-tdiff-string (y d h m)
  13643. (let ((fmt "")
  13644. (l nil))
  13645. (when (> y 0)
  13646. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13647. (push y l))
  13648. (when (> d 0)
  13649. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13650. (push d l))
  13651. (when (> h 0)
  13652. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13653. (push h l))
  13654. (when (> m 0)
  13655. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13656. (push m l))
  13657. (apply 'format fmt (nreverse l))))
  13658. (defun org-time-string-to-time (s)
  13659. "Convert timestamp string S into internal time."
  13660. (apply #'encode-time (org-parse-time-string s)))
  13661. (defun org-time-string-to-seconds (s)
  13662. "Convert a timestamp string S into a number of seconds."
  13663. (float-time (org-time-string-to-time s)))
  13664. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13665. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13666. "Convert time stamp S to an absolute day number.
  13667. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13668. stamp, get the closest date to DAYNR. If PREFER is
  13669. `past' (respectively `future') return a date past (respectively
  13670. after) or equal to DAYNR.
  13671. POS is the location of time stamp S, as a buffer position in
  13672. BUFFER.
  13673. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13674. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13675. signaled."
  13676. (cond
  13677. ((string-match "\\`%%\\((.*)\\)" s)
  13678. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13679. ;; only able to match individual dates. If it fails, raise an
  13680. ;; error.
  13681. (if (and daynr
  13682. (org-diary-sexp-entry
  13683. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13684. daynr
  13685. (signal 'org-diary-sexp-no-match (list s))))
  13686. (daynr (org-closest-date s daynr prefer))
  13687. (t (time-to-days
  13688. (condition-case errdata
  13689. (org-time-string-to-time s)
  13690. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13691. s
  13692. (if (not (and buffer pos)) ""
  13693. (format-message " at %d in buffer `%s'" pos buffer))
  13694. (cdr errdata))))))))
  13695. (defun org-days-to-iso-week (days)
  13696. "Return the iso week number."
  13697. (require 'cal-iso)
  13698. (car (calendar-iso-from-absolute days)))
  13699. (defun org-small-year-to-year (year)
  13700. "Convert 2-digit years into 4-digit years.
  13701. YEAR is expanded into one of the 30 next years, if possible, or
  13702. into a past one. Any year larger than 99 is returned unchanged."
  13703. (if (>= year 100) year
  13704. (let* ((current (string-to-number (format-time-string "%Y")))
  13705. (century (/ current 100))
  13706. (offset (- year (% current 100))))
  13707. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13708. ((> offset -70) (+ (* century 100) year))
  13709. (t (+ (* (1+ century) 100) year))))))
  13710. (defun org-time-from-absolute (d)
  13711. "Return the time corresponding to date D.
  13712. D may be an absolute day number, or a calendar-type list (month day year)."
  13713. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13714. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13715. (defvar org-agenda-current-date)
  13716. (defun org-calendar-holiday ()
  13717. "List of holidays, for Diary display in Org mode."
  13718. (require 'holidays)
  13719. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13720. (and hl (mapconcat #'identity hl "; "))))
  13721. (defun org-diary-sexp-entry (sexp entry d)
  13722. "Process a SEXP diary ENTRY for date D."
  13723. (require 'diary-lib)
  13724. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13725. ;; dynamically.
  13726. (let* ((sexp `(let ((entry ,entry)
  13727. (date ',d))
  13728. ,(car (read-from-string sexp))))
  13729. (result (if calendar-debug-sexp (eval sexp)
  13730. (condition-case nil
  13731. (eval sexp)
  13732. (error
  13733. (beep)
  13734. (message "Bad sexp at line %d in %s: %s"
  13735. (org-current-line)
  13736. (buffer-file-name) sexp)
  13737. (sleep-for 2))))))
  13738. (cond ((stringp result) (split-string result "; "))
  13739. ((and (consp result)
  13740. (not (consp (cdr result)))
  13741. (stringp (cdr result))) (cdr result))
  13742. ((and (consp result)
  13743. (stringp (car result))) result)
  13744. (result entry))))
  13745. (defun org-diary-to-ical-string (frombuf)
  13746. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13747. This uses the icalendar.el library."
  13748. (let* ((tmpdir temporary-file-directory)
  13749. (tmpfile (make-temp-name
  13750. (expand-file-name "orgics" tmpdir)))
  13751. buf rtn b e)
  13752. (with-current-buffer frombuf
  13753. (icalendar-export-region (point-min) (point-max) tmpfile)
  13754. (setq buf (find-buffer-visiting tmpfile))
  13755. (set-buffer buf)
  13756. (goto-char (point-min))
  13757. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13758. (setq b (match-beginning 0)))
  13759. (goto-char (point-max))
  13760. (when (re-search-backward "^END:VEVENT" nil t)
  13761. (setq e (match-end 0)))
  13762. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13763. (kill-buffer buf)
  13764. (delete-file tmpfile)
  13765. rtn))
  13766. (defun org-closest-date (start current prefer)
  13767. "Return closest date to CURRENT starting from START.
  13768. CURRENT and START are both time stamps.
  13769. When PREFER is `past', return a date that is either CURRENT or
  13770. past. When PREFER is `future', return a date that is either
  13771. CURRENT or future.
  13772. Only time stamps with a repeater are modified. Any other time
  13773. stamp stay unchanged. In any case, return value is an absolute
  13774. day number."
  13775. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13776. ;; No repeater. Do not shift time stamp.
  13777. (time-to-days (org-time-string-to-time start))
  13778. (let ((value (string-to-number (match-string 1 start)))
  13779. (type (match-string 2 start)))
  13780. (if (= 0 value)
  13781. ;; Repeater with a 0-value is considered as void.
  13782. (time-to-days (org-time-string-to-time start))
  13783. (let* ((base (org-date-to-gregorian start))
  13784. (target (org-date-to-gregorian current))
  13785. (sday (calendar-absolute-from-gregorian base))
  13786. (cday (calendar-absolute-from-gregorian target))
  13787. n1 n2)
  13788. ;; If START is already past CURRENT, just return START.
  13789. (if (<= cday sday) sday
  13790. ;; Compute closest date before (N1) and closest date past
  13791. ;; (N2) CURRENT.
  13792. (pcase type
  13793. ("h"
  13794. (let ((missing-hours
  13795. (mod (+ (- (* 24 (- cday sday))
  13796. (nth 2 (org-parse-time-string start)))
  13797. org-extend-today-until)
  13798. value)))
  13799. (setf n1 (if (= missing-hours 0) cday
  13800. (- cday (1+ (/ missing-hours 24)))))
  13801. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13802. ((or "d" "w")
  13803. (let ((value (if (equal type "w") (* 7 value) value)))
  13804. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13805. (setf n2 (+ n1 value))))
  13806. ("m"
  13807. (let* ((add-months
  13808. (lambda (d n)
  13809. ;; Add N months to gregorian date D, i.e.,
  13810. ;; a list (MONTH DAY YEAR). Return a valid
  13811. ;; gregorian date.
  13812. (let ((m (+ (nth 0 d) n)))
  13813. (list (mod m 12)
  13814. (nth 1 d)
  13815. (+ (/ m 12) (nth 2 d))))))
  13816. (months ; Complete months to TARGET.
  13817. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13818. (- (nth 0 target) (nth 0 base))
  13819. ;; If START's day is greater than
  13820. ;; TARGET's, remove incomplete month.
  13821. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13822. value)
  13823. value))
  13824. (before (funcall add-months base months)))
  13825. (setf n1 (calendar-absolute-from-gregorian before))
  13826. (setf n2
  13827. (calendar-absolute-from-gregorian
  13828. (funcall add-months before value)))))
  13829. (_
  13830. (let* ((d (nth 1 base))
  13831. (m (nth 0 base))
  13832. (y (nth 2 base))
  13833. (years ; Complete years to TARGET.
  13834. (* (/ (- (nth 2 target)
  13835. y
  13836. ;; If START's month and day are
  13837. ;; greater than TARGET's, remove
  13838. ;; incomplete year.
  13839. (if (or (> (nth 0 target) m)
  13840. (and (= (nth 0 target) m)
  13841. (> (nth 1 target) d)))
  13842. 0
  13843. 1))
  13844. value)
  13845. value))
  13846. (before (list m d (+ y years))))
  13847. (setf n1 (calendar-absolute-from-gregorian before))
  13848. (setf n2 (calendar-absolute-from-gregorian
  13849. (list m d (+ (nth 2 before) value)))))))
  13850. ;; Handle PREFER parameter, if any.
  13851. (cond
  13852. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13853. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13854. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13855. (defun org-date-to-gregorian (d)
  13856. "Turn any specification of date D into a Gregorian date for the calendar."
  13857. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13858. ((and (listp d) (= (length d) 3)) d)
  13859. ((stringp d)
  13860. (let ((d (org-parse-time-string d)))
  13861. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13862. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13863. (defun org-timestamp-up (&optional arg)
  13864. "Increase the date item at the cursor by one.
  13865. If the cursor is on the year, change the year. If it is on the month,
  13866. the day or the time, change that. If the cursor is on the enclosing
  13867. bracket, change the timestamp type.
  13868. With prefix ARG, change by that many units."
  13869. (interactive "p")
  13870. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13871. (defun org-timestamp-down (&optional arg)
  13872. "Decrease the date item at the cursor by one.
  13873. If the cursor is on the year, change the year. If it is on the month,
  13874. the day or the time, change that. If the cursor is on the enclosing
  13875. bracket, change the timestamp type.
  13876. With prefix ARG, change by that many units."
  13877. (interactive "p")
  13878. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13879. (defun org-timestamp-up-day (&optional arg)
  13880. "Increase the date in the time stamp by one day.
  13881. With prefix ARG, change that many days."
  13882. (interactive "p")
  13883. (if (and (not (org-at-timestamp-p 'lax))
  13884. (org-at-heading-p))
  13885. (org-todo 'up)
  13886. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13887. (defun org-timestamp-down-day (&optional arg)
  13888. "Decrease the date in the time stamp by one day.
  13889. With prefix ARG, change that many days."
  13890. (interactive "p")
  13891. (if (and (not (org-at-timestamp-p 'lax))
  13892. (org-at-heading-p))
  13893. (org-todo 'down)
  13894. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13895. (defun org-at-timestamp-p (&optional extended)
  13896. "Non-nil if point is inside a timestamp.
  13897. By default, the function only consider syntactically valid active
  13898. timestamps. However, the caller may have a broader definition
  13899. for timestamps. As a consequence, optional argument EXTENDED can
  13900. be set to the following values
  13901. `inactive'
  13902. Include also syntactically valid inactive timestamps.
  13903. `agenda'
  13904. Include timestamps allowed in Agenda, i.e., those in
  13905. properties drawers, planning lines and clock lines.
  13906. `lax'
  13907. Ignore context. The function matches any part of the
  13908. document looking like a timestamp. This includes comments,
  13909. example blocks...
  13910. For backward-compatibility with Org 9.0, every other non-nil
  13911. value is equivalent to `inactive'.
  13912. When at a timestamp, return the position of the point as a symbol
  13913. among `bracket', `after', `year', `month', `hour', `minute',
  13914. `day' or a number of character from the last know part of the
  13915. time stamp.
  13916. When matching, the match groups are the following:
  13917. group 1: year
  13918. group 2: month
  13919. group 3: day number
  13920. group 4: day name
  13921. group 5: hours, if any
  13922. group 6: minutes, if any"
  13923. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13924. (pos (point))
  13925. (match?
  13926. (let ((boundaries (org-in-regexp regexp)))
  13927. (save-match-data
  13928. (cond ((null boundaries) nil)
  13929. ((eq extended 'lax) t)
  13930. (t
  13931. (or (and (eq extended 'agenda)
  13932. (or (org-at-planning-p)
  13933. (org-at-property-p)
  13934. (and (bound-and-true-p
  13935. org-agenda-include-inactive-timestamps)
  13936. (org-at-clock-log-p))))
  13937. (eq 'timestamp
  13938. (save-excursion
  13939. (when (= pos (cdr boundaries)) (forward-char -1))
  13940. (org-element-type (org-element-context)))))))))))
  13941. (cond
  13942. ((not match?) nil)
  13943. ((= pos (match-beginning 0)) 'bracket)
  13944. ;; Distinguish location right before the closing bracket from
  13945. ;; right after it.
  13946. ((= pos (1- (match-end 0))) 'bracket)
  13947. ((= pos (match-end 0)) 'after)
  13948. ((org-pos-in-match-range pos 2) 'year)
  13949. ((org-pos-in-match-range pos 3) 'month)
  13950. ((org-pos-in-match-range pos 7) 'hour)
  13951. ((org-pos-in-match-range pos 8) 'minute)
  13952. ((or (org-pos-in-match-range pos 4)
  13953. (org-pos-in-match-range pos 5)) 'day)
  13954. ((and (> pos (or (match-end 8) (match-end 5)))
  13955. (< pos (match-end 0)))
  13956. (- pos (or (match-end 8) (match-end 5))))
  13957. (t 'day))))
  13958. (defun org-toggle-timestamp-type ()
  13959. "Toggle the type (<active> or [inactive]) of a time stamp."
  13960. (interactive)
  13961. (when (org-at-timestamp-p 'lax)
  13962. (let ((beg (match-beginning 0)) (end (match-end 0))
  13963. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13964. (save-excursion
  13965. (goto-char beg)
  13966. (while (re-search-forward "[][<>]" end t)
  13967. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13968. t t)))
  13969. (message "Timestamp is now %sactive"
  13970. (if (equal (char-after beg) ?<) "" "in")))))
  13971. (defun org-at-clock-log-p ()
  13972. "Non-nil if point is on a clock log line."
  13973. (and (org-match-line org-clock-line-re)
  13974. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13975. (defvar org-clock-history) ; defined in org-clock.el
  13976. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13977. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13978. "Change the date in the time stamp at point.
  13979. The date is changed by N times WHAT. WHAT can be `day', `month',
  13980. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13981. position in the timestamp determines what is changed.
  13982. When optional argument UPDOWN is non-nil, minutes are rounded
  13983. according to `org-time-stamp-rounding-minutes'.
  13984. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13985. \"--2d\"."
  13986. (let ((origin (point))
  13987. (timestamp? (org-at-timestamp-p 'lax))
  13988. origin-cat
  13989. with-hm inactive
  13990. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13991. extra rem
  13992. ts time time0 fixnext clrgx)
  13993. (unless timestamp? (user-error "Not at a timestamp"))
  13994. (if (and (not what) (eq timestamp? 'bracket))
  13995. (org-toggle-timestamp-type)
  13996. ;; Point isn't on brackets. Remember the part of the time-stamp
  13997. ;; the point was in. Indeed, size of time-stamps may change,
  13998. ;; but point must be kept in the same category nonetheless.
  13999. (setq origin-cat timestamp?)
  14000. (when (and (not what) (not (eq timestamp? 'day))
  14001. org-display-custom-times
  14002. (get-text-property (point) 'display)
  14003. (not (get-text-property (1- (point)) 'display)))
  14004. (setq timestamp? 'day))
  14005. (setq timestamp? (or what timestamp?)
  14006. inactive (= (char-after (match-beginning 0)) ?\[)
  14007. ts (match-string 0))
  14008. (replace-match "")
  14009. (when (string-match
  14010. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  14011. ts)
  14012. (setq extra (match-string 1 ts))
  14013. (when suppress-tmp-delay
  14014. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  14015. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  14016. (setq with-hm t))
  14017. (setq time0 (org-parse-time-string ts))
  14018. (when (and updown
  14019. (eq timestamp? 'minute)
  14020. (not current-prefix-arg))
  14021. ;; This looks like s-up and s-down. Change by one rounding step.
  14022. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  14023. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  14024. (setcar (cdr time0) (+ (nth 1 time0)
  14025. (if (> n 0) (- rem) (- dm rem))))))
  14026. (setq time
  14027. (apply #'encode-time
  14028. (or (car time0) 0)
  14029. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  14030. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  14031. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  14032. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  14033. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  14034. (nthcdr 6 time0)))
  14035. (when (and (memq timestamp? '(hour minute))
  14036. extra
  14037. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  14038. (setq extra (org-modify-ts-extra
  14039. extra
  14040. (if (eq timestamp? 'hour) 2 5)
  14041. n dm)))
  14042. (when (integerp timestamp?)
  14043. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  14044. (when (eq what 'calendar)
  14045. (let ((cal-date (org-get-date-from-calendar)))
  14046. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  14047. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  14048. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  14049. (setcar time0 (or (car time0) 0))
  14050. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  14051. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  14052. (setq time (apply 'encode-time time0))))
  14053. ;; Insert the new time-stamp, and ensure point stays in the same
  14054. ;; category as before (i.e. not after the last position in that
  14055. ;; category).
  14056. (let ((pos (point)))
  14057. ;; Stay before inserted string. `save-excursion' is of no use.
  14058. (setq org-last-changed-timestamp
  14059. (org-insert-time-stamp time with-hm inactive nil nil extra))
  14060. (goto-char pos))
  14061. (save-match-data
  14062. (looking-at org-ts-regexp3)
  14063. (goto-char
  14064. (pcase origin-cat
  14065. ;; `day' category ends before `hour' if any, or at the end
  14066. ;; of the day name.
  14067. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  14068. (`hour (min (match-end 7) origin))
  14069. (`minute (min (1- (match-end 8)) origin))
  14070. ((pred integerp) (min (1- (match-end 0)) origin))
  14071. ;; Point was right after the time-stamp. However, the
  14072. ;; time-stamp length might have changed, so refer to
  14073. ;; (match-end 0) instead.
  14074. (`after (match-end 0))
  14075. ;; `year' and `month' have both fixed size: point couldn't
  14076. ;; have moved into another part.
  14077. (_ origin))))
  14078. ;; Update clock if on a CLOCK line.
  14079. (org-clock-update-time-maybe)
  14080. ;; Maybe adjust the closest clock in `org-clock-history'
  14081. (when org-clock-adjust-closest
  14082. (if (not (and (org-at-clock-log-p)
  14083. (< 1 (length (delq nil (mapcar 'marker-position
  14084. org-clock-history))))))
  14085. (message "No clock to adjust")
  14086. (cond ((save-excursion ; fix previous clock?
  14087. (re-search-backward org-ts-regexp0 nil t)
  14088. (looking-back (concat org-clock-string " \\[")
  14089. (line-beginning-position)))
  14090. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  14091. ((save-excursion ; fix next clock?
  14092. (re-search-backward org-ts-regexp0 nil t)
  14093. (looking-at (concat org-ts-regexp0 "\\] =>")))
  14094. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  14095. (save-window-excursion
  14096. ;; Find closest clock to point, adjust the previous/next one in history
  14097. (let* ((p (save-excursion (org-back-to-heading t)))
  14098. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  14099. (clfixnth
  14100. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  14101. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  14102. (if (not clfixpos)
  14103. (message "No clock to adjust")
  14104. (save-excursion
  14105. (org-goto-marker-or-bmk clfixpos)
  14106. (org-show-subtree)
  14107. (when (re-search-forward clrgx nil t)
  14108. (goto-char (match-beginning 1))
  14109. (let (org-clock-adjust-closest)
  14110. (org-timestamp-change n timestamp? updown))
  14111. (message "Clock adjusted in %s for heading: %s"
  14112. (file-name-nondirectory (buffer-file-name))
  14113. (org-get-heading t t)))))))))
  14114. ;; Try to recenter the calendar window, if any.
  14115. (when (and org-calendar-follow-timestamp-change
  14116. (get-buffer-window "*Calendar*" t)
  14117. (memq timestamp? '(day month year)))
  14118. (org-recenter-calendar (time-to-days time))))))
  14119. (defun org-modify-ts-extra (s pos n dm)
  14120. "Change the different parts of the lead-time and repeat fields in timestamp."
  14121. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  14122. ng h m new rem)
  14123. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  14124. (cond
  14125. ((or (org-pos-in-match-range pos 2)
  14126. (org-pos-in-match-range pos 3))
  14127. (setq m (string-to-number (match-string 3 s))
  14128. h (string-to-number (match-string 2 s)))
  14129. (if (org-pos-in-match-range pos 2)
  14130. (setq h (+ h n))
  14131. (setq n (* dm (with-no-warnings (cl-signum n))))
  14132. (unless (= 0 (setq rem (% m dm)))
  14133. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  14134. (setq m (+ m n)))
  14135. (when (< m 0) (setq m (+ m 60) h (1- h)))
  14136. (when (> m 59) (setq m (- m 60) h (1+ h)))
  14137. (setq h (mod h 24))
  14138. (setq ng 1 new (format "-%02d:%02d" h m)))
  14139. ((org-pos-in-match-range pos 6)
  14140. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  14141. ((org-pos-in-match-range pos 5)
  14142. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  14143. ((org-pos-in-match-range pos 9)
  14144. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  14145. ((org-pos-in-match-range pos 8)
  14146. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  14147. (when ng
  14148. (setq s (concat
  14149. (substring s 0 (match-beginning ng))
  14150. new
  14151. (substring s (match-end ng))))))
  14152. s))
  14153. (defun org-recenter-calendar (d)
  14154. "If the calendar is visible, recenter it to date D."
  14155. (let ((cwin (get-buffer-window "*Calendar*" t)))
  14156. (when cwin
  14157. (let ((calendar-move-hook nil))
  14158. (with-selected-window cwin
  14159. (calendar-goto-date
  14160. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  14161. (defun org-goto-calendar (&optional arg)
  14162. "Go to the Emacs calendar at the current date.
  14163. If there is a time stamp in the current line, go to that date.
  14164. A prefix ARG can be used to force the current date."
  14165. (interactive "P")
  14166. (let ((calendar-move-hook nil)
  14167. (calendar-view-holidays-initially-flag nil)
  14168. (calendar-view-diary-initially-flag nil)
  14169. diff)
  14170. (when (or (org-at-timestamp-p 'lax)
  14171. (org-match-line (concat ".*" org-ts-regexp)))
  14172. (let ((d1 (time-to-days nil))
  14173. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  14174. (setq diff (- d2 d1))))
  14175. (calendar)
  14176. (calendar-goto-today)
  14177. (when (and diff (not arg)) (calendar-forward-day diff))))
  14178. (defun org-get-date-from-calendar ()
  14179. "Return a list (month day year) of date at point in calendar."
  14180. (with-current-buffer "*Calendar*"
  14181. (save-match-data
  14182. (calendar-cursor-to-date))))
  14183. (defun org-date-from-calendar ()
  14184. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  14185. If there is already a time stamp at the cursor position, update it."
  14186. (interactive)
  14187. (if (org-at-timestamp-p 'lax)
  14188. (org-timestamp-change 0 'calendar)
  14189. (let ((cal-date (org-get-date-from-calendar)))
  14190. (org-insert-time-stamp
  14191. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  14192. (defcustom org-image-actual-width t
  14193. "When non-nil, use the actual width of images when inlining them.
  14194. When set to a number, use imagemagick (when available) to set the
  14195. image's width to this value.
  14196. When set to a number in a list, try to get the width from any
  14197. #+ATTR.* keyword if it matches a width specification like
  14198. #+ATTR_HTML: :width 300px
  14199. and fall back on that number if none is found.
  14200. When set to nil, try to get the width from an #+ATTR.* keyword
  14201. and fall back on the original width if none is found.
  14202. When set to any other non-nil value, always use the image width.
  14203. This requires Emacs >= 24.1, built with imagemagick support."
  14204. :group 'org-appearance
  14205. :version "24.4"
  14206. :package-version '(Org . "8.0")
  14207. :type '(choice
  14208. (const :tag "Use the image width" t)
  14209. (integer :tag "Use a number of pixels")
  14210. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  14211. (const :tag "Use #+ATTR* or don't resize" nil)))
  14212. (defcustom org-agenda-inhibit-startup nil
  14213. "Inhibit startup when preparing agenda buffers.
  14214. When this variable is t, the initialization of the Org agenda
  14215. buffers is inhibited: e.g. the visibility state is not set, the
  14216. tables are not re-aligned, etc."
  14217. :type 'boolean
  14218. :version "24.3"
  14219. :group 'org-agenda)
  14220. (defcustom org-agenda-ignore-properties nil
  14221. "Avoid updating text properties when building the agenda.
  14222. Properties are used to prepare buffers for effort estimates,
  14223. appointments, statistics and subtree-local categories.
  14224. If you don't use these in the agenda, you can add them to this
  14225. list and agenda building will be a bit faster.
  14226. The value is a list, with zero or more of the symbols `effort', `appt',
  14227. `stats' or `category'."
  14228. :type '(set :greedy t
  14229. (const effort)
  14230. (const appt)
  14231. (const stats)
  14232. (const category))
  14233. :version "26.1"
  14234. :package-version '(Org . "8.3")
  14235. :group 'org-agenda)
  14236. ;;;; Files
  14237. (defun org-save-all-org-buffers ()
  14238. "Save all Org buffers without user confirmation."
  14239. (interactive)
  14240. (message "Saving all Org buffers...")
  14241. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  14242. (when (featurep 'org-id) (org-id-locations-save))
  14243. (message "Saving all Org buffers... done"))
  14244. (defun org-revert-all-org-buffers ()
  14245. "Revert all Org buffers.
  14246. Prompt for confirmation when there are unsaved changes.
  14247. Be sure you know what you are doing before letting this function
  14248. overwrite your changes.
  14249. This function is useful in a setup where one tracks Org files
  14250. with a version control system, to revert on one machine after pulling
  14251. changes from another. I believe the procedure must be like this:
  14252. 1. M-x org-save-all-org-buffers
  14253. 2. Pull changes from the other machine, resolve conflicts
  14254. 3. M-x org-revert-all-org-buffers"
  14255. (interactive)
  14256. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  14257. (user-error "Abort"))
  14258. (save-excursion
  14259. (save-window-excursion
  14260. (dolist (b (buffer-list))
  14261. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  14262. (with-current-buffer b buffer-file-name))
  14263. (pop-to-buffer-same-window b)
  14264. (revert-buffer t 'no-confirm)))
  14265. (when (and (featurep 'org-id) org-id-track-globally)
  14266. (org-id-locations-load)))))
  14267. ;;;; Agenda files
  14268. ;;;###autoload
  14269. (defun org-switchb (&optional arg)
  14270. "Switch between Org buffers.
  14271. With `\\[universal-argument]' prefix, restrict available buffers to files.
  14272. With `\\[universal-argument] \\[universal-argument]' \
  14273. prefix, restrict available buffers to agenda files."
  14274. (interactive "P")
  14275. (let ((blist (org-buffer-list
  14276. (cond ((equal arg '(4)) 'files)
  14277. ((equal arg '(16)) 'agenda)))))
  14278. (pop-to-buffer-same-window
  14279. (completing-read "Org buffer: "
  14280. (mapcar #'list (mapcar #'buffer-name blist))
  14281. nil t))))
  14282. (defun org-buffer-list (&optional predicate exclude-tmp)
  14283. "Return a list of Org buffers.
  14284. PREDICATE can be `export', `files' or `agenda'.
  14285. export restrict the list to Export buffers.
  14286. files restrict the list to buffers visiting Org files.
  14287. agenda restrict the list to buffers visiting agenda files.
  14288. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  14289. (let* ((bfn nil)
  14290. (agenda-files (and (eq predicate 'agenda)
  14291. (mapcar 'file-truename (org-agenda-files t))))
  14292. (filter
  14293. (cond
  14294. ((eq predicate 'files)
  14295. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  14296. ((eq predicate 'export)
  14297. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  14298. ((eq predicate 'agenda)
  14299. (lambda (b)
  14300. (with-current-buffer b
  14301. (and (derived-mode-p 'org-mode)
  14302. (setq bfn (buffer-file-name b))
  14303. (member (file-truename bfn) agenda-files)))))
  14304. (t (lambda (b) (with-current-buffer b
  14305. (or (derived-mode-p 'org-mode)
  14306. (string-match "\\*Org .*Export"
  14307. (buffer-name b)))))))))
  14308. (delq nil
  14309. (mapcar
  14310. (lambda(b)
  14311. (if (and (funcall filter b)
  14312. (or (not exclude-tmp)
  14313. (not (string-match "tmp" (buffer-name b)))))
  14314. b
  14315. nil))
  14316. (buffer-list)))))
  14317. (defun org-agenda-files (&optional unrestricted archives)
  14318. "Get the list of agenda files.
  14319. Optional UNRESTRICTED means return the full list even if a restriction
  14320. is currently in place.
  14321. When ARCHIVES is t, include all archive files that are really being
  14322. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  14323. `org-agenda-archives-mode' is t."
  14324. (let ((files
  14325. (cond
  14326. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  14327. ((stringp org-agenda-files) (org-read-agenda-file-list))
  14328. ((listp org-agenda-files) org-agenda-files)
  14329. (t (error "Invalid value of `org-agenda-files'")))))
  14330. (setq files (apply 'append
  14331. (mapcar (lambda (f)
  14332. (if (file-directory-p f)
  14333. (directory-files
  14334. f t org-agenda-file-regexp)
  14335. (list f)))
  14336. files)))
  14337. (when org-agenda-skip-unavailable-files
  14338. (setq files (delq nil
  14339. (mapcar (function
  14340. (lambda (file)
  14341. (and (file-readable-p file) file)))
  14342. files))))
  14343. (when (or (eq archives t)
  14344. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  14345. (setq files (org-add-archive-files files)))
  14346. files))
  14347. (defun org-agenda-file-p (&optional file)
  14348. "Return non-nil, if FILE is an agenda file.
  14349. If FILE is omitted, use the file associated with the current
  14350. buffer."
  14351. (let ((fname (or file (buffer-file-name))))
  14352. (and fname
  14353. (member (file-truename fname)
  14354. (mapcar #'file-truename (org-agenda-files t))))))
  14355. (defun org-edit-agenda-file-list ()
  14356. "Edit the list of agenda files.
  14357. Depending on setup, this either uses customize to edit the variable
  14358. `org-agenda-files', or it visits the file that is holding the list. In the
  14359. latter case, the buffer is set up in a way that saving it automatically kills
  14360. the buffer and restores the previous window configuration."
  14361. (interactive)
  14362. (if (stringp org-agenda-files)
  14363. (let ((cw (current-window-configuration)))
  14364. (find-file org-agenda-files)
  14365. (setq-local org-window-configuration cw)
  14366. (add-hook 'after-save-hook
  14367. (lambda ()
  14368. (set-window-configuration
  14369. (prog1 org-window-configuration
  14370. (kill-buffer (current-buffer))))
  14371. (org-install-agenda-files-menu)
  14372. (message "New agenda file list installed"))
  14373. nil 'local)
  14374. (message "%s" (substitute-command-keys
  14375. "Edit list and finish with \\[save-buffer]")))
  14376. (customize-variable 'org-agenda-files)))
  14377. (defun org-store-new-agenda-file-list (list)
  14378. "Set new value for the agenda file list and save it correctly."
  14379. (if (stringp org-agenda-files)
  14380. (let ((fe (org-read-agenda-file-list t)) b u)
  14381. (while (setq b (find-buffer-visiting org-agenda-files))
  14382. (kill-buffer b))
  14383. (with-temp-file org-agenda-files
  14384. (insert
  14385. (mapconcat
  14386. (lambda (f) ;; Keep un-expanded entries.
  14387. (if (setq u (assoc f fe))
  14388. (cdr u)
  14389. f))
  14390. list "\n")
  14391. "\n")))
  14392. (let ((org-mode-hook nil) (org-inhibit-startup t)
  14393. (org-insert-mode-line-in-empty-file nil))
  14394. (setq org-agenda-files list)
  14395. (customize-save-variable 'org-agenda-files org-agenda-files))))
  14396. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  14397. "Read the list of agenda files from a file.
  14398. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  14399. filenames, used by `org-store-new-agenda-file-list' to write back
  14400. un-expanded file names."
  14401. (when (file-directory-p org-agenda-files)
  14402. (error "`org-agenda-files' cannot be a single directory"))
  14403. (when (stringp org-agenda-files)
  14404. (with-temp-buffer
  14405. (insert-file-contents org-agenda-files)
  14406. (mapcar
  14407. (lambda (f)
  14408. (let ((e (expand-file-name (substitute-in-file-name f)
  14409. org-directory)))
  14410. (if pair-with-expansion
  14411. (cons e f)
  14412. e)))
  14413. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  14414. ;;;###autoload
  14415. (defun org-cycle-agenda-files ()
  14416. "Cycle through the files in `org-agenda-files'.
  14417. If the current buffer visits an agenda file, find the next one in the list.
  14418. If the current buffer does not, find the first agenda file."
  14419. (interactive)
  14420. (let* ((fs (or (org-agenda-files t)
  14421. (user-error "No agenda files")))
  14422. (files (copy-sequence fs))
  14423. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  14424. file)
  14425. (when tcf
  14426. (while (and (setq file (pop files))
  14427. (not (equal (file-truename file) tcf)))))
  14428. (find-file (car (or files fs)))
  14429. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  14430. (defun org-agenda-file-to-front (&optional to-end)
  14431. "Move/add the current file to the top of the agenda file list.
  14432. If the file is not present in the list, it is added to the front. If it is
  14433. present, it is moved there. With optional argument TO-END, add/move to the
  14434. end of the list."
  14435. (interactive "P")
  14436. (let ((org-agenda-skip-unavailable-files nil)
  14437. (file-alist (mapcar (lambda (x)
  14438. (cons (file-truename x) x))
  14439. (org-agenda-files t)))
  14440. (ctf (file-truename
  14441. (or buffer-file-name
  14442. (user-error "Please save the current buffer to a file"))))
  14443. x had)
  14444. (setq x (assoc ctf file-alist) had x)
  14445. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  14446. (if to-end
  14447. (setq file-alist (append (delq x file-alist) (list x)))
  14448. (setq file-alist (cons x (delq x file-alist))))
  14449. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  14450. (org-install-agenda-files-menu)
  14451. (message "File %s to %s of agenda file list"
  14452. (if had "moved" "added") (if to-end "end" "front"))))
  14453. (defun org-remove-file (&optional file)
  14454. "Remove current file from the list of files in variable `org-agenda-files'.
  14455. These are the files which are being checked for agenda entries.
  14456. Optional argument FILE means use this file instead of the current."
  14457. (interactive)
  14458. (let* ((org-agenda-skip-unavailable-files nil)
  14459. (file (or file buffer-file-name
  14460. (user-error "Current buffer does not visit a file")))
  14461. (true-file (file-truename file))
  14462. (afile (abbreviate-file-name file))
  14463. (files (delq nil (mapcar
  14464. (lambda (x)
  14465. (unless (equal true-file
  14466. (file-truename x))
  14467. x))
  14468. (org-agenda-files t)))))
  14469. (if (not (= (length files) (length (org-agenda-files t))))
  14470. (progn
  14471. (org-store-new-agenda-file-list files)
  14472. (org-install-agenda-files-menu)
  14473. (message "Removed from Org Agenda list: %s" afile))
  14474. (message "File was not in list: %s (not removed)" afile))))
  14475. (defun org-file-menu-entry (file)
  14476. (vector file (list 'find-file file) t))
  14477. (defun org-check-agenda-file (file)
  14478. "Make sure FILE exists. If not, ask user what to do."
  14479. (unless (file-exists-p file)
  14480. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  14481. (abbreviate-file-name file))
  14482. (let ((r (downcase (read-char-exclusive))))
  14483. (cond
  14484. ((equal r ?r)
  14485. (org-remove-file file)
  14486. (throw 'nextfile t))
  14487. (t (user-error "Abort"))))))
  14488. (defun org-get-agenda-file-buffer (file)
  14489. "Get an agenda buffer visiting FILE.
  14490. If the buffer needs to be created, add it to the list of buffers
  14491. which might be released later."
  14492. (let ((buf (org-find-base-buffer-visiting file)))
  14493. (if buf
  14494. buf ; just return it
  14495. ;; Make a new buffer and remember it
  14496. (setq buf (find-file-noselect file))
  14497. (when buf (push buf org-agenda-new-buffers))
  14498. buf)))
  14499. (defun org-release-buffers (blist)
  14500. "Release all buffers in list, asking the user for confirmation when needed.
  14501. When a buffer is unmodified, it is just killed. When modified, it is saved
  14502. \(if the user agrees) and then killed."
  14503. (let (file)
  14504. (dolist (buf blist)
  14505. (setq file (buffer-file-name buf))
  14506. (when (and (buffer-modified-p buf)
  14507. file
  14508. (y-or-n-p (format "Save file %s? " file)))
  14509. (with-current-buffer buf (save-buffer)))
  14510. (kill-buffer buf))))
  14511. (defun org-agenda-prepare-buffers (files)
  14512. "Create buffers for all agenda files, protect archived trees and comments."
  14513. (interactive)
  14514. (let ((pa '(:org-archived t))
  14515. (pc '(:org-comment t))
  14516. (pall '(:org-archived t :org-comment t))
  14517. (inhibit-read-only t)
  14518. (org-inhibit-startup org-agenda-inhibit-startup)
  14519. (rea (org-make-tag-string (list org-archive-tag)))
  14520. re pos)
  14521. (setq org-tag-alist-for-agenda nil
  14522. org-tag-groups-alist-for-agenda nil)
  14523. (save-excursion
  14524. (save-restriction
  14525. (dolist (file files)
  14526. (catch 'nextfile
  14527. (if (bufferp file)
  14528. (set-buffer file)
  14529. (org-check-agenda-file file)
  14530. (set-buffer (org-get-agenda-file-buffer file)))
  14531. (widen)
  14532. (org-set-regexps-and-options 'tags-only)
  14533. (setq pos (point))
  14534. (or (memq 'category org-agenda-ignore-properties)
  14535. (org-refresh-category-properties))
  14536. (or (memq 'stats org-agenda-ignore-properties)
  14537. (org-refresh-stats-properties))
  14538. (or (memq 'effort org-agenda-ignore-properties)
  14539. (org-refresh-effort-properties))
  14540. (or (memq 'appt org-agenda-ignore-properties)
  14541. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14542. (setq org-todo-keywords-for-agenda
  14543. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14544. (setq org-done-keywords-for-agenda
  14545. (append org-done-keywords-for-agenda org-done-keywords))
  14546. (setq org-todo-keyword-alist-for-agenda
  14547. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14548. (setq org-tag-alist-for-agenda
  14549. (org--tag-add-to-alist
  14550. org-tag-alist-for-agenda
  14551. org-current-tag-alist))
  14552. ;; Merge current file's tag groups into global
  14553. ;; `org-tag-groups-alist-for-agenda'.
  14554. (when org-group-tags
  14555. (dolist (alist org-tag-groups-alist)
  14556. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14557. (if old
  14558. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14559. (push alist org-tag-groups-alist-for-agenda)))))
  14560. (with-silent-modifications
  14561. (save-excursion
  14562. (remove-text-properties (point-min) (point-max) pall)
  14563. (when org-agenda-skip-archived-trees
  14564. (goto-char (point-min))
  14565. (while (re-search-forward rea nil t)
  14566. (when (org-at-heading-p t)
  14567. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  14568. (goto-char (point-min))
  14569. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  14570. (while (re-search-forward re nil t)
  14571. (when (save-match-data (org-in-commented-heading-p t))
  14572. (add-text-properties
  14573. (match-beginning 0) (org-end-of-subtree t) pc)))))
  14574. (goto-char pos)))))
  14575. (setq org-todo-keywords-for-agenda
  14576. (org-uniquify org-todo-keywords-for-agenda))
  14577. (setq org-todo-keyword-alist-for-agenda
  14578. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14579. ;;;; CDLaTeX minor mode
  14580. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14581. "Keymap for the minor `org-cdlatex-mode'.")
  14582. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14583. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14584. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14585. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14586. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14587. (defvar org-cdlatex-texmathp-advice-is-done nil
  14588. "Flag remembering if we have applied the advice to texmathp already.")
  14589. (define-minor-mode org-cdlatex-mode
  14590. "Toggle the minor `org-cdlatex-mode'.
  14591. This mode supports entering LaTeX environment and math in LaTeX fragments
  14592. in Org mode.
  14593. \\{org-cdlatex-mode-map}"
  14594. nil " OCDL" nil
  14595. (when org-cdlatex-mode
  14596. (require 'cdlatex)
  14597. (run-hooks 'cdlatex-mode-hook)
  14598. (cdlatex-compute-tables))
  14599. (unless org-cdlatex-texmathp-advice-is-done
  14600. (setq org-cdlatex-texmathp-advice-is-done t)
  14601. (defadvice texmathp (around org-math-always-on activate)
  14602. "Always return t in Org buffers.
  14603. This is because we want to insert math symbols without dollars even outside
  14604. the LaTeX math segments. If Org mode thinks that point is actually inside
  14605. an embedded LaTeX fragment, let `texmathp' do its job.
  14606. `\\[org-cdlatex-mode-map]'"
  14607. (interactive)
  14608. (let (p)
  14609. (cond
  14610. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14611. ((eq this-command 'cdlatex-math-symbol)
  14612. (setq ad-return-value t
  14613. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14614. (t
  14615. (let ((p (org-inside-LaTeX-fragment-p)))
  14616. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14617. (setq ad-return-value t
  14618. texmathp-why '("Org mode embedded math" . 0))
  14619. (when p ad-do-it)))))))))
  14620. (defun turn-on-org-cdlatex ()
  14621. "Unconditionally turn on `org-cdlatex-mode'."
  14622. (org-cdlatex-mode 1))
  14623. (defun org-try-cdlatex-tab ()
  14624. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14625. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14626. - inside a LaTeX fragment, or
  14627. - after the first word in a line, where an abbreviation expansion could
  14628. insert a LaTeX environment."
  14629. (when org-cdlatex-mode
  14630. (cond
  14631. ;; Before any word on the line: No expansion possible.
  14632. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14633. ;; Just after first word on the line: Expand it. Make sure it
  14634. ;; cannot happen on headlines, though.
  14635. ((save-excursion
  14636. (skip-chars-backward "a-zA-Z0-9*")
  14637. (skip-chars-backward " \t")
  14638. (and (bolp) (not (org-at-heading-p))))
  14639. (cdlatex-tab) t)
  14640. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14641. (defun org-cdlatex-underscore-caret (&optional _arg)
  14642. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14643. Revert to the normal definition outside of these fragments."
  14644. (interactive "P")
  14645. (if (org-inside-LaTeX-fragment-p)
  14646. (call-interactively 'cdlatex-sub-superscript)
  14647. (let (org-cdlatex-mode)
  14648. (call-interactively (key-binding (vector last-input-event))))))
  14649. (defun org-cdlatex-math-modify (&optional _arg)
  14650. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14651. Revert to the normal definition outside of these fragments."
  14652. (interactive "P")
  14653. (if (org-inside-LaTeX-fragment-p)
  14654. (call-interactively 'cdlatex-math-modify)
  14655. (let (org-cdlatex-mode)
  14656. (call-interactively (key-binding (vector last-input-event))))))
  14657. (defun org-cdlatex-environment-indent (&optional environment item)
  14658. "Execute `cdlatex-environment' and indent the inserted environment.
  14659. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14660. The inserted environment is indented to current indentation
  14661. unless point is at the beginning of the line, in which the
  14662. environment remains unintended."
  14663. (interactive)
  14664. ;; cdlatex-environment always return nil. Therefore, capture output
  14665. ;; first and determine if an environment was selected.
  14666. (let* ((beg (point-marker))
  14667. (end (copy-marker (point) t))
  14668. (inserted (progn
  14669. (ignore-errors (cdlatex-environment environment item))
  14670. (< beg end)))
  14671. ;; Figure out how many lines to move forward after the
  14672. ;; environment has been inserted.
  14673. (lines (when inserted
  14674. (save-excursion
  14675. (- (cl-loop while (< beg (point))
  14676. with x = 0
  14677. do (forward-line -1)
  14678. (cl-incf x)
  14679. finally return x)
  14680. (if (progn (goto-char beg)
  14681. (and (progn (skip-chars-forward " \t") (eolp))
  14682. (progn (skip-chars-backward " \t") (bolp))))
  14683. 1 0)))))
  14684. (env (org-trim (delete-and-extract-region beg end))))
  14685. (when inserted
  14686. ;; Get indentation of next line unless at column 0.
  14687. (let ((ind (if (bolp) 0
  14688. (save-excursion
  14689. (org-return-indent)
  14690. (prog1 (current-indentation)
  14691. (when (progn (skip-chars-forward " \t") (eolp))
  14692. (delete-region beg (point)))))))
  14693. (bol (progn (skip-chars-backward " \t") (bolp))))
  14694. ;; Insert a newline before environment unless at column zero
  14695. ;; to "escape" the current line. Insert a newline if
  14696. ;; something is one the same line as \end{ENVIRONMENT}.
  14697. (insert
  14698. (concat (unless bol "\n") env
  14699. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14700. (unless (zerop ind)
  14701. (save-excursion
  14702. (goto-char beg)
  14703. (while (< (point) end)
  14704. (unless (eolp) (indent-line-to ind))
  14705. (forward-line))))
  14706. (goto-char beg)
  14707. (forward-line lines)
  14708. (indent-line-to ind)))
  14709. (set-marker beg nil)
  14710. (set-marker end nil)))
  14711. ;;;; LaTeX fragments
  14712. (defun org-inside-LaTeX-fragment-p ()
  14713. "Test if point is inside a LaTeX fragment.
  14714. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14715. sequence appearing also before point.
  14716. Even though the matchers for math are configurable, this function assumes
  14717. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14718. delimiters are skipped when they have been removed by customization.
  14719. The return value is nil, or a cons cell with the delimiter and the
  14720. position of this delimiter.
  14721. This function does a reasonably good job, but can locally be fooled by
  14722. for example currency specifications. For example it will assume being in
  14723. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14724. fragments that are properly closed, but during editing, we have to live
  14725. with the uncertainty caused by missing closing delimiters. This function
  14726. looks only before point, not after."
  14727. (catch 'exit
  14728. (let ((pos (point))
  14729. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14730. (lim (save-excursion (org-backward-paragraph) (point)))
  14731. dd-on str (start 0) m re)
  14732. (goto-char pos)
  14733. (when dodollar
  14734. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14735. re (nth 1 (assoc "$" org-latex-regexps)))
  14736. (while (string-match re str start)
  14737. (cond
  14738. ((= (match-end 0) (length str))
  14739. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14740. ((= (match-end 0) (- (length str) 5))
  14741. (throw 'exit nil))
  14742. (t (setq start (match-end 0))))))
  14743. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14744. (goto-char pos)
  14745. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14746. (and (match-beginning 2) (throw 'exit nil))
  14747. ;; count $$
  14748. (while (re-search-backward "\\$\\$" lim t)
  14749. (setq dd-on (not dd-on)))
  14750. (goto-char pos)
  14751. (when dd-on (cons "$$" m))))))
  14752. (defun org-inside-latex-macro-p ()
  14753. "Is point inside a LaTeX macro or its arguments?"
  14754. (save-match-data
  14755. (org-in-regexp
  14756. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14757. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14758. "Build an overlay between BEG and END using IMAGE file.
  14759. Argument IMAGETYPE is the extension of the displayed image,
  14760. as a string. It defaults to \"png\"."
  14761. (let ((ov (make-overlay beg end))
  14762. (imagetype (or (intern imagetype) 'png)))
  14763. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14764. (overlay-put ov 'evaporate t)
  14765. (overlay-put ov
  14766. 'modification-hooks
  14767. (list (lambda (o _flag _beg _end &optional _l)
  14768. (delete-overlay o))))
  14769. (overlay-put ov
  14770. 'display
  14771. (list 'image :type imagetype :file image :ascent 'center))))
  14772. (defun org-clear-latex-preview (&optional beg end)
  14773. "Remove all overlays with LaTeX fragment images in current buffer.
  14774. When optional arguments BEG and END are non-nil, remove all
  14775. overlays between them instead. Return a non-nil value when some
  14776. overlays were removed, nil otherwise."
  14777. (let ((overlays
  14778. (cl-remove-if-not
  14779. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14780. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14781. (mapc #'delete-overlay overlays)
  14782. overlays))
  14783. (defun org--latex-preview-region (beg end)
  14784. "Preview LaTeX fragments between BEG and END.
  14785. BEG and END are buffer positions."
  14786. (let ((file (buffer-file-name (buffer-base-buffer))))
  14787. (save-excursion
  14788. (org-format-latex
  14789. (concat org-preview-latex-image-directory "org-ltximg")
  14790. beg end
  14791. ;; Emacs cannot overlay images from remote hosts. Create it in
  14792. ;; `temporary-file-directory' instead.
  14793. (if (or (not file) (file-remote-p file))
  14794. temporary-file-directory
  14795. default-directory)
  14796. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14797. (defun org-latex-preview (&optional arg)
  14798. "Toggle preview of the LaTeX fragment at point.
  14799. If the cursor is on a LaTeX fragment, create the image and
  14800. overlay it over the source code, if there is none. Remove it
  14801. otherwise. If there is no fragment at point, display images for
  14802. all fragments in the current section.
  14803. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14804. for all fragments
  14805. in the current section.
  14806. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14807. argument ARG, display image for all
  14808. fragments in the buffer.
  14809. With a `\\[universal-argument] \\[universal-argument] \
  14810. \\[universal-argument]' prefix argument ARG, clear image for all
  14811. fragments in the buffer."
  14812. (interactive "P")
  14813. (cond
  14814. ((not (display-graphic-p)) nil)
  14815. ;; Clear whole buffer.
  14816. ((equal arg '(64))
  14817. (org-clear-latex-preview (point-min) (point-max))
  14818. (message "LaTeX previews removed from buffer"))
  14819. ;; Preview whole buffer.
  14820. ((equal arg '(16))
  14821. (message "Creating LaTeX previews in buffer...")
  14822. (org--latex-preview-region (point-min) (point-max))
  14823. (message "Creating LaTeX previews in buffer... done."))
  14824. ;; Clear current section.
  14825. ((equal arg '(4))
  14826. (org-clear-latex-preview
  14827. (if (org-before-first-heading-p) (point-min)
  14828. (save-excursion
  14829. (org-with-limited-levels (org-back-to-heading t) (point))))
  14830. (org-with-limited-levels (org-entry-end-position))))
  14831. ;; Toggle preview on LaTeX code at point.
  14832. ((let ((datum (org-element-context)))
  14833. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14834. (let ((beg (org-element-property :begin datum))
  14835. (end (org-element-property :end datum)))
  14836. (if (org-clear-latex-preview beg end)
  14837. (message "LaTeX preview removed")
  14838. (message "Creating LaTeX preview...")
  14839. (org--latex-preview-region beg end)
  14840. (message "Creating LaTeX preview... done."))
  14841. t))))
  14842. ;; Preview current section.
  14843. (t
  14844. (let ((beg (if (org-before-first-heading-p) (point-min)
  14845. (save-excursion
  14846. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14847. (end (org-with-limited-levels (org-entry-end-position))))
  14848. (message "Creating LaTeX previews in section...")
  14849. (org--latex-preview-region beg end)
  14850. (message "Creating LaTeX previews in section... done.")))))
  14851. (defun org-format-latex
  14852. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14853. "Replace LaTeX fragments with links to an image.
  14854. The function takes care of creating the replacement image.
  14855. Only consider fragments between BEG and END when those are
  14856. provided.
  14857. When optional argument OVERLAYS is non-nil, display the image on
  14858. top of the fragment instead of replacing it.
  14859. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14860. Some of the options can be changed using the variable
  14861. `org-format-latex-options', which see."
  14862. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14863. (unless (eq processing-type 'verbatim)
  14864. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14865. (cnt 0)
  14866. checkdir-flag)
  14867. (goto-char (or beg (point-min)))
  14868. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14869. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14870. (overlay-recenter (or end (point-max))))
  14871. (while (re-search-forward math-regexp end t)
  14872. (unless (and overlays
  14873. (eq (get-char-property (point) 'org-overlay-type)
  14874. 'org-latex-overlay))
  14875. (let* ((context (org-element-context))
  14876. (type (org-element-type context)))
  14877. (when (memq type '(latex-environment latex-fragment))
  14878. (let ((block-type (eq type 'latex-environment))
  14879. (value (org-element-property :value context))
  14880. (beg (org-element-property :begin context))
  14881. (end (save-excursion
  14882. (goto-char (org-element-property :end context))
  14883. (skip-chars-backward " \r\t\n")
  14884. (point))))
  14885. (cond
  14886. ((eq processing-type 'mathjax)
  14887. ;; Prepare for MathJax processing.
  14888. (if (not (string-match "\\`\\$\\$?" value))
  14889. (goto-char end)
  14890. (delete-region beg end)
  14891. (if (string= (match-string 0 value) "$$")
  14892. (insert "\\[" (substring value 2 -2) "\\]")
  14893. (insert "\\(" (substring value 1 -1) "\\)"))))
  14894. ((assq processing-type org-preview-latex-process-alist)
  14895. ;; Process to an image.
  14896. (cl-incf cnt)
  14897. (goto-char beg)
  14898. (let* ((processing-info
  14899. (cdr (assq processing-type org-preview-latex-process-alist)))
  14900. (face (face-at-point))
  14901. ;; Get the colors from the face at point.
  14902. (fg
  14903. (let ((color (plist-get org-format-latex-options
  14904. :foreground)))
  14905. (if (and forbuffer (eq color 'auto))
  14906. (face-attribute face :foreground nil 'default)
  14907. color)))
  14908. (bg
  14909. (let ((color (plist-get org-format-latex-options
  14910. :background)))
  14911. (if (and forbuffer (eq color 'auto))
  14912. (face-attribute face :background nil 'default)
  14913. color)))
  14914. (hash (sha1 (prin1-to-string
  14915. (list org-format-latex-header
  14916. org-latex-default-packages-alist
  14917. org-latex-packages-alist
  14918. org-format-latex-options
  14919. forbuffer value fg bg))))
  14920. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14921. (absprefix (expand-file-name prefix dir))
  14922. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14923. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14924. (sep (and block-type "\n\n"))
  14925. (link (concat sep "[[file:" linkfile "]]" sep))
  14926. (options
  14927. (org-combine-plists
  14928. org-format-latex-options
  14929. `(:foreground ,fg :background ,bg))))
  14930. (when msg (message msg cnt))
  14931. (unless checkdir-flag ; Ensure the directory exists.
  14932. (setq checkdir-flag t)
  14933. (let ((todir (file-name-directory absprefix)))
  14934. (unless (file-directory-p todir)
  14935. (make-directory todir t))))
  14936. (unless (file-exists-p movefile)
  14937. (org-create-formula-image
  14938. value movefile options forbuffer processing-type))
  14939. (if overlays
  14940. (progn
  14941. (dolist (o (overlays-in beg end))
  14942. (when (eq (overlay-get o 'org-overlay-type)
  14943. 'org-latex-overlay)
  14944. (delete-overlay o)))
  14945. (org--make-preview-overlay beg end movefile imagetype)
  14946. (goto-char end))
  14947. (delete-region beg end)
  14948. (insert
  14949. (org-add-props link
  14950. (list 'org-latex-src
  14951. (replace-regexp-in-string "\"" "" value)
  14952. 'org-latex-src-embed-type
  14953. (if block-type 'paragraph 'character)))))))
  14954. ((eq processing-type 'mathml)
  14955. ;; Process to MathML.
  14956. (unless (org-format-latex-mathml-available-p)
  14957. (user-error "LaTeX to MathML converter not configured"))
  14958. (cl-incf cnt)
  14959. (when msg (message msg cnt))
  14960. (goto-char beg)
  14961. (delete-region beg end)
  14962. (insert (org-format-latex-as-mathml
  14963. value block-type prefix dir)))
  14964. (t
  14965. (error "Unknown conversion process %s for LaTeX fragments"
  14966. processing-type)))))))))))
  14967. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14968. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14969. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14970. successful, return the portion between \"<math...> </math>\"
  14971. elements otherwise return nil. When MATHML-FILE is specified,
  14972. write the results in to that file. When invoked as an
  14973. interactive command, prompt for LATEX-FRAG, with initial value
  14974. set to the current active region and echo the results for user
  14975. inspection."
  14976. (interactive (list (let ((frag (when (org-region-active-p)
  14977. (buffer-substring-no-properties
  14978. (region-beginning) (region-end)))))
  14979. (read-string "LaTeX Fragment: " frag nil frag))))
  14980. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14981. (let* ((tmp-in-file
  14982. (let ((file (file-relative-name
  14983. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14984. (write-region latex-frag nil file)
  14985. file))
  14986. (tmp-out-file (file-relative-name
  14987. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14988. (cmd (format-spec
  14989. org-latex-to-mathml-convert-command
  14990. `((?j . ,(and org-latex-to-mathml-jar-file
  14991. (shell-quote-argument
  14992. (expand-file-name
  14993. org-latex-to-mathml-jar-file))))
  14994. (?I . ,(shell-quote-argument tmp-in-file))
  14995. (?i . ,latex-frag)
  14996. (?o . ,(shell-quote-argument tmp-out-file)))))
  14997. mathml shell-command-output)
  14998. (when (called-interactively-p 'any)
  14999. (unless (org-format-latex-mathml-available-p)
  15000. (user-error "LaTeX to MathML converter not configured")))
  15001. (message "Running %s" cmd)
  15002. (setq shell-command-output (shell-command-to-string cmd))
  15003. (setq mathml
  15004. (when (file-readable-p tmp-out-file)
  15005. (with-current-buffer (find-file-noselect tmp-out-file t)
  15006. (goto-char (point-min))
  15007. (when (re-search-forward
  15008. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  15009. (regexp-quote
  15010. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  15011. nil t)
  15012. (prog1 (match-string 0) (kill-buffer))))))
  15013. (cond
  15014. (mathml
  15015. (setq mathml
  15016. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  15017. (when mathml-file
  15018. (write-region mathml nil mathml-file))
  15019. (when (called-interactively-p 'any)
  15020. (message mathml)))
  15021. ((message "LaTeX to MathML conversion failed")
  15022. (message shell-command-output)))
  15023. (delete-file tmp-in-file)
  15024. (when (file-exists-p tmp-out-file)
  15025. (delete-file tmp-out-file))
  15026. mathml))
  15027. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  15028. prefix &optional dir)
  15029. "Use `org-create-math-formula' but check local cache first."
  15030. (let* ((absprefix (expand-file-name prefix dir))
  15031. (print-length nil) (print-level nil)
  15032. (formula-id (concat
  15033. "formula-"
  15034. (sha1
  15035. (prin1-to-string
  15036. (list latex-frag
  15037. org-latex-to-mathml-convert-command)))))
  15038. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  15039. (formula-cache-dir (file-name-directory formula-cache)))
  15040. (unless (file-directory-p formula-cache-dir)
  15041. (make-directory formula-cache-dir t))
  15042. (unless (file-exists-p formula-cache)
  15043. (org-create-math-formula latex-frag formula-cache))
  15044. (if (file-exists-p formula-cache)
  15045. ;; Successful conversion. Return the link to MathML file.
  15046. (org-add-props
  15047. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  15048. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  15049. 'org-latex-src-embed-type (if latex-frag-type
  15050. 'paragraph 'character)))
  15051. ;; Failed conversion. Return the LaTeX fragment verbatim
  15052. latex-frag)))
  15053. (defun org--get-display-dpi ()
  15054. "Get the DPI of the display.
  15055. The function assumes that the display has the same pixel width in
  15056. the horizontal and vertical directions."
  15057. (if (display-graphic-p)
  15058. (round (/ (display-pixel-height)
  15059. (/ (display-mm-height) 25.4)))
  15060. (error "Attempt to calculate the dpi of a non-graphic display")))
  15061. (defun org-create-formula-image
  15062. (string tofile options buffer &optional processing-type)
  15063. "Create an image from LaTeX source using external processes.
  15064. The LaTeX STRING is saved to a temporary LaTeX file, then
  15065. converted to an image file by process PROCESSING-TYPE defined in
  15066. `org-preview-latex-process-alist'. A nil value defaults to
  15067. `org-preview-latex-default-process'.
  15068. The generated image file is eventually moved to TOFILE.
  15069. The OPTIONS argument controls the size, foreground color and
  15070. background color of the generated image.
  15071. When BUFFER non-nil, this function is used for LaTeX previewing.
  15072. Otherwise, it is used to deal with LaTeX snippets showed in
  15073. a HTML file."
  15074. (let* ((processing-type (or processing-type
  15075. org-preview-latex-default-process))
  15076. (processing-info
  15077. (cdr (assq processing-type org-preview-latex-process-alist)))
  15078. (programs (plist-get processing-info :programs))
  15079. (error-message (or (plist-get processing-info :message) ""))
  15080. (image-input-type (plist-get processing-info :image-input-type))
  15081. (image-output-type (plist-get processing-info :image-output-type))
  15082. (post-clean (or (plist-get processing-info :post-clean)
  15083. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  15084. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  15085. (latex-header
  15086. (or (plist-get processing-info :latex-header)
  15087. (org-latex-make-preamble
  15088. (org-export-get-environment (org-export-get-backend 'latex))
  15089. org-format-latex-header
  15090. 'snippet)))
  15091. (latex-compiler (plist-get processing-info :latex-compiler))
  15092. (image-converter (plist-get processing-info :image-converter))
  15093. (tmpdir temporary-file-directory)
  15094. (texfilebase (make-temp-name
  15095. (expand-file-name "orgtex" tmpdir)))
  15096. (texfile (concat texfilebase ".tex"))
  15097. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  15098. '(1.0 . 1.0)))
  15099. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  15100. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  15101. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  15102. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  15103. "Black"))
  15104. (bg (or (plist-get options (if buffer :background :html-background))
  15105. "Transparent"))
  15106. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  15107. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  15108. (dolist (program programs)
  15109. (org-check-external-command program error-message))
  15110. (if (eq fg 'default)
  15111. (setq fg (org-latex-color :foreground))
  15112. (setq fg (org-latex-color-format fg)))
  15113. (if (eq bg 'default)
  15114. (setq bg (org-latex-color :background))
  15115. (setq bg (org-latex-color-format
  15116. (if (string= bg "Transparent") "white" bg))))
  15117. ;; Remove TeX \par at end of snippet to avoid trailing space.
  15118. (if (string-suffix-p string "\n")
  15119. (aset string (1- (length string)) ?%)
  15120. (setq string (concat string "%")))
  15121. (with-temp-file texfile
  15122. (insert latex-header)
  15123. (insert "\n\\begin{document}\n"
  15124. "\\definecolor{fg}{rgb}{" fg "}%\n"
  15125. "\\definecolor{bg}{rgb}{" bg "}%\n"
  15126. "\n\\pagecolor{bg}%\n"
  15127. "\n{\\color{fg}\n"
  15128. string
  15129. "\n}\n"
  15130. "\n\\end{document}\n"))
  15131. (let* ((err-msg (format "Please adjust `%s' part of \
  15132. `org-preview-latex-process-alist'."
  15133. processing-type))
  15134. (image-input-file
  15135. (org-compile-file
  15136. texfile latex-compiler image-input-type err-msg log-buf))
  15137. (image-output-file
  15138. (org-compile-file
  15139. image-input-file image-converter image-output-type err-msg log-buf
  15140. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  15141. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  15142. (copy-file image-output-file tofile 'replace)
  15143. (dolist (e post-clean)
  15144. (when (file-exists-p (concat texfilebase e))
  15145. (delete-file (concat texfilebase e))))
  15146. image-output-file)))
  15147. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  15148. "Fill a LaTeX header template TPL.
  15149. In the template, the following place holders will be recognized:
  15150. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  15151. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  15152. [PACKAGES] \\usepackage statements for PKG
  15153. [NO-PACKAGES] do not include PKG
  15154. [EXTRA] the string EXTRA
  15155. [NO-EXTRA] do not include EXTRA
  15156. For backward compatibility, if both the positive and the negative place
  15157. holder is missing, the positive one (without the \"NO-\") will be
  15158. assumed to be present at the end of the template.
  15159. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  15160. EXTRA is a string.
  15161. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  15162. (let (rpl (end ""))
  15163. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  15164. (setq rpl (if (or (match-end 1) (not def-pkg))
  15165. "" (org-latex-packages-to-string def-pkg snippets-p t))
  15166. tpl (replace-match rpl t t tpl))
  15167. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  15168. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  15169. (setq rpl (if (or (match-end 1) (not pkg))
  15170. "" (org-latex-packages-to-string pkg snippets-p t))
  15171. tpl (replace-match rpl t t tpl))
  15172. (when pkg (setq end
  15173. (concat end "\n"
  15174. (org-latex-packages-to-string pkg snippets-p)))))
  15175. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  15176. (setq rpl (if (or (match-end 1) (not extra))
  15177. "" (concat extra "\n"))
  15178. tpl (replace-match rpl t t tpl))
  15179. (when (and extra (string-match "\\S-" extra))
  15180. (setq end (concat end "\n" extra))))
  15181. (if (string-match "\\S-" end)
  15182. (concat tpl "\n" end)
  15183. tpl)))
  15184. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  15185. "Turn an alist of packages into a string with the \\usepackage macros."
  15186. (setq pkg (mapconcat (lambda(p)
  15187. (cond
  15188. ((stringp p) p)
  15189. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  15190. (format "%% Package %s omitted" (cadr p)))
  15191. ((equal "" (car p))
  15192. (format "\\usepackage{%s}" (cadr p)))
  15193. (t
  15194. (format "\\usepackage[%s]{%s}"
  15195. (car p) (cadr p)))))
  15196. pkg
  15197. "\n"))
  15198. (if newline (concat pkg "\n") pkg))
  15199. (defun org-dvipng-color (attr)
  15200. "Return a RGB color specification for dvipng."
  15201. (org-dvipng-color-format (face-attribute 'default attr nil)))
  15202. (defun org-dvipng-color-format (color-name)
  15203. "Convert COLOR-NAME to a RGB color value for dvipng."
  15204. (apply #'format "rgb %s %s %s"
  15205. (mapcar 'org-normalize-color
  15206. (color-values color-name))))
  15207. (defun org-latex-color (attr)
  15208. "Return a RGB color for the LaTeX color package."
  15209. (org-latex-color-format (face-attribute 'default attr nil)))
  15210. (defun org-latex-color-format (color-name)
  15211. "Convert COLOR-NAME to a RGB color value."
  15212. (apply #'format "%s,%s,%s"
  15213. (mapcar 'org-normalize-color
  15214. (color-values color-name))))
  15215. (defun org-normalize-color (value)
  15216. "Return string to be used as color value for an RGB component."
  15217. (format "%g" (/ value 65535.0)))
  15218. ;; Image display
  15219. (defvar-local org-inline-image-overlays nil)
  15220. (defun org-toggle-inline-images (&optional include-linked)
  15221. "Toggle the display of inline images.
  15222. INCLUDE-LINKED is passed to `org-display-inline-images'."
  15223. (interactive "P")
  15224. (if org-inline-image-overlays
  15225. (progn
  15226. (org-remove-inline-images)
  15227. (when (called-interactively-p 'interactive)
  15228. (message "Inline image display turned off")))
  15229. (org-display-inline-images include-linked)
  15230. (when (called-interactively-p 'interactive)
  15231. (message (if org-inline-image-overlays
  15232. (format "%d images displayed inline"
  15233. (length org-inline-image-overlays))
  15234. "No images to display inline")))))
  15235. (defun org-redisplay-inline-images ()
  15236. "Refresh the display of inline images."
  15237. (interactive)
  15238. (if (not org-inline-image-overlays)
  15239. (org-toggle-inline-images)
  15240. (org-toggle-inline-images)
  15241. (org-toggle-inline-images)))
  15242. ;; For without-x builds.
  15243. (declare-function image-refresh "image" (spec &optional frame))
  15244. (defun org-display-inline-images (&optional include-linked refresh beg end)
  15245. "Display inline images.
  15246. An inline image is a link which follows either of these
  15247. conventions:
  15248. 1. Its path is a file with an extension matching return value
  15249. from `image-file-name-regexp' and it has no contents.
  15250. 2. Its description consists in a single link of the previous
  15251. type. In this case, that link must be a well-formed plain
  15252. or angle link, i.e., it must have an explicit \"file\" type.
  15253. Equip each image with the key-map `image-map'.
  15254. When optional argument INCLUDE-LINKED is non-nil, also links with
  15255. a text description part will be inlined. This can be nice for
  15256. a quick look at those images, but it does not reflect what
  15257. exported files will look like.
  15258. When optional argument REFRESH is non-nil, refresh existing
  15259. images between BEG and END. This will create new image displays
  15260. only if necessary.
  15261. BEG and END define the considered part. They default to the
  15262. buffer boundaries with possible narrowing."
  15263. (interactive "P")
  15264. (when (display-graphic-p)
  15265. (unless refresh
  15266. (org-remove-inline-images)
  15267. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  15268. (let ((end (or end (point-max))))
  15269. (org-with-point-at (or beg (point-min))
  15270. (let* ((case-fold-search t)
  15271. (file-extension-re (image-file-name-regexp))
  15272. (link-abbrevs (mapcar #'car
  15273. (append org-link-abbrev-alist-local
  15274. org-link-abbrev-alist)))
  15275. ;; Check absolute, relative file names and explicit
  15276. ;; "file:" links. Also check link abbreviations since
  15277. ;; some might expand to "file" links.
  15278. (file-types-re
  15279. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  15280. (if (not link-abbrevs) ""
  15281. (concat "\\|" (regexp-opt link-abbrevs))))))
  15282. (while (re-search-forward file-types-re end t)
  15283. (let* ((link (org-element-lineage
  15284. (save-match-data (org-element-context))
  15285. '(link) t))
  15286. (linktype (org-element-property :type link))
  15287. (inner-start (match-beginning 1))
  15288. (path
  15289. (cond
  15290. ;; No link at point; no inline image.
  15291. ((not link) nil)
  15292. ;; File link without a description. Also handle
  15293. ;; INCLUDE-LINKED here since it should have
  15294. ;; precedence over the next case. I.e., if link
  15295. ;; contains filenames in both the path and the
  15296. ;; description, prioritize the path only when
  15297. ;; INCLUDE-LINKED is non-nil.
  15298. ((or (not (org-element-property :contents-begin link))
  15299. include-linked)
  15300. (and (or (equal "file" linktype)
  15301. (equal "attachment" linktype))
  15302. (org-element-property :path link)))
  15303. ;; Link with a description. Check if description
  15304. ;; is a filename. Even if Org doesn't have syntax
  15305. ;; for those -- clickable image -- constructs, fake
  15306. ;; them, as in `org-export-insert-image-links'.
  15307. ((not inner-start) nil)
  15308. (t
  15309. (org-with-point-at inner-start
  15310. (and (looking-at
  15311. (if (char-equal ?< (char-after inner-start))
  15312. org-link-angle-re
  15313. org-link-plain-re))
  15314. ;; File name must fill the whole
  15315. ;; description.
  15316. (= (org-element-property :contents-end link)
  15317. (match-end 0))
  15318. (match-string 2)))))))
  15319. (when (and path (string-match-p file-extension-re path))
  15320. (let ((file (if (equal "attachment" linktype)
  15321. (progn
  15322. (require 'org-attach)
  15323. (ignore-errors (org-attach-expand path)))
  15324. (expand-file-name path))))
  15325. (when (and file (file-exists-p file))
  15326. (let ((width
  15327. ;; Apply `org-image-actual-width' specifications.
  15328. (cond
  15329. ((eq org-image-actual-width t) nil)
  15330. ((listp org-image-actual-width)
  15331. (or
  15332. ;; First try to find a width among
  15333. ;; attributes associated to the paragraph
  15334. ;; containing link.
  15335. (pcase (org-element-lineage link '(paragraph))
  15336. (`nil nil)
  15337. (p
  15338. (let* ((case-fold-search t)
  15339. (end (org-element-property :post-affiliated p))
  15340. (re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"))
  15341. (when (org-with-point-at
  15342. (org-element-property :begin p)
  15343. (re-search-forward re end t))
  15344. (string-to-number (match-string 1))))))
  15345. ;; Otherwise, fall-back to provided number.
  15346. (car org-image-actual-width)))
  15347. ((numberp org-image-actual-width)
  15348. org-image-actual-width)
  15349. (t nil)))
  15350. (old (get-char-property-and-overlay
  15351. (org-element-property :begin link)
  15352. 'org-image-overlay)))
  15353. (if (and (car-safe old) refresh)
  15354. (image-refresh (overlay-get (cdr old) 'display))
  15355. (let ((image (create-image file
  15356. (and (image-type-available-p 'imagemagick)
  15357. width 'imagemagick)
  15358. nil
  15359. :width width)))
  15360. (when image
  15361. (let ((ov (make-overlay
  15362. (org-element-property :begin link)
  15363. (progn
  15364. (goto-char
  15365. (org-element-property :end link))
  15366. (skip-chars-backward " \t")
  15367. (point)))))
  15368. (overlay-put ov 'display image)
  15369. (overlay-put ov 'face 'default)
  15370. (overlay-put ov 'org-image-overlay t)
  15371. (overlay-put
  15372. ov 'modification-hooks
  15373. (list 'org-display-inline-remove-overlay))
  15374. (when (<= 26 emacs-major-version)
  15375. (cl-assert (boundp 'image-map))
  15376. (overlay-put ov 'keymap image-map))
  15377. (push ov org-inline-image-overlays))))))))))))))))
  15378. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  15379. "Remove inline-display overlay if a corresponding region is modified."
  15380. (let ((inhibit-modification-hooks t))
  15381. (when (and ov after)
  15382. (delete ov org-inline-image-overlays)
  15383. (delete-overlay ov))))
  15384. (defun org-remove-inline-images ()
  15385. "Remove inline display of images."
  15386. (interactive)
  15387. (mapc #'delete-overlay org-inline-image-overlays)
  15388. (setq org-inline-image-overlays nil))
  15389. (defvar org-self-insert-command-undo-counter 0)
  15390. (defvar org-speed-command nil)
  15391. (defun org-self-insert-command (N)
  15392. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  15393. If the cursor is in a table looking at whitespace, the whitespace is
  15394. overwritten, and the table is not marked as requiring realignment."
  15395. (interactive "p")
  15396. (org-check-before-invisible-edit 'insert)
  15397. (cond
  15398. ((and org-use-speed-commands
  15399. (let ((kv (this-command-keys-vector)))
  15400. (setq org-speed-command
  15401. (run-hook-with-args-until-success
  15402. 'org-speed-command-hook
  15403. (make-string 1 (aref kv (1- (length kv))))))))
  15404. (cond
  15405. ((commandp org-speed-command)
  15406. (setq this-command org-speed-command)
  15407. (call-interactively org-speed-command))
  15408. ((functionp org-speed-command)
  15409. (funcall org-speed-command))
  15410. ((and org-speed-command (listp org-speed-command))
  15411. (eval org-speed-command))
  15412. (t (let (org-use-speed-commands)
  15413. (call-interactively 'org-self-insert-command)))))
  15414. ((and
  15415. (= N 1)
  15416. (not (org-region-active-p))
  15417. (org-at-table-p)
  15418. (progn
  15419. ;; Check if we blank the field, and if that triggers align.
  15420. (and (featurep 'org-table)
  15421. org-table-auto-blank-field
  15422. (memq last-command
  15423. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  15424. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  15425. ;; Got extra space, this field does not determine
  15426. ;; column width.
  15427. (let (org-table-may-need-update) (org-table-blank-field))
  15428. ;; No extra space, this field may determine column
  15429. ;; width.
  15430. (org-table-blank-field)))
  15431. t)
  15432. (looking-at "[^|\n]* |"))
  15433. ;; There is room for insertion without re-aligning the table.
  15434. (self-insert-command N)
  15435. (org-table-with-shrunk-field
  15436. (save-excursion
  15437. (skip-chars-forward "^|")
  15438. ;; Do not delete last space, which is
  15439. ;; `org-table-separator-space', but the regular space before
  15440. ;; it.
  15441. (delete-region (- (point) 2) (1- (point))))))
  15442. (t
  15443. (setq org-table-may-need-update t)
  15444. (self-insert-command N)
  15445. (org-fix-tags-on-the-fly)
  15446. (when org-self-insert-cluster-for-undo
  15447. (if (not (eq last-command 'org-self-insert-command))
  15448. (setq org-self-insert-command-undo-counter 1)
  15449. (if (>= org-self-insert-command-undo-counter 20)
  15450. (setq org-self-insert-command-undo-counter 1)
  15451. (and (> org-self-insert-command-undo-counter 0)
  15452. buffer-undo-list (listp buffer-undo-list)
  15453. (not (cadr buffer-undo-list)) ; remove nil entry
  15454. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15455. (setq org-self-insert-command-undo-counter
  15456. (1+ org-self-insert-command-undo-counter))))))))
  15457. (defun org-check-before-invisible-edit (kind)
  15458. "Check is editing if kind KIND would be dangerous with invisible text around.
  15459. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15460. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15461. (when (and org-catch-invisible-edits
  15462. (or (not (boundp 'visible-mode)) (not visible-mode))
  15463. (or (get-char-property (point) 'invisible)
  15464. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15465. ;; OK, we need to take a closer look. Do not consider
  15466. ;; invisibility obtained through text properties (e.g., link
  15467. ;; fontification), as it cannot be toggled.
  15468. (let* ((invisible-at-point
  15469. (pcase (get-char-property-and-overlay (point) 'invisible)
  15470. (`(,_ . ,(and (pred overlayp) o)) o)))
  15471. ;; Assume that point cannot land in the middle of an
  15472. ;; overlay, or between two overlays.
  15473. (invisible-before-point
  15474. (and (not invisible-at-point)
  15475. (not (bobp))
  15476. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15477. (`(,_ . ,(and (pred overlayp) o)) o))))
  15478. (border-and-ok-direction
  15479. (or
  15480. ;; Check if we are acting predictably before invisible
  15481. ;; text.
  15482. (and invisible-at-point
  15483. (memq kind '(insert delete-backward)))
  15484. ;; Check if we are acting predictably after invisible text
  15485. ;; This works not well, and I have turned it off. It seems
  15486. ;; better to always show and stop after invisible text.
  15487. ;; (and (not invisible-at-point) invisible-before-point
  15488. ;; (memq kind '(insert delete)))
  15489. )))
  15490. (when (or invisible-at-point invisible-before-point)
  15491. (when (eq org-catch-invisible-edits 'error)
  15492. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15493. (if (and org-custom-properties-overlays
  15494. (y-or-n-p "Display invisible properties in this buffer? "))
  15495. (org-toggle-custom-properties-visibility)
  15496. ;; Make the area visible
  15497. (save-excursion
  15498. (when invisible-before-point
  15499. (goto-char
  15500. (previous-single-char-property-change (point) 'invisible)))
  15501. ;; Remove whatever overlay is currently making yet-to-be
  15502. ;; edited text invisible. Also remove nested invisibility
  15503. ;; related overlays.
  15504. (delete-overlay (or invisible-at-point invisible-before-point))
  15505. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15506. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15507. (`(,_ . ,(and (pred overlayp) o))
  15508. (delete-overlay o)
  15509. t)))))
  15510. (cond
  15511. ((eq org-catch-invisible-edits 'show)
  15512. ;; That's it, we do the edit after showing
  15513. (message
  15514. "Unfolding invisible region around point before editing")
  15515. (sit-for 1))
  15516. ((and (eq org-catch-invisible-edits 'smart)
  15517. border-and-ok-direction)
  15518. (message "Unfolding invisible region around point before editing"))
  15519. (t
  15520. ;; Don't do the edit, make the user repeat it in full visibility
  15521. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15522. (defun org-fix-tags-on-the-fly ()
  15523. "Align tags in headline at point.
  15524. Unlike `org-align-tags', this function does nothing if point is
  15525. either not currently on a tagged headline or on a tag."
  15526. (when (and (org-match-line org-tag-line-re)
  15527. (< (point) (match-beginning 1)))
  15528. (org-align-tags)))
  15529. (defun org-delete-backward-char (N)
  15530. "Like `delete-backward-char', insert whitespace at field end in tables.
  15531. When deleting backwards, in tables this function will insert whitespace in
  15532. front of the next \"|\" separator, to keep the table aligned. The table will
  15533. still be marked for re-alignment if the field did fill the entire column,
  15534. because, in this case the deletion might narrow the column."
  15535. (interactive "p")
  15536. (save-match-data
  15537. (org-check-before-invisible-edit 'delete-backward)
  15538. (if (and (= N 1)
  15539. (not overwrite-mode)
  15540. (not (org-region-active-p))
  15541. (not (eq (char-before) ?|))
  15542. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15543. (looking-at-p ".*?|")
  15544. (org-at-table-p))
  15545. (progn (forward-char -1) (org-delete-char 1))
  15546. (backward-delete-char N)
  15547. (org-fix-tags-on-the-fly))))
  15548. (defun org-delete-char (N)
  15549. "Like `delete-char', but insert whitespace at field end in tables.
  15550. When deleting characters, in tables this function will insert whitespace in
  15551. front of the next \"|\" separator, to keep the table aligned. The table will
  15552. still be marked for re-alignment if the field did fill the entire column,
  15553. because, in this case the deletion might narrow the column."
  15554. (interactive "p")
  15555. (save-match-data
  15556. (org-check-before-invisible-edit 'delete)
  15557. (cond
  15558. ((or (/= N 1)
  15559. (eq (char-after) ?|)
  15560. (save-excursion (skip-chars-backward " \t") (bolp))
  15561. (not (org-at-table-p)))
  15562. (delete-char N)
  15563. (org-fix-tags-on-the-fly))
  15564. ((looking-at ".\\(.*?\\)|")
  15565. (let* ((update? org-table-may-need-update)
  15566. (noalign (looking-at-p ".*? |")))
  15567. (delete-char 1)
  15568. (org-table-with-shrunk-field
  15569. (save-excursion
  15570. ;; Last space is `org-table-separator-space', so insert
  15571. ;; a regular one before it instead.
  15572. (goto-char (- (match-end 0) 2))
  15573. (insert " ")))
  15574. ;; If there were two spaces at the end, this field does not
  15575. ;; determine the width of the column.
  15576. (when noalign (setq org-table-may-need-update update?))))
  15577. (t
  15578. (delete-char N)))))
  15579. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15580. (put 'org-self-insert-command 'delete-selection
  15581. (lambda ()
  15582. (not (run-hook-with-args-until-success
  15583. 'self-insert-uses-region-functions))))
  15584. (put 'orgtbl-self-insert-command 'delete-selection
  15585. (lambda ()
  15586. (not (run-hook-with-args-until-success
  15587. 'self-insert-uses-region-functions))))
  15588. (put 'org-delete-char 'delete-selection 'supersede)
  15589. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15590. (put 'org-yank 'delete-selection 'yank)
  15591. ;; Make `flyspell-mode' delay after some commands
  15592. (put 'org-self-insert-command 'flyspell-delayed t)
  15593. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15594. (put 'org-delete-char 'flyspell-delayed t)
  15595. (put 'org-delete-backward-char 'flyspell-delayed t)
  15596. ;; Make pabbrev-mode expand after Org mode commands
  15597. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15598. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15599. (defun org-transpose-words ()
  15600. "Transpose words for Org.
  15601. This uses the `org-mode-transpose-word-syntax-table' syntax
  15602. table, which interprets characters in `org-emphasis-alist' as
  15603. word constituents."
  15604. (interactive)
  15605. (with-syntax-table org-mode-transpose-word-syntax-table
  15606. (call-interactively 'transpose-words)))
  15607. (defvar org-ctrl-c-ctrl-c-hook nil
  15608. "Hook for functions attaching themselves to `C-c C-c'.
  15609. This can be used to add additional functionality to the C-c C-c
  15610. key which executes context-dependent commands. This hook is run
  15611. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15612. run after the last test.
  15613. Each function will be called with no arguments. The function
  15614. must check if the context is appropriate for it to act. If yes,
  15615. it should do its thing and then return a non-nil value. If the
  15616. context is wrong, just do nothing and return nil.")
  15617. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15618. "Hook for functions attaching themselves to `C-c C-c'.
  15619. This can be used to add additional functionality to the C-c C-c
  15620. key which executes context-dependent commands. This hook is run
  15621. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15622. before the first test.
  15623. Each function will be called with no arguments. The function
  15624. must check if the context is appropriate for it to act. If yes,
  15625. it should do its thing and then return a non-nil value. If the
  15626. context is wrong, just do nothing and return nil.")
  15627. (defvar org-tab-first-hook nil
  15628. "Hook for functions to attach themselves to TAB.
  15629. See `org-ctrl-c-ctrl-c-hook' for more information.
  15630. This hook runs as the first action when TAB is pressed, even before
  15631. `org-cycle' messes around with the `outline-regexp' to cater for
  15632. inline tasks and plain list item folding.
  15633. If any function in this hook returns t, any other actions that
  15634. would have been caused by TAB (such as table field motion or visibility
  15635. cycling) will not occur.")
  15636. (defvar org-tab-after-check-for-table-hook nil
  15637. "Hook for functions to attach themselves to TAB.
  15638. See `org-ctrl-c-ctrl-c-hook' for more information.
  15639. This hook runs after it has been established that the cursor is not in a
  15640. table, but before checking if the cursor is in a headline or if global cycling
  15641. should be done.
  15642. If any function in this hook returns t, not other actions like visibility
  15643. cycling will be done.")
  15644. (defvar org-tab-after-check-for-cycling-hook nil
  15645. "Hook for functions to attach themselves to TAB.
  15646. See `org-ctrl-c-ctrl-c-hook' for more information.
  15647. This hook runs after it has been established that not table field motion and
  15648. not visibility should be done because of current context. This is probably
  15649. the place where a package like yasnippets can hook in.")
  15650. (defvar org-tab-before-tab-emulation-hook nil
  15651. "Hook for functions to attach themselves to TAB.
  15652. See `org-ctrl-c-ctrl-c-hook' for more information.
  15653. This hook runs after every other options for TAB have been exhausted, but
  15654. before indentation and \t insertion takes place.")
  15655. (defvar org-metaleft-hook nil
  15656. "Hook for functions attaching themselves to `M-left'.
  15657. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15658. (defvar org-metaright-hook nil
  15659. "Hook for functions attaching themselves to `M-right'.
  15660. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15661. (defvar org-metaup-hook nil
  15662. "Hook for functions attaching themselves to `M-up'.
  15663. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15664. (defvar org-metadown-hook nil
  15665. "Hook for functions attaching themselves to `M-down'.
  15666. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15667. (defvar org-shiftmetaleft-hook nil
  15668. "Hook for functions attaching themselves to `M-S-left'.
  15669. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15670. (defvar org-shiftmetaright-hook nil
  15671. "Hook for functions attaching themselves to `M-S-right'.
  15672. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15673. (defvar org-shiftmetaup-hook nil
  15674. "Hook for functions attaching themselves to `M-S-up'.
  15675. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15676. (defvar org-shiftmetadown-hook nil
  15677. "Hook for functions attaching themselves to `M-S-down'.
  15678. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15679. (defvar org-metareturn-hook nil
  15680. "Hook for functions attaching themselves to `M-RET'.
  15681. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15682. (defvar org-shiftup-hook nil
  15683. "Hook for functions attaching themselves to `S-up'.
  15684. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15685. (defvar org-shiftup-final-hook nil
  15686. "Hook for functions attaching themselves to `S-up'.
  15687. This one runs after all other options except shift-select have been excluded.
  15688. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15689. (defvar org-shiftdown-hook nil
  15690. "Hook for functions attaching themselves to `S-down'.
  15691. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15692. (defvar org-shiftdown-final-hook nil
  15693. "Hook for functions attaching themselves to `S-down'.
  15694. This one runs after all other options except shift-select have been excluded.
  15695. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15696. (defvar org-shiftleft-hook nil
  15697. "Hook for functions attaching themselves to `S-left'.
  15698. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15699. (defvar org-shiftleft-final-hook nil
  15700. "Hook for functions attaching themselves to `S-left'.
  15701. This one runs after all other options except shift-select have been excluded.
  15702. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15703. (defvar org-shiftright-hook nil
  15704. "Hook for functions attaching themselves to `S-right'.
  15705. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15706. (defvar org-shiftright-final-hook nil
  15707. "Hook for functions attaching themselves to `S-right'.
  15708. This one runs after all other options except shift-select have been excluded.
  15709. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15710. (defun org-modifier-cursor-error ()
  15711. "Throw an error, a modified cursor command was applied in wrong context."
  15712. (user-error "This command is active in special context like tables, headlines or items"))
  15713. (defun org-shiftselect-error ()
  15714. "Throw an error because Shift-Cursor command was applied in wrong context."
  15715. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15716. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15717. (user-error "This command works only in special context like headlines or timestamps")))
  15718. (defun org-call-for-shift-select (cmd)
  15719. (let ((this-command-keys-shift-translated t))
  15720. (call-interactively cmd)))
  15721. (defun org-shifttab (&optional arg)
  15722. "Global visibility cycling or move to previous table field.
  15723. Call `org-table-previous-field' within a table.
  15724. When ARG is nil, cycle globally through visibility states.
  15725. When ARG is a numeric prefix, show contents of this level."
  15726. (interactive "P")
  15727. (cond
  15728. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15729. ((integerp arg)
  15730. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15731. (message "Content view to level: %d" arg)
  15732. (org-content (prefix-numeric-value arg2))
  15733. (org-cycle-show-empty-lines t)
  15734. (setq org-cycle-global-status 'overview)))
  15735. (t (call-interactively 'org-global-cycle))))
  15736. (defun org-shiftmetaleft ()
  15737. "Promote subtree or delete table column.
  15738. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15739. `org-table-delete-column', depending on context. See the
  15740. individual commands for more information."
  15741. (interactive)
  15742. (cond
  15743. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15744. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15745. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15746. ((if (not (org-region-active-p)) (org-at-item-p)
  15747. (save-excursion (goto-char (region-beginning))
  15748. (org-at-item-p)))
  15749. (call-interactively 'org-outdent-item-tree))
  15750. (t (org-modifier-cursor-error))))
  15751. (defun org-shiftmetaright ()
  15752. "Demote subtree or insert table column.
  15753. Calls `org-demote-subtree', `org-indent-item-tree', or
  15754. `org-table-insert-column', depending on context. See the
  15755. individual commands for more information."
  15756. (interactive)
  15757. (cond
  15758. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15759. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15760. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15761. ((if (not (org-region-active-p)) (org-at-item-p)
  15762. (save-excursion (goto-char (region-beginning))
  15763. (org-at-item-p)))
  15764. (call-interactively 'org-indent-item-tree))
  15765. (t (org-modifier-cursor-error))))
  15766. (defun org-shiftmetaup (&optional _arg)
  15767. "Drag the line at point up.
  15768. In a table, kill the current row.
  15769. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15770. but also adjust the previous clocked item in the clock history.
  15771. Everywhere else, drag the line at point up."
  15772. (interactive "P")
  15773. (cond
  15774. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15775. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15776. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15777. (call-interactively 'org-timestamp-up)))
  15778. (t (call-interactively 'org-drag-line-backward))))
  15779. (defun org-shiftmetadown (&optional _arg)
  15780. "Drag the line at point down.
  15781. In a table, insert an empty row at the current line.
  15782. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15783. but also adjust the previous clocked item in the clock history.
  15784. Everywhere else, drag the line at point down."
  15785. (interactive "P")
  15786. (cond
  15787. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15788. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15789. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15790. (call-interactively 'org-timestamp-down)))
  15791. (t (call-interactively 'org-drag-line-forward))))
  15792. (defsubst org-hidden-tree-error ()
  15793. (user-error
  15794. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15795. (defun org-metaleft (&optional _arg)
  15796. "Promote heading, list item at point or move table column left.
  15797. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15798. depending on context. With no specific context, calls the Emacs
  15799. default `backward-word'. See the individual commands for more
  15800. information.
  15801. This function runs the hook `org-metaleft-hook' as a first step,
  15802. and returns at first non-nil value."
  15803. (interactive "P")
  15804. (cond
  15805. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15806. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15807. ((org-with-limited-levels
  15808. (or (org-at-heading-p)
  15809. (and (org-region-active-p)
  15810. (save-excursion
  15811. (goto-char (region-beginning))
  15812. (org-at-heading-p)))))
  15813. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15814. (call-interactively 'org-do-promote))
  15815. ;; At an inline task.
  15816. ((org-at-heading-p)
  15817. (call-interactively 'org-inlinetask-promote))
  15818. ((or (org-at-item-p)
  15819. (and (org-region-active-p)
  15820. (save-excursion
  15821. (goto-char (region-beginning))
  15822. (org-at-item-p))))
  15823. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15824. (call-interactively 'org-outdent-item))
  15825. (t (call-interactively 'backward-word))))
  15826. (defun org-metaright (&optional _arg)
  15827. "Demote heading, list item at point or move table column right.
  15828. In front of a drawer or a block keyword, indent it correctly.
  15829. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15830. `org-indent-drawer' or `org-indent-block' depending on context.
  15831. With no specific context, calls the Emacs default `forward-word'.
  15832. See the individual commands for more information.
  15833. This function runs the hook `org-metaright-hook' as a first step,
  15834. and returns at first non-nil value."
  15835. (interactive "P")
  15836. (cond
  15837. ((run-hook-with-args-until-success 'org-metaright-hook))
  15838. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15839. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15840. ((org-at-block-p) (call-interactively 'org-indent-block))
  15841. ((org-with-limited-levels
  15842. (or (org-at-heading-p)
  15843. (and (org-region-active-p)
  15844. (save-excursion
  15845. (goto-char (region-beginning))
  15846. (org-at-heading-p)))))
  15847. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15848. (call-interactively 'org-do-demote))
  15849. ;; At an inline task.
  15850. ((org-at-heading-p)
  15851. (call-interactively 'org-inlinetask-demote))
  15852. ((or (org-at-item-p)
  15853. (and (org-region-active-p)
  15854. (save-excursion
  15855. (goto-char (region-beginning))
  15856. (org-at-item-p))))
  15857. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15858. (call-interactively 'org-indent-item))
  15859. (t (call-interactively 'forward-word))))
  15860. (defun org-check-for-hidden (what)
  15861. "Check if there are hidden headlines/items in the current visual line.
  15862. WHAT can be either `headlines' or `items'. If the current line is
  15863. an outline or item heading and it has a folded subtree below it,
  15864. this function returns t, nil otherwise."
  15865. (let ((re (cond
  15866. ((eq what 'headlines) org-outline-regexp-bol)
  15867. ((eq what 'items) (org-item-beginning-re))
  15868. (t (error "This should not happen"))))
  15869. beg end)
  15870. (save-excursion
  15871. (catch 'exit
  15872. (unless (org-region-active-p)
  15873. (setq beg (point-at-bol))
  15874. (beginning-of-line 2)
  15875. (while (and (not (eobp)) ;; this is like `next-line'
  15876. (get-char-property (1- (point)) 'invisible))
  15877. (beginning-of-line 2))
  15878. (setq end (point))
  15879. (goto-char beg)
  15880. (goto-char (point-at-eol))
  15881. (setq end (max end (point)))
  15882. (while (re-search-forward re end t)
  15883. (when (get-char-property (match-beginning 0) 'invisible)
  15884. (throw 'exit t))))
  15885. nil))))
  15886. (defun org-metaup (&optional _arg)
  15887. "Move subtree up or move table row up.
  15888. Calls `org-move-subtree-up' or `org-table-move-row' or
  15889. `org-move-item-up', depending on context. See the individual commands
  15890. for more information."
  15891. (interactive "P")
  15892. (cond
  15893. ((run-hook-with-args-until-success 'org-metaup-hook))
  15894. ((org-region-active-p)
  15895. (let* ((a (save-excursion
  15896. (goto-char (min (region-beginning) (region-end)))
  15897. (line-beginning-position)))
  15898. (b (save-excursion
  15899. (goto-char (max (region-beginning) (region-end)))
  15900. (if (bolp) (1- (point)) (line-end-position))))
  15901. (c (save-excursion
  15902. (goto-char a)
  15903. (move-beginning-of-line 0)
  15904. (point)))
  15905. (d (save-excursion
  15906. (goto-char a)
  15907. (move-end-of-line 0)
  15908. (point))))
  15909. (transpose-regions a b c d)
  15910. (goto-char c)))
  15911. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15912. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15913. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15914. (t (org-drag-element-backward))))
  15915. (defun org-metadown (&optional _arg)
  15916. "Move subtree down or move table row down.
  15917. Calls `org-move-subtree-down' or `org-table-move-row' or
  15918. `org-move-item-down', depending on context. See the individual
  15919. commands for more information."
  15920. (interactive "P")
  15921. (cond
  15922. ((run-hook-with-args-until-success 'org-metadown-hook))
  15923. ((org-region-active-p)
  15924. (let* ((a (save-excursion
  15925. (goto-char (min (region-beginning) (region-end)))
  15926. (line-beginning-position)))
  15927. (b (save-excursion
  15928. (goto-char (max (region-beginning) (region-end)))
  15929. (if (bolp) (1- (point)) (line-end-position))))
  15930. (c (save-excursion
  15931. (goto-char b)
  15932. (move-beginning-of-line (if (bolp) 1 2))
  15933. (point)))
  15934. (d (save-excursion
  15935. (goto-char b)
  15936. (move-end-of-line (if (bolp) 1 2))
  15937. (point))))
  15938. (transpose-regions a b c d)
  15939. (goto-char d)))
  15940. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15941. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15942. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15943. (t (org-drag-element-forward))))
  15944. (defun org-shiftup (&optional arg)
  15945. "Act on current element according to context.
  15946. Call `org-timestamp-up' or `org-priority-up', or
  15947. `org-previous-item', or `org-table-move-cell-up'. See the
  15948. individual commands for more information."
  15949. (interactive "P")
  15950. (cond
  15951. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15952. ((and org-support-shift-select (org-region-active-p))
  15953. (org-call-for-shift-select 'previous-line))
  15954. ((org-at-timestamp-p 'lax)
  15955. (call-interactively (if org-edit-timestamp-down-means-later
  15956. 'org-timestamp-down 'org-timestamp-up)))
  15957. ((and (not (eq org-support-shift-select 'always))
  15958. org-priority-enable-commands
  15959. (org-at-heading-p))
  15960. (call-interactively 'org-priority-up))
  15961. ((and (not org-support-shift-select) (org-at-item-p))
  15962. (call-interactively 'org-previous-item))
  15963. ((org-clocktable-try-shift 'up arg))
  15964. ((org-at-table-p) (org-table-move-cell-up))
  15965. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15966. (org-support-shift-select
  15967. (org-call-for-shift-select 'previous-line))
  15968. (t (org-shiftselect-error))))
  15969. (defun org-shiftdown (&optional arg)
  15970. "Act on current element according to context.
  15971. Call `org-timestamp-down' or `org-priority-down', or
  15972. `org-next-item', or `org-table-move-cell-down'. See the
  15973. individual commands for more information."
  15974. (interactive "P")
  15975. (cond
  15976. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15977. ((and org-support-shift-select (org-region-active-p))
  15978. (org-call-for-shift-select 'next-line))
  15979. ((org-at-timestamp-p 'lax)
  15980. (call-interactively (if org-edit-timestamp-down-means-later
  15981. 'org-timestamp-up 'org-timestamp-down)))
  15982. ((and (not (eq org-support-shift-select 'always))
  15983. org-priority-enable-commands
  15984. (org-at-heading-p))
  15985. (call-interactively 'org-priority-down))
  15986. ((and (not org-support-shift-select) (org-at-item-p))
  15987. (call-interactively 'org-next-item))
  15988. ((org-clocktable-try-shift 'down arg))
  15989. ((org-at-table-p) (org-table-move-cell-down))
  15990. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15991. (org-support-shift-select
  15992. (org-call-for-shift-select 'next-line))
  15993. (t (org-shiftselect-error))))
  15994. (defun org-shiftright (&optional arg)
  15995. "Act on the current element according to context.
  15996. This does one of the following:
  15997. - switch a timestamp at point one day into the future
  15998. - on a headline, switch to the next TODO keyword
  15999. - on an item, switch entire list to the next bullet type
  16000. - on a property line, switch to the next allowed value
  16001. - on a clocktable definition line, move time block into the future
  16002. - in a table, move a single cell right"
  16003. (interactive "P")
  16004. (cond
  16005. ((run-hook-with-args-until-success 'org-shiftright-hook))
  16006. ((and org-support-shift-select (org-region-active-p))
  16007. (org-call-for-shift-select 'forward-char))
  16008. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  16009. ((and (not (eq org-support-shift-select 'always))
  16010. (org-at-heading-p))
  16011. (let ((org-inhibit-logging
  16012. (not org-treat-S-cursor-todo-selection-as-state-change))
  16013. (org-inhibit-blocking
  16014. (not org-treat-S-cursor-todo-selection-as-state-change)))
  16015. (org-call-with-arg 'org-todo 'right)))
  16016. ((or (and org-support-shift-select
  16017. (not (eq org-support-shift-select 'always))
  16018. (org-at-item-bullet-p))
  16019. (and (not org-support-shift-select) (org-at-item-p)))
  16020. (org-call-with-arg 'org-cycle-list-bullet nil))
  16021. ((and (not (eq org-support-shift-select 'always))
  16022. (org-at-property-p))
  16023. (call-interactively 'org-property-next-allowed-value))
  16024. ((org-clocktable-try-shift 'right arg))
  16025. ((org-at-table-p) (org-table-move-cell-right))
  16026. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  16027. (org-support-shift-select
  16028. (org-call-for-shift-select 'forward-char))
  16029. (t (org-shiftselect-error))))
  16030. (defun org-shiftleft (&optional arg)
  16031. "Act on current element according to context.
  16032. This does one of the following:
  16033. - switch a timestamp at point one day into the past
  16034. - on a headline, switch to the previous TODO keyword.
  16035. - on an item, switch entire list to the previous bullet type
  16036. - on a property line, switch to the previous allowed value
  16037. - on a clocktable definition line, move time block into the past
  16038. - in a table, move a single cell left"
  16039. (interactive "P")
  16040. (cond
  16041. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  16042. ((and org-support-shift-select (org-region-active-p))
  16043. (org-call-for-shift-select 'backward-char))
  16044. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  16045. ((and (not (eq org-support-shift-select 'always))
  16046. (org-at-heading-p))
  16047. (let ((org-inhibit-logging
  16048. (not org-treat-S-cursor-todo-selection-as-state-change))
  16049. (org-inhibit-blocking
  16050. (not org-treat-S-cursor-todo-selection-as-state-change)))
  16051. (org-call-with-arg 'org-todo 'left)))
  16052. ((or (and org-support-shift-select
  16053. (not (eq org-support-shift-select 'always))
  16054. (org-at-item-bullet-p))
  16055. (and (not org-support-shift-select) (org-at-item-p)))
  16056. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  16057. ((and (not (eq org-support-shift-select 'always))
  16058. (org-at-property-p))
  16059. (call-interactively 'org-property-previous-allowed-value))
  16060. ((org-clocktable-try-shift 'left arg))
  16061. ((org-at-table-p) (org-table-move-cell-left))
  16062. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  16063. (org-support-shift-select
  16064. (org-call-for-shift-select 'backward-char))
  16065. (t (org-shiftselect-error))))
  16066. (defun org-shiftcontrolright ()
  16067. "Switch to next TODO set."
  16068. (interactive)
  16069. (cond
  16070. ((and org-support-shift-select (org-region-active-p))
  16071. (org-call-for-shift-select 'forward-word))
  16072. ((and (not (eq org-support-shift-select 'always))
  16073. (org-at-heading-p))
  16074. (org-call-with-arg 'org-todo 'nextset))
  16075. (org-support-shift-select
  16076. (org-call-for-shift-select 'forward-word))
  16077. (t (org-shiftselect-error))))
  16078. (defun org-shiftcontrolleft ()
  16079. "Switch to previous TODO set."
  16080. (interactive)
  16081. (cond
  16082. ((and org-support-shift-select (org-region-active-p))
  16083. (org-call-for-shift-select 'backward-word))
  16084. ((and (not (eq org-support-shift-select 'always))
  16085. (org-at-heading-p))
  16086. (org-call-with-arg 'org-todo 'previousset))
  16087. (org-support-shift-select
  16088. (org-call-for-shift-select 'backward-word))
  16089. (t (org-shiftselect-error))))
  16090. (defun org-shiftcontrolup (&optional n)
  16091. "Change timestamps synchronously up in CLOCK log lines.
  16092. Optional argument N tells to change by that many units."
  16093. (interactive "P")
  16094. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  16095. (let (org-support-shift-select)
  16096. (org-clock-timestamps-up n))
  16097. (user-error "Not at a clock log")))
  16098. (defun org-shiftcontroldown (&optional n)
  16099. "Change timestamps synchronously down in CLOCK log lines.
  16100. Optional argument N tells to change by that many units."
  16101. (interactive "P")
  16102. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  16103. (let (org-support-shift-select)
  16104. (org-clock-timestamps-down n))
  16105. (user-error "Not at a clock log")))
  16106. (defun org-increase-number-at-point (&optional inc)
  16107. "Increment the number at point.
  16108. With an optional prefix numeric argument INC, increment using
  16109. this numeric value."
  16110. (interactive "p")
  16111. (if (not (number-at-point))
  16112. (user-error "Not on a number")
  16113. (unless inc (setq inc 1))
  16114. (let ((pos (point))
  16115. (beg (skip-chars-backward "-+^/*0-9eE."))
  16116. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  16117. (setq nap (buffer-substring-no-properties
  16118. (+ pos beg) (+ pos beg end)))
  16119. (delete-region (+ pos beg) (+ pos beg end))
  16120. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  16121. (when (org-at-table-p)
  16122. (org-table-align)
  16123. (org-table-end-of-field 1))))
  16124. (defun org-decrease-number-at-point (&optional inc)
  16125. "Decrement the number at point.
  16126. With an optional prefix numeric argument INC, decrement using
  16127. this numeric value."
  16128. (interactive "p")
  16129. (org-increase-number-at-point (- (or inc 1))))
  16130. (defun org-ctrl-c-ret ()
  16131. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  16132. (interactive)
  16133. (cond
  16134. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  16135. (t (call-interactively 'org-insert-heading))))
  16136. (defun org-copy-visible (beg end)
  16137. "Copy the visible parts of the region."
  16138. (interactive "r")
  16139. (let ((result ""))
  16140. (while (/= beg end)
  16141. (when (get-char-property beg 'invisible)
  16142. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  16143. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  16144. (setq result (concat result (buffer-substring beg next)))
  16145. (setq beg next)))
  16146. (setq deactivate-mark t)
  16147. (kill-new result)
  16148. (message "Visible strings have been copied to the kill ring.")))
  16149. (defun org-copy-special ()
  16150. "Copy region in table or copy current subtree.
  16151. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  16152. context. See the individual commands for more information."
  16153. (interactive)
  16154. (call-interactively
  16155. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  16156. (defun org-cut-special ()
  16157. "Cut region in table or cut current subtree.
  16158. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  16159. context. See the individual commands for more information."
  16160. (interactive)
  16161. (call-interactively
  16162. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  16163. (defun org-paste-special (arg)
  16164. "Paste rectangular region into table, or past subtree relative to level.
  16165. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  16166. See the individual commands for more information."
  16167. (interactive "P")
  16168. (if (org-at-table-p)
  16169. (org-table-paste-rectangle)
  16170. (org-paste-subtree arg)))
  16171. (defun org-edit-special (&optional arg)
  16172. "Call a special editor for the element at point.
  16173. When at a table, call the formula editor with `org-table-edit-formulas'.
  16174. When in a source code block, call `org-edit-src-code'.
  16175. When in a fixed-width region, call `org-edit-fixed-width-region'.
  16176. When in an export block, call `org-edit-export-block'.
  16177. When in a LaTeX environment, call `org-edit-latex-environment'.
  16178. When at an #+INCLUDE keyword, visit the included file.
  16179. When at a footnote reference, call `org-edit-footnote-reference'.
  16180. When at a planning line call, `org-deadline' and/or `org-schedule'.
  16181. When at an active timestamp, call `org-time-stamp'.
  16182. When at an inactive timestamp, call `org-time-stamp-inactive'.
  16183. On a link, call `ffap' to visit the link at point.
  16184. Otherwise, return a user error."
  16185. (interactive "P")
  16186. (let ((element (org-element-at-point)))
  16187. (barf-if-buffer-read-only)
  16188. (pcase (org-element-type element)
  16189. (`src-block
  16190. (if (not arg) (org-edit-src-code)
  16191. (let* ((info (org-babel-get-src-block-info))
  16192. (lang (nth 0 info))
  16193. (params (nth 2 info))
  16194. (session (cdr (assq :session params))))
  16195. (if (not session) (org-edit-src-code)
  16196. ;; At a source block with a session and function called
  16197. ;; with an ARG: switch to the buffer related to the
  16198. ;; inferior process.
  16199. (switch-to-buffer
  16200. (funcall (intern (concat "org-babel-prep-session:" lang))
  16201. session params))))))
  16202. (`keyword
  16203. (unless (member (org-element-property :key element)
  16204. '("INCLUDE" "SETUPFILE"))
  16205. (user-error "No special environment to edit here"))
  16206. (let ((value (org-element-property :value element)))
  16207. (unless (org-string-nw-p value) (user-error "No file to edit"))
  16208. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  16209. (or (match-string 1 value)
  16210. (match-string 0 value)))))
  16211. (when (org-file-url-p file)
  16212. (user-error "Files located with a URL cannot be edited"))
  16213. (org-link-open-from-string
  16214. (format "[[%s]]" (expand-file-name file))))))
  16215. (`table
  16216. (if (eq (org-element-property :type element) 'table.el)
  16217. (org-edit-table.el)
  16218. (call-interactively 'org-table-edit-formulas)))
  16219. ;; Only Org tables contain `table-row' type elements.
  16220. (`table-row (call-interactively 'org-table-edit-formulas))
  16221. (`example-block (org-edit-src-code))
  16222. (`export-block (org-edit-export-block))
  16223. (`fixed-width (org-edit-fixed-width-region))
  16224. (`latex-environment (org-edit-latex-environment))
  16225. (`planning
  16226. (let ((proplist (cadr element)))
  16227. (mapc #'call-interactively
  16228. (remq nil
  16229. (list
  16230. (when (plist-get proplist :deadline) #'org-deadline)
  16231. (when (plist-get proplist :scheduled) #'org-schedule))))))
  16232. (_
  16233. ;; No notable element at point. Though, we may be at a link or
  16234. ;; a footnote reference, which are objects. Thus, scan deeper.
  16235. (let ((context (org-element-context element)))
  16236. (pcase (org-element-type context)
  16237. (`footnote-reference (org-edit-footnote-reference))
  16238. (`inline-src-block (org-edit-inline-src-code))
  16239. (`timestamp (if (eq 'inactive (org-element-property :type context))
  16240. (call-interactively #'org-time-stamp-inactive)
  16241. (call-interactively #'org-time-stamp)))
  16242. (`link (call-interactively #'ffap))
  16243. (_ (user-error "No special environment to edit here"))))))))
  16244. (defun org-ctrl-c-ctrl-c (&optional arg)
  16245. "Set tags in headline, or update according to changed information at point.
  16246. This command does many different things, depending on context:
  16247. - If column view is active, in agenda or org buffers, quit it.
  16248. - If there are highlights, remove them.
  16249. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  16250. this is what we do.
  16251. - If the cursor is on a statistics cookie, update it.
  16252. - If the cursor is in a headline, in an agenda or an org buffer,
  16253. prompt for tags and insert them into the current line, aligned
  16254. to `org-tags-column'. When called with prefix arg, realign all
  16255. tags in the current buffer.
  16256. - If the cursor is in one of the special #+KEYWORD lines, this
  16257. triggers scanning the buffer for these lines and updating the
  16258. information.
  16259. - If the cursor is inside a table, realign the table. This command
  16260. works even if the automatic table editor has been turned off.
  16261. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  16262. the entire table.
  16263. - If the cursor is at a footnote reference or definition, jump to
  16264. the corresponding definition or references, respectively.
  16265. - If the cursor is a the beginning of a dynamic block, update it.
  16266. - If the current buffer is a capture buffer, close note and file it.
  16267. - If the cursor is on a <<<target>>>, update radio targets and
  16268. corresponding links in this buffer.
  16269. - If the cursor is on a numbered item in a plain list, renumber the
  16270. ordered list.
  16271. - If the cursor is on a checkbox, toggle it.
  16272. - If the cursor is on a code block, evaluate it. The variable
  16273. `org-confirm-babel-evaluate' can be used to control prompting
  16274. before code block evaluation, by default every code block
  16275. evaluation requires confirmation. Code block evaluation can be
  16276. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  16277. (interactive "P")
  16278. (cond
  16279. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  16280. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  16281. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  16282. (org-remove-occur-highlights)
  16283. (message "Temporary highlights/overlays removed from current buffer"))
  16284. ((and (local-variable-p 'org-finish-function)
  16285. (fboundp org-finish-function))
  16286. (funcall org-finish-function))
  16287. ((org-babel-hash-at-point))
  16288. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  16289. (t
  16290. (let* ((context
  16291. (org-element-lineage
  16292. (org-element-context)
  16293. ;; Limit to supported contexts.
  16294. '(babel-call clock dynamic-block footnote-definition
  16295. footnote-reference inline-babel-call inline-src-block
  16296. inlinetask item keyword node-property paragraph
  16297. plain-list planning property-drawer radio-target
  16298. src-block statistics-cookie table table-cell table-row
  16299. timestamp)
  16300. t))
  16301. (type (org-element-type context)))
  16302. ;; For convenience: at the first line of a paragraph on the same
  16303. ;; line as an item, apply function on that item instead.
  16304. (when (eq type 'paragraph)
  16305. (let ((parent (org-element-property :parent context)))
  16306. (when (and (eq (org-element-type parent) 'item)
  16307. (= (line-beginning-position)
  16308. (org-element-property :begin parent)))
  16309. (setq context parent)
  16310. (setq type 'item))))
  16311. ;; Act according to type of element or object at point.
  16312. ;;
  16313. ;; Do nothing on a blank line, except if it is contained in
  16314. ;; a source block. Hence, we first check if point is in such
  16315. ;; a block and then if it is at a blank line.
  16316. (pcase type
  16317. ((or `inline-src-block `src-block)
  16318. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  16319. (org-babel-eval-wipe-error-buffer)
  16320. (org-babel-execute-src-block
  16321. current-prefix-arg (org-babel-get-src-block-info nil context))))
  16322. ((guard (org-match-line "[ \t]*$"))
  16323. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  16324. (user-error
  16325. (substitute-command-keys
  16326. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  16327. ((or `babel-call `inline-babel-call)
  16328. (let ((info (org-babel-lob-get-info context)))
  16329. (when info (org-babel-execute-src-block nil info))))
  16330. (`clock (org-clock-update-time-maybe))
  16331. (`dynamic-block
  16332. (save-excursion
  16333. (goto-char (org-element-property :post-affiliated context))
  16334. (org-update-dblock)))
  16335. (`footnote-definition
  16336. (goto-char (org-element-property :post-affiliated context))
  16337. (call-interactively 'org-footnote-action))
  16338. (`footnote-reference (call-interactively #'org-footnote-action))
  16339. ((or `headline `inlinetask)
  16340. (save-excursion (goto-char (org-element-property :begin context))
  16341. (call-interactively #'org-set-tags-command)))
  16342. (`item
  16343. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  16344. ;; unconditionally, whereas `C-u' will toggle its presence.
  16345. ;; Without a universal argument, if the item has a checkbox,
  16346. ;; toggle it. Otherwise repair the list.
  16347. (let* ((box (org-element-property :checkbox context))
  16348. (struct (org-element-property :structure context))
  16349. (old-struct (copy-tree struct))
  16350. (parents (org-list-parents-alist struct))
  16351. (prevs (org-list-prevs-alist struct))
  16352. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  16353. (org-list-set-checkbox
  16354. (org-element-property :begin context) struct
  16355. (cond ((equal arg '(16)) "[-]")
  16356. ((and (not box) (equal arg '(4))) "[ ]")
  16357. ((or (not box) (equal arg '(4))) nil)
  16358. ((eq box 'on) "[ ]")
  16359. (t "[X]")))
  16360. ;; Mimic `org-list-write-struct' but with grabbing a return
  16361. ;; value from `org-list-struct-fix-box'.
  16362. (org-list-struct-fix-ind struct parents 2)
  16363. (org-list-struct-fix-item-end struct)
  16364. (org-list-struct-fix-bul struct prevs)
  16365. (org-list-struct-fix-ind struct parents)
  16366. (let ((block-item
  16367. (org-list-struct-fix-box struct parents prevs orderedp)))
  16368. (if (and box (equal struct old-struct))
  16369. (if (equal arg '(16))
  16370. (message "Checkboxes already reset")
  16371. (user-error "Cannot toggle this checkbox: %s"
  16372. (if (eq box 'on)
  16373. "all subitems checked"
  16374. "unchecked subitems")))
  16375. (org-list-struct-apply-struct struct old-struct)
  16376. (org-update-checkbox-count-maybe))
  16377. (when block-item
  16378. (message "Checkboxes were removed due to empty box at line %d"
  16379. (org-current-line block-item))))))
  16380. (`keyword
  16381. (let ((org-inhibit-startup-visibility-stuff t)
  16382. (org-startup-align-all-tables nil))
  16383. (when (boundp 'org-table-coordinate-overlays)
  16384. (mapc #'delete-overlay org-table-coordinate-overlays)
  16385. (setq org-table-coordinate-overlays nil))
  16386. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  16387. (message "Local setup has been refreshed"))
  16388. (`plain-list
  16389. ;; At a plain list, with a double C-u argument, set
  16390. ;; checkboxes of each item to "[-]", whereas a single one
  16391. ;; will toggle their presence according to the state of the
  16392. ;; first item in the list. Without an argument, repair the
  16393. ;; list.
  16394. (let* ((begin (org-element-property :contents-begin context))
  16395. (struct (org-element-property :structure context))
  16396. (old-struct (copy-tree struct))
  16397. (first-box (save-excursion
  16398. (goto-char begin)
  16399. (looking-at org-list-full-item-re)
  16400. (match-string-no-properties 3)))
  16401. (new-box (cond ((equal arg '(16)) "[-]")
  16402. ((equal arg '(4)) (unless first-box "[ ]"))
  16403. ((equal first-box "[X]") "[ ]")
  16404. (t "[X]"))))
  16405. (cond
  16406. (arg
  16407. (dolist (pos
  16408. (org-list-get-all-items
  16409. begin struct (org-list-prevs-alist struct)))
  16410. (org-list-set-checkbox pos struct new-box)))
  16411. ((and first-box (eq (point) begin))
  16412. ;; For convenience, when point is at bol on the first
  16413. ;; item of the list and no argument is provided, simply
  16414. ;; toggle checkbox of that item, if any.
  16415. (org-list-set-checkbox begin struct new-box)))
  16416. (when (equal
  16417. (org-list-write-struct
  16418. struct (org-list-parents-alist struct) old-struct)
  16419. old-struct)
  16420. (message "Cannot update this checkbox"))
  16421. (org-update-checkbox-count-maybe)))
  16422. ((or `property-drawer `node-property)
  16423. (call-interactively #'org-property-action))
  16424. (`radio-target
  16425. (call-interactively #'org-update-radio-target-regexp))
  16426. (`statistics-cookie
  16427. (call-interactively #'org-update-statistics-cookies))
  16428. ((or `table `table-cell `table-row)
  16429. ;; At a table, recalculate every field and align it. Also
  16430. ;; send the table if necessary. If the table has
  16431. ;; a `table.el' type, just give up. At a table row or cell,
  16432. ;; maybe recalculate line but always align table.
  16433. (if (eq (org-element-property :type context) 'table.el)
  16434. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16435. Use `\\[org-edit-special]' to edit table.el tables"))
  16436. (if (or (eq type 'table)
  16437. ;; Check if point is at a TBLFM line.
  16438. (and (eq type 'table-row)
  16439. (= (point) (org-element-property :end context))))
  16440. (save-excursion
  16441. (if (org-at-TBLFM-p)
  16442. (progn (require 'org-table)
  16443. (org-table-calc-current-TBLFM))
  16444. (goto-char (org-element-property :contents-begin context))
  16445. (org-call-with-arg 'org-table-recalculate (or arg t))
  16446. (orgtbl-send-table 'maybe)))
  16447. (org-table-maybe-eval-formula)
  16448. (cond (arg (call-interactively #'org-table-recalculate))
  16449. ((org-table-maybe-recalculate-line))
  16450. (t (org-table-align))))))
  16451. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16452. (org-timestamp-change 0 'day))
  16453. ((and `nil (guard (org-at-heading-p)))
  16454. ;; When point is on an unsupported object type, we can miss
  16455. ;; the fact that it also is at a heading. Handle it here.
  16456. (call-interactively #'org-set-tags-command))
  16457. ((guard
  16458. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16459. (_
  16460. (user-error
  16461. (substitute-command-keys
  16462. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16463. (defun org-mode-restart ()
  16464. (interactive)
  16465. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16466. (funcall major-mode)
  16467. (hack-local-variables)
  16468. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16469. (org-indent-mode -1))
  16470. (org-reset-file-cache))
  16471. (message "%s restarted" major-mode))
  16472. (defun org-flag-above-first-heading (&optional arg)
  16473. "Hide from bob up to the first heading.
  16474. Move point to the beginning of first heading or end of buffer."
  16475. (goto-char (point-min))
  16476. (unless (org-at-heading-p)
  16477. (outline-next-heading))
  16478. (unless (bobp)
  16479. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16480. (defun org-show-branches-buffer ()
  16481. "Show all branches in the buffer."
  16482. (org-flag-above-first-heading)
  16483. (outline-hide-sublevels 1)
  16484. (unless (eobp)
  16485. (outline-show-branches)
  16486. (while (outline-get-next-sibling)
  16487. (outline-show-branches)))
  16488. (goto-char (point-min)))
  16489. (defun org-kill-note-or-show-branches ()
  16490. "Abort storing current note, or show just branches."
  16491. (interactive)
  16492. (cond (org-finish-function
  16493. (let ((org-note-abort t)) (funcall org-finish-function)))
  16494. ((org-before-first-heading-p)
  16495. (org-show-branches-buffer)
  16496. (org-hide-archived-subtrees (point-min) (point-max)))
  16497. (t
  16498. (let ((beg (progn (org-back-to-heading) (point)))
  16499. (end (save-excursion (org-end-of-subtree t t) (point))))
  16500. (outline-hide-subtree)
  16501. (outline-show-branches)
  16502. (org-hide-archived-subtrees beg end)))))
  16503. (defun org-delete-indentation (&optional arg)
  16504. "Join current line to previous and fix whitespace at join.
  16505. If previous line is a headline add to headline title. Otherwise
  16506. the function calls `delete-indentation'.
  16507. With a non-nil optional argument, join it to the following one."
  16508. (interactive "*P")
  16509. (if (save-excursion
  16510. (beginning-of-line (if arg 1 0))
  16511. (let ((case-fold-search nil))
  16512. (looking-at org-complex-heading-regexp)))
  16513. ;; At headline.
  16514. (let ((tags-column (when (match-beginning 5)
  16515. (save-excursion (goto-char (match-beginning 5))
  16516. (current-column))))
  16517. (string (concat " " (progn (when arg (forward-line 1))
  16518. (org-trim (delete-and-extract-region
  16519. (line-beginning-position)
  16520. (line-end-position)))))))
  16521. (unless (bobp) (delete-region (point) (1- (point))))
  16522. (goto-char (or (match-end 4)
  16523. (match-beginning 5)
  16524. (match-end 0)))
  16525. (skip-chars-backward " \t")
  16526. (save-excursion (insert string))
  16527. ;; Adjust alignment of tags.
  16528. (cond
  16529. ((not tags-column)) ;no tags
  16530. (org-auto-align-tags (org-align-tags))
  16531. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16532. (delete-indentation arg)))
  16533. (defun org-open-line (n)
  16534. "Insert a new row in tables, call `open-line' elsewhere.
  16535. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16536. As a special case, when a document starts with a table, allow to
  16537. call `open-line' on the very first character."
  16538. (interactive "*p")
  16539. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16540. (org-table-insert-row)
  16541. (open-line n)))
  16542. (defun org-return (&optional indent)
  16543. "Goto next table row or insert a newline.
  16544. Calls `org-table-next-row' or `newline', depending on context.
  16545. When optional INDENT argument is non-nil, call
  16546. `newline-and-indent' instead of `newline'.
  16547. When `org-return-follows-link' is non-nil and point is on
  16548. a timestamp or a link, call `org-open-at-point'. However, it
  16549. will not happen if point is in a table or on a \"dead\"
  16550. object (e.g., within a comment). In these case, you need to use
  16551. `org-open-at-point' directly."
  16552. (interactive)
  16553. (let ((context (if org-return-follows-link (org-element-context)
  16554. (org-element-at-point))))
  16555. (cond
  16556. ;; In a table, call `org-table-next-row'. However, before first
  16557. ;; column or after last one, split the table.
  16558. ((or (and (eq 'table (org-element-type context))
  16559. (not (eq 'table.el (org-element-property :type context)))
  16560. (>= (point) (org-element-property :contents-begin context))
  16561. (< (point) (org-element-property :contents-end context)))
  16562. (org-element-lineage context '(table-row table-cell) t))
  16563. (if (or (looking-at-p "[ \t]*$")
  16564. (save-excursion (skip-chars-backward " \t") (bolp)))
  16565. (insert "\n")
  16566. (org-table-justify-field-maybe)
  16567. (call-interactively #'org-table-next-row)))
  16568. ;; On a link or a timestamp, call `org-open-at-point' if
  16569. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16570. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16571. ((and org-return-follows-link
  16572. (or (and (eq 'link (org-element-type context))
  16573. ;; Ensure point is not on the white spaces after
  16574. ;; the link.
  16575. (let ((origin (point)))
  16576. (org-with-point-at (org-element-property :end context)
  16577. (skip-chars-backward " \t")
  16578. (> (point) origin))))
  16579. (org-in-regexp org-ts-regexp-both nil t)
  16580. (org-in-regexp org-tsr-regexp-both nil t)
  16581. (org-in-regexp org-link-any-re nil t)))
  16582. (call-interactively #'org-open-at-point))
  16583. ;; Insert newline in heading, but preserve tags.
  16584. ((and (not (bolp))
  16585. (let ((case-fold-search nil))
  16586. (org-match-line org-complex-heading-regexp)))
  16587. ;; At headline. Split line. However, if point is on keyword,
  16588. ;; priority cookie or tags, do not break any of them: add
  16589. ;; a newline after the headline instead.
  16590. (let ((tags-column (and (match-beginning 5)
  16591. (save-excursion (goto-char (match-beginning 5))
  16592. (current-column))))
  16593. (string
  16594. (when (and (match-end 4) (org-point-in-group (point) 4))
  16595. (delete-and-extract-region (point) (match-end 4)))))
  16596. ;; Adjust tag alignment.
  16597. (cond
  16598. ((not (and tags-column string)))
  16599. (org-auto-align-tags (org-align-tags))
  16600. (t (org--align-tags-here tags-column))) ;preserve tags column
  16601. (end-of-line)
  16602. (org-show-entry)
  16603. (if indent (newline-and-indent) (newline))
  16604. (when string (save-excursion (insert (org-trim string))))))
  16605. ;; In a list, make sure indenting keeps trailing text within.
  16606. ((and indent
  16607. (not (eolp))
  16608. (org-element-lineage context '(item)))
  16609. (let ((trailing-data
  16610. (delete-and-extract-region (point) (line-end-position))))
  16611. (newline-and-indent)
  16612. (save-excursion (insert trailing-data))))
  16613. (t
  16614. ;; Do not auto-fill when point is in an Org property drawer.
  16615. (let ((auto-fill-function (and (not (org-at-property-p))
  16616. auto-fill-function)))
  16617. (if indent
  16618. (newline-and-indent)
  16619. (newline)))))))
  16620. (defun org-return-indent ()
  16621. "Goto next table row or insert a newline and indent.
  16622. Calls `org-table-next-row' or `newline-and-indent', depending on
  16623. context. See the individual commands for more information."
  16624. (interactive)
  16625. (org-return t))
  16626. (defun org-ctrl-c-tab (&optional arg)
  16627. "Toggle columns width in a table, or show children.
  16628. Call `org-table-toggle-column-width' if point is in a table.
  16629. Otherwise, call `org-show-children'. ARG is the level to hide."
  16630. (interactive "p")
  16631. (if (org-at-table-p)
  16632. (call-interactively #'org-table-toggle-column-width)
  16633. (if (org-before-first-heading-p)
  16634. (progn
  16635. (org-flag-above-first-heading)
  16636. (outline-hide-sublevels (or arg 1))
  16637. (goto-char (point-min)))
  16638. (outline-hide-subtree)
  16639. (org-show-children arg))))
  16640. (defun org-ctrl-c-star ()
  16641. "Compute table, or change heading status of lines.
  16642. Calls `org-table-recalculate' or `org-toggle-heading',
  16643. depending on context."
  16644. (interactive)
  16645. (cond
  16646. ((org-at-table-p)
  16647. (call-interactively 'org-table-recalculate))
  16648. (t
  16649. ;; Convert all lines in region to list items
  16650. (call-interactively 'org-toggle-heading))))
  16651. (defun org-ctrl-c-minus ()
  16652. "Insert separator line in table or modify bullet status of line.
  16653. Also turns a plain line or a region of lines into list items.
  16654. Calls `org-table-insert-hline', `org-toggle-item', or
  16655. `org-cycle-list-bullet', depending on context."
  16656. (interactive)
  16657. (cond
  16658. ((org-at-table-p)
  16659. (call-interactively 'org-table-insert-hline))
  16660. ((org-region-active-p)
  16661. (call-interactively 'org-toggle-item))
  16662. ((org-in-item-p)
  16663. (call-interactively 'org-cycle-list-bullet))
  16664. (t
  16665. (call-interactively 'org-toggle-item))))
  16666. (defun org-toggle-heading (&optional nstars)
  16667. "Convert headings to normal text, or items or text to headings.
  16668. If there is no active region, only convert the current line.
  16669. With a `\\[universal-argument]' prefix, convert the whole list at
  16670. point into heading.
  16671. In a region:
  16672. - If the first non blank line is a headline, remove the stars
  16673. from all headlines in the region.
  16674. - If it is a normal line, turn each and every normal line (i.e.,
  16675. not an heading or an item) in the region into headings. If you
  16676. want to convert only the first line of this region, use one
  16677. universal prefix argument.
  16678. - If it is a plain list item, turn all plain list items into headings.
  16679. When converting a line into a heading, the number of stars is chosen
  16680. such that the lines become children of the current entry. However,
  16681. when a numeric prefix argument is given, its value determines the
  16682. number of stars to add."
  16683. (interactive "P")
  16684. (let ((skip-blanks
  16685. (function
  16686. ;; Return beginning of first non-blank line, starting from
  16687. ;; line at POS.
  16688. (lambda (pos)
  16689. (save-excursion
  16690. (goto-char pos)
  16691. (while (org-at-comment-p) (forward-line))
  16692. (skip-chars-forward " \r\t\n")
  16693. (point-at-bol)))))
  16694. beg end toggled)
  16695. ;; Determine boundaries of changes. If a universal prefix has
  16696. ;; been given, put the list in a region. If region ends at a bol,
  16697. ;; do not consider the last line to be in the region.
  16698. (when (and current-prefix-arg (org-at-item-p))
  16699. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16700. (org-mark-element))
  16701. (if (org-region-active-p)
  16702. (setq beg (funcall skip-blanks (region-beginning))
  16703. end (copy-marker (save-excursion
  16704. (goto-char (region-end))
  16705. (if (bolp) (point) (point-at-eol)))))
  16706. (setq beg (funcall skip-blanks (point-at-bol))
  16707. end (copy-marker (point-at-eol))))
  16708. ;; Ensure inline tasks don't count as headings.
  16709. (org-with-limited-levels
  16710. (save-excursion
  16711. (goto-char beg)
  16712. (cond
  16713. ;; Case 1. Started at an heading: de-star headings.
  16714. ((org-at-heading-p)
  16715. (while (< (point) end)
  16716. (when (org-at-heading-p t)
  16717. (looking-at org-outline-regexp) (replace-match "")
  16718. (setq toggled t))
  16719. (forward-line)))
  16720. ;; Case 2. Started at an item: change items into headlines.
  16721. ;; One star will be added by `org-list-to-subtree'.
  16722. ((org-at-item-p)
  16723. (while (< (point) end)
  16724. (when (org-at-item-p)
  16725. ;; Pay attention to cases when region ends before list.
  16726. (let* ((struct (org-list-struct))
  16727. (list-end
  16728. (min (org-list-get-bottom-point struct) (1+ end))))
  16729. (save-restriction
  16730. (narrow-to-region (point) list-end)
  16731. (insert (org-list-to-subtree
  16732. (org-list-to-lisp t)
  16733. (pcase (org-current-level)
  16734. (`nil 1)
  16735. (l (1+ (org-reduced-level l)))))
  16736. "\n")))
  16737. (setq toggled t))
  16738. (forward-line)))
  16739. ;; Case 3. Started at normal text: make every line an heading,
  16740. ;; skipping headlines and items.
  16741. (t (let* ((stars
  16742. (make-string
  16743. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16744. (add-stars
  16745. (cond (nstars "") ; stars from prefix only
  16746. ((equal stars "") "*") ; before first heading
  16747. (org-odd-levels-only "**") ; inside heading, odd
  16748. (t "*"))) ; inside heading, oddeven
  16749. (rpl (concat stars add-stars " "))
  16750. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16751. (while (< (point) (if (equal nstars '(4)) lend end))
  16752. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16753. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16754. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16755. (forward-line)))))))
  16756. (unless toggled (message "Cannot toggle heading from here"))))
  16757. (defun org-meta-return (&optional arg)
  16758. "Insert a new heading or wrap a region in a table.
  16759. Calls `org-insert-heading', `org-insert-item' or
  16760. `org-table-wrap-region', depending on context. When called with
  16761. an argument, unconditionally call `org-insert-heading'."
  16762. (interactive "P")
  16763. (org-check-before-invisible-edit 'insert)
  16764. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16765. (call-interactively (cond (arg #'org-insert-heading)
  16766. ((org-at-table-p) #'org-table-wrap-region)
  16767. ((org-in-item-p) #'org-insert-item)
  16768. (t #'org-insert-heading)))))
  16769. ;;; Menu entries
  16770. (defsubst org-in-subtree-not-table-p ()
  16771. "Are we in a subtree and not in a table?"
  16772. (and (not (org-before-first-heading-p))
  16773. (not (org-at-table-p))))
  16774. ;; Define the Org mode menus
  16775. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  16776. '("Tbl"
  16777. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16778. ["Next Field" org-cycle (org-at-table-p)]
  16779. ["Previous Field" org-shifttab (org-at-table-p)]
  16780. ["Next Row" org-return (org-at-table-p)]
  16781. "--"
  16782. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16783. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16784. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16785. "--"
  16786. ("Column"
  16787. ["Move Column Left" org-metaleft (org-at-table-p)]
  16788. ["Move Column Right" org-metaright (org-at-table-p)]
  16789. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16790. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16791. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16792. ("Row"
  16793. ["Move Row Up" org-metaup (org-at-table-p)]
  16794. ["Move Row Down" org-metadown (org-at-table-p)]
  16795. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16796. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16797. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16798. "--"
  16799. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16800. ("Rectangle"
  16801. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16802. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16803. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16804. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16805. "--"
  16806. ("Calculate"
  16807. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16808. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16809. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16810. "--"
  16811. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16812. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16813. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16814. "--"
  16815. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16816. "--"
  16817. ["Sum Column/Rectangle" org-table-sum
  16818. (or (org-at-table-p) (org-region-active-p))]
  16819. ["Which Column?" org-table-current-column (org-at-table-p)])
  16820. ["Debug Formulas"
  16821. org-table-toggle-formula-debugger
  16822. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16823. ["Show Col/Row Numbers"
  16824. org-table-toggle-coordinate-overlays
  16825. :style toggle
  16826. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16827. "--"
  16828. ["Create" org-table-create (not (org-at-table-p))]
  16829. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16830. ["Import from File" org-table-import (not (org-at-table-p))]
  16831. ["Export to File" org-table-export (org-at-table-p)]
  16832. "--"
  16833. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16834. "--"
  16835. ("Plot"
  16836. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16837. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16838. (easy-menu-define org-org-menu org-mode-map "Org menu"
  16839. '("Org"
  16840. ("Show/Hide"
  16841. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16842. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16843. ["Sparse Tree..." org-sparse-tree t]
  16844. ["Reveal Context" org-reveal t]
  16845. ["Show All" org-show-all t]
  16846. "--"
  16847. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16848. "--"
  16849. ["New Heading" org-insert-heading t]
  16850. ("Navigate Headings"
  16851. ["Up" outline-up-heading t]
  16852. ["Next" outline-next-visible-heading t]
  16853. ["Previous" outline-previous-visible-heading t]
  16854. ["Next Same Level" outline-forward-same-level t]
  16855. ["Previous Same Level" outline-backward-same-level t]
  16856. "--"
  16857. ["Jump" org-goto t])
  16858. ("Edit Structure"
  16859. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  16860. "--"
  16861. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16862. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16863. "--"
  16864. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16865. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16866. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16867. "--"
  16868. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16869. "--"
  16870. ["Copy visible text" org-copy-visible t]
  16871. "--"
  16872. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16873. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16874. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16875. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16876. "--"
  16877. ["Sort Region/Children" org-sort t]
  16878. "--"
  16879. ["Convert to odd levels" org-convert-to-odd-levels t]
  16880. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16881. ("Editing"
  16882. ["Emphasis..." org-emphasize t]
  16883. ["Edit Source Example" org-edit-special t]
  16884. "--"
  16885. ["Footnote new/jump" org-footnote-action t]
  16886. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16887. ("Archive"
  16888. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16889. "--"
  16890. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16891. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16892. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  16893. )
  16894. "--"
  16895. ("Hyperlinks"
  16896. ["Store Link (Global)" org-store-link t]
  16897. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16898. ["Insert Link" org-insert-link t]
  16899. ["Follow Link" org-open-at-point t]
  16900. "--"
  16901. ["Next link" org-next-link t]
  16902. ["Previous link" org-previous-link t]
  16903. "--"
  16904. ["Descriptive Links"
  16905. org-toggle-link-display
  16906. :style radio
  16907. :selected org-descriptive-links
  16908. ]
  16909. ["Literal Links"
  16910. org-toggle-link-display
  16911. :style radio
  16912. :selected (not org-descriptive-links)])
  16913. "--"
  16914. ("TODO Lists"
  16915. ["TODO/DONE/-" org-todo t]
  16916. ("Select keyword"
  16917. ["Next keyword" org-shiftright (org-at-heading-p)]
  16918. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16919. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16920. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16921. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16922. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16923. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16924. "--"
  16925. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16926. :selected org-enforce-todo-dependencies :style toggle :active t]
  16927. "Settings for tree at point"
  16928. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16929. :selected (org-entry-get nil "ORDERED")
  16930. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16931. ["Do Children parallel" org-toggle-ordered-property :style radio
  16932. :selected (not (org-entry-get nil "ORDERED"))
  16933. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16934. "--"
  16935. ["Set Priority" org-priority t]
  16936. ["Priority Up" org-shiftup t]
  16937. ["Priority Down" org-shiftdown t]
  16938. "--"
  16939. ["Get news from all feeds" org-feed-update-all t]
  16940. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16941. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16942. ("TAGS and Properties"
  16943. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16944. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16945. "--"
  16946. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16947. ["Column view of properties" org-columns t]
  16948. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16949. ("Dates and Scheduling"
  16950. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16951. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16952. ("Change Date"
  16953. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16954. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16955. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16956. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16957. ["Compute Time Range" org-evaluate-time-range t]
  16958. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16959. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16960. "--"
  16961. ["Custom time format" org-toggle-time-stamp-overlays
  16962. :style radio :selected org-display-custom-times]
  16963. "--"
  16964. ["Goto Calendar" org-goto-calendar t]
  16965. ["Date from Calendar" org-date-from-calendar t]
  16966. "--"
  16967. ["Start/Restart Timer" org-timer-start t]
  16968. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16969. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16970. ["Insert Timer String" org-timer t]
  16971. ["Insert Timer Item" org-timer-item t])
  16972. ("Logging work"
  16973. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16974. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16975. ["Clock out" org-clock-out t]
  16976. ["Clock cancel" org-clock-cancel t]
  16977. "--"
  16978. ["Mark as default task" org-clock-mark-default-task t]
  16979. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16980. ["Goto running clock" org-clock-goto t]
  16981. "--"
  16982. ["Display times" org-clock-display t]
  16983. ["Create clock table" org-clock-report t]
  16984. "--"
  16985. ["Record DONE time"
  16986. (progn (setq org-log-done (not org-log-done))
  16987. (message "Switching to %s will %s record a timestamp"
  16988. (car org-done-keywords)
  16989. (if org-log-done "automatically" "not")))
  16990. :style toggle :selected org-log-done])
  16991. "--"
  16992. ["Agenda Command..." org-agenda t]
  16993. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16994. ("File List for Agenda")
  16995. ("Special views current file"
  16996. ["TODO Tree" org-show-todo-tree t]
  16997. ["Check Deadlines" org-check-deadlines t]
  16998. ["Tags/Property tree" org-match-sparse-tree t])
  16999. "--"
  17000. ["Export/Publish..." org-export-dispatch t]
  17001. ("LaTeX"
  17002. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  17003. :style toggle :selected org-cdlatex-mode]
  17004. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  17005. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  17006. ["Modify math symbol" org-cdlatex-math-modify
  17007. (org-inside-LaTeX-fragment-p)]
  17008. ["Insert citation" org-reftex-citation t])
  17009. "--"
  17010. ("MobileOrg"
  17011. ["Push Files and Views" org-mobile-push t]
  17012. ["Get Captured and Flagged" org-mobile-pull t]
  17013. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  17014. "--"
  17015. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  17016. "--"
  17017. ("Documentation"
  17018. ["Show Version" org-version t]
  17019. ["Info Documentation" org-info t]
  17020. ["Browse Org News" org-browse-news t])
  17021. ("Customize"
  17022. ["Browse Org Group" org-customize t]
  17023. "--"
  17024. ["Expand This Menu" org-create-customize-menu
  17025. (fboundp 'customize-menu-create)])
  17026. ["Send bug report" org-submit-bug-report t]
  17027. "--"
  17028. ("Refresh/Reload"
  17029. ["Refresh setup current buffer" org-mode-restart t]
  17030. ["Reload Org (after update)" org-reload t]
  17031. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  17032. (defun org-info (&optional node)
  17033. "Read documentation for Org in the info system.
  17034. With optional NODE, go directly to that node."
  17035. (interactive)
  17036. (info (format "(org)%s" (or node ""))))
  17037. (defun org-browse-news ()
  17038. "Browse the news for the latest major release."
  17039. (interactive)
  17040. (browse-url "https://orgmode.org/Changes.html"))
  17041. ;;;###autoload
  17042. (defun org-submit-bug-report ()
  17043. "Submit a bug report on Org via mail.
  17044. Don't hesitate to report any problems or inaccurate documentation.
  17045. If you don't have setup sending mail from (X)Emacs, please copy the
  17046. output buffer into your mail program, as it gives us important
  17047. information about your Org version and configuration."
  17048. (interactive)
  17049. (require 'reporter)
  17050. (defvar reporter-prompt-for-summary-p)
  17051. (org-load-modules-maybe)
  17052. (org-require-autoloaded-modules)
  17053. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  17054. (reporter-submit-bug-report
  17055. "emacs-orgmode@gnu.org"
  17056. (org-version nil 'full)
  17057. (let (list)
  17058. (save-window-excursion
  17059. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  17060. (delete-other-windows)
  17061. (erase-buffer)
  17062. (insert "You are about to submit a bug report to the Org mailing list.
  17063. We would like to add your full Org and Outline configuration to the
  17064. bug report. This greatly simplifies the work of the maintainer and
  17065. other experts on the mailing list.
  17066. HOWEVER, some variables you have customized may contain private
  17067. information. The names of customers, colleagues, or friends, might
  17068. appear in the form of file names, tags, todo states, or search strings.
  17069. If you answer yes to the prompt, you might want to check and remove
  17070. such private information before sending the email.")
  17071. (add-text-properties (point-min) (point-max) '(face org-warning))
  17072. (when (yes-or-no-p "Include your Org configuration ")
  17073. (mapatoms
  17074. (lambda (v)
  17075. (and (boundp v)
  17076. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  17077. (or (and (symbol-value v)
  17078. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  17079. (and
  17080. (get v 'custom-type) (get v 'standard-value)
  17081. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  17082. (push v list)))))
  17083. (kill-buffer (get-buffer "*Warn about privacy*"))
  17084. list))
  17085. nil nil
  17086. "Remember to cover the basics, that is, what you expected to happen and
  17087. what in fact did happen. You don't know how to make a good report? See
  17088. https://orgmode.org/manual/Feedback.html#Feedback
  17089. Your bug report will be posted to the Org mailing list.
  17090. ------------------------------------------------------------------------")
  17091. (save-excursion
  17092. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  17093. (replace-match "\\1Bug: \\3 [\\2]")))))
  17094. (defun org-install-agenda-files-menu ()
  17095. (let ((bl (buffer-list)))
  17096. (save-excursion
  17097. (while bl
  17098. (set-buffer (pop bl))
  17099. (when (derived-mode-p 'org-mode) (setq bl nil)))
  17100. (when (derived-mode-p 'org-mode)
  17101. (easy-menu-change
  17102. '("Org") "File List for Agenda"
  17103. (append
  17104. (list
  17105. ["Edit File List" (org-edit-agenda-file-list) t]
  17106. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  17107. ["Remove Current File from List" org-remove-file t]
  17108. ["Cycle through agenda files" org-cycle-agenda-files t]
  17109. ["Occur in all agenda files" org-occur-in-agenda-files t]
  17110. "--")
  17111. (mapcar 'org-file-menu-entry
  17112. ;; Prevent initialization from failing.
  17113. (ignore-errors (org-agenda-files t)))))))))
  17114. ;;;; Documentation
  17115. (defun org-require-autoloaded-modules ()
  17116. (interactive)
  17117. (mapc #'require
  17118. '(org-agenda org-archive org-attach org-clock org-colview org-id
  17119. org-table org-timer)))
  17120. ;;;###autoload
  17121. (defun org-reload (&optional uncompiled)
  17122. "Reload all Org Lisp files.
  17123. With prefix arg UNCOMPILED, load the uncompiled versions."
  17124. (interactive "P")
  17125. (require 'loadhist)
  17126. (let* ((org-dir (org-find-library-dir "org"))
  17127. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  17128. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  17129. (remove-re (format "\\`%s\\'"
  17130. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  17131. (feats (delete-dups
  17132. (mapcar 'file-name-sans-extension
  17133. (mapcar 'file-name-nondirectory
  17134. (delq nil
  17135. (mapcar 'feature-file
  17136. features))))))
  17137. (lfeat (append
  17138. (sort
  17139. (setq feats
  17140. (delq nil (mapcar
  17141. (lambda (f)
  17142. (if (and (string-match feature-re f)
  17143. (not (string-match remove-re f)))
  17144. f nil))
  17145. feats)))
  17146. 'string-lessp)
  17147. (list "org-version" "org")))
  17148. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  17149. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  17150. load-uncore load-misses)
  17151. (setq load-misses
  17152. (delq 't
  17153. (mapcar (lambda (f)
  17154. (or (org-load-noerror-mustsuffix (concat org-dir f))
  17155. (and (string= org-dir contrib-dir)
  17156. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  17157. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  17158. (add-to-list 'load-uncore f 'append)
  17159. 't)
  17160. f))
  17161. lfeat)))
  17162. (when load-uncore
  17163. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  17164. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  17165. (if load-misses
  17166. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  17167. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  17168. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  17169. ;;;###autoload
  17170. (defun org-customize ()
  17171. "Call the customize function with org as argument."
  17172. (interactive)
  17173. (org-load-modules-maybe)
  17174. (org-require-autoloaded-modules)
  17175. (customize-browse 'org))
  17176. (defun org-create-customize-menu ()
  17177. "Create a full customization menu for Org mode, insert it into the menu."
  17178. (interactive)
  17179. (org-load-modules-maybe)
  17180. (org-require-autoloaded-modules)
  17181. (if (fboundp 'customize-menu-create)
  17182. (progn
  17183. (easy-menu-change
  17184. '("Org") "Customize"
  17185. `(["Browse Org group" org-customize t]
  17186. "--"
  17187. ,(customize-menu-create 'org)
  17188. ["Set" Custom-set t]
  17189. ["Save" Custom-save t]
  17190. ["Reset to Current" Custom-reset-current t]
  17191. ["Reset to Saved" Custom-reset-saved t]
  17192. ["Reset to Standard Settings" Custom-reset-standard t]))
  17193. (message "\"Org\"-menu now contains full customization menu"))
  17194. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  17195. ;;;; Miscellaneous stuff
  17196. ;;; Generally useful functions
  17197. (defun org-in-clocktable-p ()
  17198. "Check if the cursor is in a clocktable."
  17199. (let ((pos (point)) start)
  17200. (save-excursion
  17201. (end-of-line 1)
  17202. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  17203. (setq start (match-beginning 0))
  17204. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  17205. (>= (match-end 0) pos)
  17206. start))))
  17207. (defun org-in-verbatim-emphasis ()
  17208. (save-match-data
  17209. (and (org-in-regexp org-verbatim-re 2)
  17210. (>= (point) (match-beginning 3))
  17211. (<= (point) (match-end 4)))))
  17212. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  17213. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  17214. (if (and marker (marker-buffer marker)
  17215. (buffer-live-p (marker-buffer marker)))
  17216. (progn
  17217. (pop-to-buffer-same-window (marker-buffer marker))
  17218. (when (or (> marker (point-max)) (< marker (point-min)))
  17219. (widen))
  17220. (goto-char marker)
  17221. (org-show-context 'org-goto))
  17222. (if bookmark
  17223. (bookmark-jump bookmark)
  17224. (error "Cannot find location"))))
  17225. (defun org-quote-csv-field (s)
  17226. "Quote field for inclusion in CSV material."
  17227. (if (string-match "[\",]" s)
  17228. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  17229. s))
  17230. (defun org-force-self-insert (N)
  17231. "Needed to enforce self-insert under remapping."
  17232. (interactive "p")
  17233. (self-insert-command N))
  17234. (defun org-quote-vert (s)
  17235. "Replace \"|\" with \"\\vert\"."
  17236. (while (string-match "|" s)
  17237. (setq s (replace-match "\\vert" t t s)))
  17238. s)
  17239. (defun org-uuidgen-p (s)
  17240. "Is S an ID created by UUIDGEN?"
  17241. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  17242. (defun org-in-src-block-p (&optional inside)
  17243. "Whether point is in a code source block.
  17244. When INSIDE is non-nil, don't consider we are within a source
  17245. block when point is at #+BEGIN_SRC or #+END_SRC."
  17246. (let ((case-fold-search t))
  17247. (or (and (eq (get-char-property (point) 'src-block) t))
  17248. (and (not inside)
  17249. (save-match-data
  17250. (save-excursion
  17251. (beginning-of-line)
  17252. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  17253. (defun org-context ()
  17254. "Return a list of contexts of the current cursor position.
  17255. If several contexts apply, all are returned.
  17256. Each context entry is a list with a symbol naming the context, and
  17257. two positions indicating start and end of the context. Possible
  17258. contexts are:
  17259. :headline anywhere in a headline
  17260. :headline-stars on the leading stars in a headline
  17261. :todo-keyword on a TODO keyword (including DONE) in a headline
  17262. :tags on the TAGS in a headline
  17263. :priority on the priority cookie in a headline
  17264. :item on the first line of a plain list item
  17265. :item-bullet on the bullet/number of a plain list item
  17266. :checkbox on the checkbox in a plain list item
  17267. :table in an Org table
  17268. :table-special on a special filed in a table
  17269. :table-table in a table.el table
  17270. :clocktable in a clocktable
  17271. :src-block in a source block
  17272. :link on a hyperlink
  17273. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  17274. :latex-fragment on a LaTeX fragment
  17275. :latex-preview on a LaTeX fragment with overlaid preview image
  17276. This function expects the position to be visible because it uses font-lock
  17277. faces as a help to recognize the following contexts: :table-special, :link,
  17278. and :keyword."
  17279. (let* ((f (get-text-property (point) 'face))
  17280. (faces (if (listp f) f (list f)))
  17281. (case-fold-search t)
  17282. (p (point)) clist o)
  17283. ;; First the large context
  17284. (cond
  17285. ((org-at-heading-p t)
  17286. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  17287. (when (progn
  17288. (beginning-of-line 1)
  17289. (looking-at org-todo-line-tags-regexp))
  17290. (push (org-point-in-group p 1 :headline-stars) clist)
  17291. (push (org-point-in-group p 2 :todo-keyword) clist)
  17292. (push (org-point-in-group p 4 :tags) clist))
  17293. (goto-char p)
  17294. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  17295. (when (looking-at "\\[#[A-Z0-9]\\]")
  17296. (push (org-point-in-group p 0 :priority) clist)))
  17297. ((org-at-item-p)
  17298. (push (org-point-in-group p 2 :item-bullet) clist)
  17299. (push (list :item (point-at-bol)
  17300. (save-excursion (org-end-of-item) (point)))
  17301. clist)
  17302. (and (org-at-item-checkbox-p)
  17303. (push (org-point-in-group p 0 :checkbox) clist)))
  17304. ((org-at-table-p)
  17305. (push (list :table (org-table-begin) (org-table-end)) clist)
  17306. (when (memq 'org-formula faces)
  17307. (push (list :table-special
  17308. (previous-single-property-change p 'face)
  17309. (next-single-property-change p 'face)) clist)))
  17310. ((org-at-table-p 'any)
  17311. (push (list :table-table) clist)))
  17312. (goto-char p)
  17313. (let ((case-fold-search t))
  17314. ;; New the "medium" contexts: clocktables, source blocks
  17315. (cond ((org-in-clocktable-p)
  17316. (push (list :clocktable
  17317. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  17318. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  17319. (match-beginning 1))
  17320. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  17321. (match-end 0))) clist))
  17322. ((org-in-src-block-p)
  17323. (push (list :src-block
  17324. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  17325. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  17326. (match-beginning 1))
  17327. (and (search-forward "#+END_SRC" nil t)
  17328. (match-beginning 0))) clist))))
  17329. (goto-char p)
  17330. ;; Now the small context
  17331. (cond
  17332. ((org-at-timestamp-p)
  17333. (push (org-point-in-group p 0 :timestamp) clist))
  17334. ((memq 'org-link faces)
  17335. (push (list :link
  17336. (previous-single-property-change p 'face)
  17337. (next-single-property-change p 'face)) clist))
  17338. ((memq 'org-special-keyword faces)
  17339. (push (list :keyword
  17340. (previous-single-property-change p 'face)
  17341. (next-single-property-change p 'face)) clist))
  17342. ((setq o (cl-some
  17343. (lambda (o)
  17344. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  17345. o))
  17346. (overlays-at (point))))
  17347. (push (list :latex-fragment
  17348. (overlay-start o) (overlay-end o)) clist)
  17349. (push (list :latex-preview
  17350. (overlay-start o) (overlay-end o)) clist))
  17351. ((org-inside-LaTeX-fragment-p)
  17352. ;; FIXME: positions wrong.
  17353. (push (list :latex-fragment (point) (point)) clist)))
  17354. (setq clist (nreverse (delq nil clist)))
  17355. clist))
  17356. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  17357. "Non-nil when point is between matches of START-RE and END-RE.
  17358. Also return a non-nil value when point is on one of the matches.
  17359. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  17360. buffer positions. Default values are the positions of headlines
  17361. surrounding the point.
  17362. The functions returns a cons cell whose car (resp. cdr) is the
  17363. position before START-RE (resp. after END-RE)."
  17364. (save-match-data
  17365. (let ((pos (point))
  17366. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  17367. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  17368. beg end)
  17369. (save-excursion
  17370. ;; Point is on a block when on START-RE or if START-RE can be
  17371. ;; found before it...
  17372. (and (or (org-in-regexp start-re)
  17373. (re-search-backward start-re limit-up t))
  17374. (setq beg (match-beginning 0))
  17375. ;; ... and END-RE after it...
  17376. (goto-char (match-end 0))
  17377. (re-search-forward end-re limit-down t)
  17378. (> (setq end (match-end 0)) pos)
  17379. ;; ... without another START-RE in-between.
  17380. (goto-char (match-beginning 0))
  17381. (not (re-search-backward start-re (1+ beg) t))
  17382. ;; Return value.
  17383. (cons beg end))))))
  17384. (defun org-in-block-p (names)
  17385. "Non-nil when point belongs to a block whose name belongs to NAMES.
  17386. NAMES is a list of strings containing names of blocks.
  17387. Return first block name matched, or nil. Beware that in case of
  17388. nested blocks, the returned name may not belong to the closest
  17389. block from point."
  17390. (save-match-data
  17391. (catch 'exit
  17392. (let ((case-fold-search t)
  17393. (lim-up (save-excursion (outline-previous-heading)))
  17394. (lim-down (save-excursion (outline-next-heading))))
  17395. (dolist (name names)
  17396. (let ((n (regexp-quote name)))
  17397. (when (org-between-regexps-p
  17398. (concat "^[ \t]*#\\+begin_" n)
  17399. (concat "^[ \t]*#\\+end_" n)
  17400. lim-up lim-down)
  17401. (throw 'exit n)))))
  17402. nil)))
  17403. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  17404. "Call `multi-occur' with buffers for all agenda files."
  17405. (interactive "sOrg-files matching: ")
  17406. (let* ((files (org-agenda-files))
  17407. (tnames (mapcar #'file-truename files))
  17408. (extra org-agenda-text-search-extra-files))
  17409. (when (eq (car extra) 'agenda-archives)
  17410. (setq extra (cdr extra))
  17411. (setq files (org-add-archive-files files)))
  17412. (dolist (f extra)
  17413. (unless (member (file-truename f) tnames)
  17414. (unless (member f files) (setq files (append files (list f))))
  17415. (setq tnames (append tnames (list (file-truename f))))))
  17416. (multi-occur
  17417. (mapcar (lambda (x)
  17418. (with-current-buffer
  17419. ;; FIXME: Why not just (find-file-noselect x)?
  17420. ;; Is it to avoid the "revert buffer" prompt?
  17421. (or (get-file-buffer x) (find-file-noselect x))
  17422. (widen)
  17423. (current-buffer)))
  17424. files)
  17425. regexp)))
  17426. (add-hook 'occur-mode-find-occurrence-hook
  17427. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17428. (defun org-occur-link-in-agenda-files ()
  17429. "Create a link and search for it in the agendas.
  17430. The link is not stored in `org-stored-links', it is just created
  17431. for the search purpose."
  17432. (interactive)
  17433. (let ((link (condition-case nil
  17434. (org-store-link nil)
  17435. (error "Unable to create a link to here"))))
  17436. (org-occur-in-agenda-files (regexp-quote link))))
  17437. (defun org-back-over-empty-lines ()
  17438. "Move backwards over whitespace, to the beginning of the first empty line.
  17439. Returns the number of empty lines passed."
  17440. (let ((pos (point)))
  17441. (if (cdr (assq 'heading org-blank-before-new-entry))
  17442. (skip-chars-backward " \t\n\r")
  17443. (unless (eobp)
  17444. (forward-line -1)))
  17445. (beginning-of-line 2)
  17446. (goto-char (min (point) pos))
  17447. (count-lines (point) pos)))
  17448. ;;; TODO: Only called once, from ox-odt which should probably use
  17449. ;;; org-export-inline-image-p or something.
  17450. (defun org-file-image-p (file)
  17451. "Return non-nil if FILE is an image."
  17452. (save-match-data
  17453. (string-match (image-file-name-regexp) file)))
  17454. (defun org-get-cursor-date (&optional with-time)
  17455. "Return the date at cursor in as a time.
  17456. This works in the calendar and in the agenda, anywhere else it just
  17457. returns the current time.
  17458. If WITH-TIME is non-nil, returns the time of the event at point (in
  17459. the agenda) or the current time of the day; otherwise returns the
  17460. earliest time on the cursor date that Org treats as that date
  17461. (bearing in mind `org-extend-today-until')."
  17462. (let (date day defd tp hod mod)
  17463. (when with-time
  17464. (setq tp (get-text-property (point) 'time))
  17465. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  17466. (setq hod (string-to-number (match-string 1 tp))
  17467. mod (string-to-number (match-string 2 tp))))
  17468. (or tp (let ((now (decode-time)))
  17469. (setq hod (nth 2 now)
  17470. mod (nth 1 now)))))
  17471. (cond
  17472. ((eq major-mode 'calendar-mode)
  17473. (setq date (calendar-cursor-to-date)
  17474. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17475. (nth 1 date) (nth 0 date) (nth 2 date))))
  17476. ((eq major-mode 'org-agenda-mode)
  17477. (setq day (get-text-property (point) 'day))
  17478. (when day
  17479. (setq date (calendar-gregorian-from-absolute day)
  17480. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17481. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17482. (or defd (current-time))))
  17483. (defun org-mark-subtree (&optional up)
  17484. "Mark the current subtree.
  17485. This puts point at the start of the current subtree, and mark at
  17486. the end. If a numeric prefix UP is given, move up into the
  17487. hierarchy of headlines by UP levels before marking the subtree."
  17488. (interactive "P")
  17489. (org-with-limited-levels
  17490. (cond ((org-at-heading-p) (beginning-of-line))
  17491. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17492. (t (outline-previous-visible-heading 1))))
  17493. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17494. (if (called-interactively-p 'any)
  17495. (call-interactively 'org-mark-element)
  17496. (org-mark-element)))
  17497. ;;; Indentation
  17498. (defvar org-element-greater-elements)
  17499. (defun org--get-expected-indentation (element contentsp)
  17500. "Expected indentation column for current line, according to ELEMENT.
  17501. ELEMENT is an element containing point. CONTENTSP is non-nil
  17502. when indentation is to be computed according to contents of
  17503. ELEMENT."
  17504. (let ((type (org-element-type element))
  17505. (start (org-element-property :begin element))
  17506. (post-affiliated (org-element-property :post-affiliated element)))
  17507. (org-with-wide-buffer
  17508. (cond
  17509. (contentsp
  17510. (cl-case type
  17511. ((diary-sexp footnote-definition) 0)
  17512. ((headline inlinetask nil)
  17513. (if (not org-adapt-indentation) 0
  17514. (let ((level (org-current-level)))
  17515. (if level (1+ level) 0))))
  17516. ((item plain-list) (org-list-item-body-column post-affiliated))
  17517. (t
  17518. (goto-char start)
  17519. (current-indentation))))
  17520. ((memq type '(headline inlinetask nil))
  17521. (if (org-match-line "[ \t]*$")
  17522. (org--get-expected-indentation element t)
  17523. 0))
  17524. ((memq type '(diary-sexp footnote-definition)) 0)
  17525. ;; First paragraph of a footnote definition or an item.
  17526. ;; Indent like parent.
  17527. ((< (line-beginning-position) start)
  17528. (org--get-expected-indentation
  17529. (org-element-property :parent element) t))
  17530. ;; At first line: indent according to previous sibling, if any,
  17531. ;; ignoring footnote definitions and inline tasks, or parent's
  17532. ;; contents.
  17533. ((= (line-beginning-position) start)
  17534. (catch 'exit
  17535. (while t
  17536. (if (= (point-min) start) (throw 'exit 0)
  17537. (goto-char (1- start))
  17538. (let* ((previous (org-element-at-point))
  17539. (parent previous))
  17540. (while (and parent (<= (org-element-property :end parent) start))
  17541. (setq previous parent
  17542. parent (org-element-property :parent parent)))
  17543. (cond
  17544. ((not previous) (throw 'exit 0))
  17545. ((> (org-element-property :end previous) start)
  17546. (throw 'exit (org--get-expected-indentation previous t)))
  17547. ((memq (org-element-type previous)
  17548. '(footnote-definition inlinetask))
  17549. (setq start (org-element-property :begin previous)))
  17550. (t (goto-char (org-element-property :begin previous))
  17551. (throw 'exit
  17552. (if (bolp) (current-indentation)
  17553. ;; At first paragraph in an item or
  17554. ;; a footnote definition.
  17555. (org--get-expected-indentation
  17556. (org-element-property :parent previous) t))))))))))
  17557. ;; Otherwise, move to the first non-blank line above.
  17558. (t
  17559. (beginning-of-line)
  17560. (let ((pos (point)))
  17561. (skip-chars-backward " \r\t\n")
  17562. (cond
  17563. ;; Two blank lines end a footnote definition or a plain
  17564. ;; list. When we indent an empty line after them, the
  17565. ;; containing list or footnote definition is over, so it
  17566. ;; qualifies as a previous sibling. Therefore, we indent
  17567. ;; like its first line.
  17568. ((and (memq type '(footnote-definition plain-list))
  17569. (> (count-lines (point) pos) 2))
  17570. (goto-char start)
  17571. (current-indentation))
  17572. ;; Line above is the first one of a paragraph at the
  17573. ;; beginning of an item or a footnote definition. Indent
  17574. ;; like parent.
  17575. ((< (line-beginning-position) start)
  17576. (org--get-expected-indentation
  17577. (org-element-property :parent element) t))
  17578. ;; Line above is the beginning of an element, i.e., point
  17579. ;; was originally on the blank lines between element's start
  17580. ;; and contents.
  17581. ((= (line-beginning-position) post-affiliated)
  17582. (org--get-expected-indentation element t))
  17583. ;; POS is after contents in a greater element. Indent like
  17584. ;; the beginning of the element.
  17585. ((and (memq type org-element-greater-elements)
  17586. (let ((cend (org-element-property :contents-end element)))
  17587. (and cend (<= cend pos))))
  17588. ;; As a special case, if point is at the end of a footnote
  17589. ;; definition or an item, indent like the very last element
  17590. ;; within. If that last element is an item, indent like
  17591. ;; its contents.
  17592. (if (memq type '(footnote-definition item plain-list))
  17593. (let ((last (org-element-at-point)))
  17594. (goto-char pos)
  17595. (org--get-expected-indentation
  17596. last (eq (org-element-type last) 'item)))
  17597. (goto-char start)
  17598. (current-indentation)))
  17599. ;; In any other case, indent like the current line.
  17600. (t (current-indentation)))))))))
  17601. (defun org--align-node-property ()
  17602. "Align node property at point.
  17603. Alignment is done according to `org-property-format', which see."
  17604. (when (save-excursion
  17605. (beginning-of-line)
  17606. (looking-at org-property-re))
  17607. (replace-match
  17608. (concat (match-string 4)
  17609. (org-trim
  17610. (format org-property-format (match-string 1) (match-string 3))))
  17611. t t)))
  17612. (defun org-indent-line ()
  17613. "Indent line depending on context.
  17614. Indentation is done according to the following rules:
  17615. - Footnote definitions, diary sexps, headlines and inline tasks
  17616. have to start at column 0.
  17617. - On the very first line of an element, consider, in order, the
  17618. next rules until one matches:
  17619. 1. If there's a sibling element before, ignoring footnote
  17620. definitions and inline tasks, indent like its first line.
  17621. 2. If element has a parent, indent like its contents. More
  17622. precisely, if parent is an item, indent after the bullet.
  17623. Else, indent like parent's first line.
  17624. 3. Otherwise, indent relatively to current level, if
  17625. `org-adapt-indentation' is non-nil, or to left margin.
  17626. - On a blank line at the end of an element, indent according to
  17627. the type of the element. More precisely
  17628. 1. If element is a plain list, an item, or a footnote
  17629. definition, indent like the very last element within.
  17630. 2. If element is a paragraph, indent like its last non blank
  17631. line.
  17632. 3. Otherwise, indent like its very first line.
  17633. - In the code part of a source block, use language major mode
  17634. to indent current line if `org-src-tab-acts-natively' is
  17635. non-nil. If it is nil, do nothing.
  17636. - Otherwise, indent like the first non-blank line above.
  17637. The function doesn't indent an item as it could break the whole
  17638. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17639. `\\[org-shiftmetaright]'.
  17640. Also align node properties according to `org-property-format'."
  17641. (interactive)
  17642. (cond
  17643. ((org-at-heading-p) 'noindent)
  17644. (t
  17645. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17646. (type (org-element-type element)))
  17647. (cond ((and (memq type '(plain-list item))
  17648. (= (line-beginning-position)
  17649. (org-element-property :post-affiliated element)))
  17650. 'noindent)
  17651. ((and (eq type 'latex-environment)
  17652. (>= (point) (org-element-property :post-affiliated element))
  17653. (< (point) (org-with-wide-buffer
  17654. (goto-char (org-element-property :end element))
  17655. (skip-chars-backward " \r\t\n")
  17656. (line-beginning-position 2))))
  17657. 'noindent)
  17658. ((and (eq type 'src-block)
  17659. org-src-tab-acts-natively
  17660. (> (line-beginning-position)
  17661. (org-element-property :post-affiliated element))
  17662. (< (line-beginning-position)
  17663. (org-with-wide-buffer
  17664. (goto-char (org-element-property :end element))
  17665. (skip-chars-backward " \r\t\n")
  17666. (line-beginning-position))))
  17667. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17668. (t
  17669. (let ((column (org--get-expected-indentation element nil)))
  17670. ;; Preserve current column.
  17671. (if (<= (current-column) (current-indentation))
  17672. (indent-line-to column)
  17673. (save-excursion (indent-line-to column))))
  17674. ;; Align node property. Also preserve current column.
  17675. (when (eq type 'node-property)
  17676. (let ((column (current-column)))
  17677. (org--align-node-property)
  17678. (org-move-to-column column)))))))))
  17679. (defun org-indent-region (start end)
  17680. "Indent each non-blank line in the region.
  17681. Called from a program, START and END specify the region to
  17682. indent. The function will not indent contents of example blocks,
  17683. verse blocks and export blocks as leading white spaces are
  17684. assumed to be significant there."
  17685. (interactive "r")
  17686. (save-excursion
  17687. (goto-char start)
  17688. (skip-chars-forward " \r\t\n")
  17689. (unless (eobp) (beginning-of-line))
  17690. (let ((indent-to
  17691. (lambda (ind pos)
  17692. ;; Set IND as indentation for all lines between point and
  17693. ;; POS. Blank lines are ignored. Leave point after POS
  17694. ;; once done.
  17695. (let ((limit (copy-marker pos)))
  17696. (while (< (point) limit)
  17697. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17698. (forward-line))
  17699. (set-marker limit nil))))
  17700. (end (copy-marker end)))
  17701. (while (< (point) end)
  17702. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17703. (let* ((element (org-element-at-point))
  17704. (type (org-element-type element))
  17705. (element-end (copy-marker (org-element-property :end element)))
  17706. (ind (org--get-expected-indentation element nil)))
  17707. (cond
  17708. ;; Element indented as a single block. Example blocks
  17709. ;; preserving indentation are a special case since the
  17710. ;; "contents" must not be indented whereas the block
  17711. ;; boundaries can.
  17712. ((or (memq type '(export-block latex-environment))
  17713. (and (eq type 'example-block)
  17714. (not
  17715. (or org-src-preserve-indentation
  17716. (org-element-property :preserve-indent element)))))
  17717. (let ((offset (- ind (current-indentation))))
  17718. (unless (zerop offset)
  17719. (indent-rigidly (org-element-property :begin element)
  17720. (org-element-property :end element)
  17721. offset)))
  17722. (goto-char element-end))
  17723. ;; Elements indented line wise. Be sure to exclude
  17724. ;; example blocks (preserving indentation) and source
  17725. ;; blocks from this category as they are treated
  17726. ;; specially later.
  17727. ((or (memq type '(paragraph table table-row))
  17728. (not (or (org-element-property :contents-begin element)
  17729. (memq type '(example-block src-block)))))
  17730. (when (eq type 'node-property)
  17731. (org--align-node-property)
  17732. (beginning-of-line))
  17733. (funcall indent-to ind (min element-end end)))
  17734. ;; Elements consisting of three parts: before the
  17735. ;; contents, the contents, and after the contents. The
  17736. ;; contents are treated specially, according to the
  17737. ;; element type, or not indented at all. Other parts are
  17738. ;; indented as a single block.
  17739. (t
  17740. (let* ((post (copy-marker
  17741. (org-element-property :post-affiliated element)))
  17742. (cbeg
  17743. (copy-marker
  17744. (cond
  17745. ((not (org-element-property :contents-begin element))
  17746. ;; Fake contents for source blocks.
  17747. (org-with-wide-buffer
  17748. (goto-char post)
  17749. (line-beginning-position 2)))
  17750. ((memq type '(footnote-definition item plain-list))
  17751. ;; Contents in these elements could start on
  17752. ;; the same line as the beginning of the
  17753. ;; element. Make sure we start indenting
  17754. ;; from the second line.
  17755. (org-with-wide-buffer
  17756. (goto-char post)
  17757. (end-of-line)
  17758. (skip-chars-forward " \r\t\n")
  17759. (if (eobp) (point) (line-beginning-position))))
  17760. (t (org-element-property :contents-begin element)))))
  17761. (cend (copy-marker
  17762. (or (org-element-property :contents-end element)
  17763. ;; Fake contents for source blocks.
  17764. (org-with-wide-buffer
  17765. (goto-char element-end)
  17766. (skip-chars-backward " \r\t\n")
  17767. (line-beginning-position)))
  17768. t)))
  17769. ;; Do not change items indentation individually as it
  17770. ;; might break the list as a whole. On the other
  17771. ;; hand, when at a plain list, indent it as a whole.
  17772. (cond ((eq type 'plain-list)
  17773. (let ((offset (- ind (current-indentation))))
  17774. (unless (zerop offset)
  17775. (indent-rigidly (org-element-property :begin element)
  17776. (org-element-property :end element)
  17777. offset))
  17778. (goto-char cbeg)))
  17779. ((eq type 'item) (goto-char cbeg))
  17780. (t (funcall indent-to ind (min cbeg end))))
  17781. (when (< (point) end)
  17782. (cl-case type
  17783. ((example-block verse-block))
  17784. (src-block
  17785. ;; In a source block, indent source code
  17786. ;; according to language major mode, but only if
  17787. ;; `org-src-tab-acts-natively' is non-nil.
  17788. (when (and (< (point) end) org-src-tab-acts-natively)
  17789. (ignore-errors
  17790. (org-babel-do-in-edit-buffer
  17791. (indent-region (point-min) (point-max))))))
  17792. (t (org-indent-region (point) (min cend end))))
  17793. (goto-char (min cend end))
  17794. (when (< (point) end)
  17795. (funcall indent-to ind (min element-end end))))
  17796. (set-marker post nil)
  17797. (set-marker cbeg nil)
  17798. (set-marker cend nil))))
  17799. (set-marker element-end nil))))
  17800. (set-marker end nil))))
  17801. (defun org-indent-drawer ()
  17802. "Indent the drawer at point."
  17803. (interactive)
  17804. (unless (save-excursion
  17805. (beginning-of-line)
  17806. (looking-at-p org-drawer-regexp))
  17807. (user-error "Not at a drawer"))
  17808. (let ((element (org-element-at-point)))
  17809. (unless (memq (org-element-type element) '(drawer property-drawer))
  17810. (user-error "Not at a drawer"))
  17811. (org-with-wide-buffer
  17812. (org-indent-region (org-element-property :begin element)
  17813. (org-element-property :end element))))
  17814. (message "Drawer at point indented"))
  17815. (defun org-indent-block ()
  17816. "Indent the block at point."
  17817. (interactive)
  17818. (unless (save-excursion
  17819. (beginning-of-line)
  17820. (let ((case-fold-search t))
  17821. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17822. (user-error "Not at a block"))
  17823. (let ((element (org-element-at-point)))
  17824. (unless (memq (org-element-type element)
  17825. '(comment-block center-block dynamic-block example-block
  17826. export-block quote-block special-block
  17827. src-block verse-block))
  17828. (user-error "Not at a block"))
  17829. (org-with-wide-buffer
  17830. (org-indent-region (org-element-property :begin element)
  17831. (org-element-property :end element))))
  17832. (message "Block at point indented"))
  17833. ;;; Filling
  17834. ;; We use our own fill-paragraph and auto-fill functions.
  17835. ;; `org-fill-paragraph' relies on adaptive filling and context
  17836. ;; checking. Appropriate `fill-prefix' is computed with
  17837. ;; `org-adaptive-fill-function'.
  17838. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17839. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17840. ;; `org-adaptive-fill-function' value. Internally,
  17841. ;; `org-comment-line-break-function' breaks the line.
  17842. ;; `org-setup-filling' installs filling and auto-filling related
  17843. ;; variables during `org-mode' initialization.
  17844. (defun org-setup-filling ()
  17845. (require 'org-element)
  17846. ;; Prevent auto-fill from inserting unwanted new items.
  17847. (when (boundp 'fill-nobreak-predicate)
  17848. (setq-local
  17849. fill-nobreak-predicate
  17850. (org-uniquify
  17851. (append fill-nobreak-predicate
  17852. '(org-fill-line-break-nobreak-p
  17853. org-fill-n-macro-as-item-nobreak-p
  17854. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17855. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17856. (setq-local paragraph-start paragraph-ending)
  17857. (setq-local paragraph-separate paragraph-ending))
  17858. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17859. (setq-local auto-fill-inhibit-regexp nil)
  17860. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17861. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17862. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17863. (defun org-fill-line-break-nobreak-p ()
  17864. "Non-nil when a new line at point would create an Org line break."
  17865. (save-excursion
  17866. (skip-chars-backward " \t")
  17867. (skip-chars-backward "\\\\")
  17868. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17869. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17870. "Non-nil when a new line at point would split a timestamp."
  17871. (and (org-at-timestamp-p 'lax)
  17872. (not (looking-at org-ts-regexp-both))))
  17873. (defun org-fill-n-macro-as-item-nobreak-p ()
  17874. "Non-nil when a new line at point would create a new list."
  17875. ;; During export, a "n" macro followed by a dot or a closing
  17876. ;; parenthesis can end up being parsed as a new list item.
  17877. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17878. (defun org-adaptive-fill-function ()
  17879. "Compute a fill prefix for the current line.
  17880. Return fill prefix, as a string, or nil if current line isn't
  17881. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17882. matches in paragraphs or comments, use it."
  17883. (org-with-wide-buffer
  17884. (unless (org-at-heading-p)
  17885. (let* ((p (line-beginning-position))
  17886. (element (save-excursion
  17887. (beginning-of-line)
  17888. (org-element-at-point)))
  17889. (type (org-element-type element))
  17890. (post-affiliated (org-element-property :post-affiliated element)))
  17891. (unless (< p post-affiliated)
  17892. (cl-case type
  17893. (comment
  17894. (save-excursion
  17895. (beginning-of-line)
  17896. (looking-at "[ \t]*")
  17897. (concat (match-string 0) "# ")))
  17898. (footnote-definition "")
  17899. ((item plain-list)
  17900. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17901. (paragraph
  17902. ;; Fill prefix is usually the same as the current line,
  17903. ;; unless the paragraph is at the beginning of an item.
  17904. (let ((parent (org-element-property :parent element)))
  17905. (save-excursion
  17906. (beginning-of-line)
  17907. (cond ((eq (org-element-type parent) 'item)
  17908. (make-string (org-list-item-body-column
  17909. (org-element-property :begin parent))
  17910. ?\s))
  17911. ((and adaptive-fill-regexp
  17912. ;; Locally disable
  17913. ;; `adaptive-fill-function' to let
  17914. ;; `fill-context-prefix' handle
  17915. ;; `adaptive-fill-regexp' variable.
  17916. (let (adaptive-fill-function)
  17917. (fill-context-prefix
  17918. post-affiliated
  17919. (org-element-property :end element)))))
  17920. ((looking-at "[ \t]+") (match-string 0))
  17921. (t "")))))
  17922. (comment-block
  17923. ;; Only fill contents if P is within block boundaries.
  17924. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17925. (forward-line)
  17926. (point)))
  17927. (cend (save-excursion
  17928. (goto-char (org-element-property :end element))
  17929. (skip-chars-backward " \r\t\n")
  17930. (line-beginning-position))))
  17931. (when (and (>= p cbeg) (< p cend))
  17932. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17933. (match-string 0)
  17934. ""))))))))))
  17935. (defun org-fill-element (&optional justify)
  17936. "Fill element at point, when applicable.
  17937. This function only applies to comment blocks, comments, example
  17938. blocks and paragraphs. Also, as a special case, re-align table
  17939. when point is at one.
  17940. If JUSTIFY is non-nil (interactively, with prefix argument),
  17941. justify as well. If `sentence-end-double-space' is non-nil, then
  17942. period followed by one space does not end a sentence, so don't
  17943. break a line there. The variable `fill-column' controls the
  17944. width for filling.
  17945. For convenience, when point is at a plain list, an item or
  17946. a footnote definition, try to fill the first paragraph within."
  17947. (with-syntax-table org-mode-transpose-word-syntax-table
  17948. ;; Move to end of line in order to get the first paragraph within
  17949. ;; a plain list or a footnote definition.
  17950. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17951. ;; First check if point is in a blank line at the beginning of
  17952. ;; the buffer. In that case, ignore filling.
  17953. (cl-case (org-element-type element)
  17954. ;; Use major mode filling function is source blocks.
  17955. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  17956. ;; Align Org tables, leave table.el tables as-is.
  17957. (table-row (org-table-align) t)
  17958. (table
  17959. (when (eq (org-element-property :type element) 'org)
  17960. (save-excursion
  17961. (goto-char (org-element-property :post-affiliated element))
  17962. (org-table-align)))
  17963. t)
  17964. (paragraph
  17965. ;; Paragraphs may contain `line-break' type objects.
  17966. (let ((beg (max (point-min)
  17967. (org-element-property :contents-begin element)))
  17968. (end (min (point-max)
  17969. (org-element-property :contents-end element))))
  17970. ;; Do nothing if point is at an affiliated keyword.
  17971. (if (< (line-end-position) beg) t
  17972. ;; Fill paragraph, taking line breaks into account.
  17973. (save-excursion
  17974. (goto-char beg)
  17975. (let ((cuts (list beg)))
  17976. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17977. (when (eq 'line-break
  17978. (org-element-type
  17979. (save-excursion (backward-char)
  17980. (org-element-context))))
  17981. (push (point) cuts)))
  17982. (dolist (c (delq end cuts))
  17983. (fill-region-as-paragraph c end justify)
  17984. (setq end c))))
  17985. t)))
  17986. ;; Contents of `comment-block' type elements should be
  17987. ;; filled as plain text, but only if point is within block
  17988. ;; markers.
  17989. (comment-block
  17990. (let* ((case-fold-search t)
  17991. (beg (save-excursion
  17992. (goto-char (org-element-property :begin element))
  17993. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17994. (forward-line)
  17995. (point)))
  17996. (end (save-excursion
  17997. (goto-char (org-element-property :end element))
  17998. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17999. (line-beginning-position))))
  18000. (if (or (< (point) beg) (> (point) end)) t
  18001. (fill-region-as-paragraph
  18002. (save-excursion (end-of-line)
  18003. (re-search-backward "^[ \t]*$" beg 'move)
  18004. (line-beginning-position))
  18005. (save-excursion (beginning-of-line)
  18006. (re-search-forward "^[ \t]*$" end 'move)
  18007. (line-beginning-position))
  18008. justify))))
  18009. ;; Fill comments.
  18010. (comment
  18011. (let ((begin (org-element-property :post-affiliated element))
  18012. (end (org-element-property :end element)))
  18013. (when (and (>= (point) begin) (<= (point) end))
  18014. (let ((begin (save-excursion
  18015. (end-of-line)
  18016. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  18017. (progn (forward-line) (point))
  18018. begin)))
  18019. (end (save-excursion
  18020. (end-of-line)
  18021. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  18022. (1- (line-beginning-position))
  18023. (skip-chars-backward " \r\t\n")
  18024. (line-end-position)))))
  18025. ;; Do not fill comments when at a blank line.
  18026. (when (> end begin)
  18027. (let ((fill-prefix
  18028. (save-excursion
  18029. (beginning-of-line)
  18030. (looking-at "[ \t]*#")
  18031. (let ((comment-prefix (match-string 0)))
  18032. (goto-char (match-end 0))
  18033. (if (looking-at adaptive-fill-regexp)
  18034. (concat comment-prefix (match-string 0))
  18035. (concat comment-prefix " "))))))
  18036. (save-excursion
  18037. (fill-region-as-paragraph begin end justify))))))
  18038. t))
  18039. ;; Ignore every other element.
  18040. (otherwise t)))))
  18041. (defun org-fill-paragraph (&optional justify region)
  18042. "Fill element at point, when applicable.
  18043. This function only applies to comment blocks, comments, example
  18044. blocks and paragraphs. Also, as a special case, re-align table
  18045. when point is at one.
  18046. For convenience, when point is at a plain list, an item or
  18047. a footnote definition, try to fill the first paragraph within.
  18048. If JUSTIFY is non-nil (interactively, with prefix argument),
  18049. justify as well. If `sentence-end-double-space' is non-nil, then
  18050. period followed by one space does not end a sentence, so don't
  18051. break a line there. The variable `fill-column' controls the
  18052. width for filling.
  18053. The REGION argument is non-nil if called interactively; in that
  18054. case, if Transient Mark mode is enabled and the mark is active,
  18055. fill each of the elements in the active region, instead of just
  18056. filling the current element."
  18057. (interactive (progn
  18058. (barf-if-buffer-read-only)
  18059. (list (when current-prefix-arg 'full) t)))
  18060. (let ((hash (and (not (buffer-modified-p))
  18061. (org-buffer-hash))))
  18062. (cond
  18063. ((and region transient-mark-mode mark-active
  18064. (not (eq (region-beginning) (region-end))))
  18065. (let ((origin (point-marker))
  18066. (start (region-beginning)))
  18067. (unwind-protect
  18068. (progn
  18069. (goto-char (region-end))
  18070. (while (> (point) start)
  18071. (org-backward-paragraph)
  18072. (org-fill-element justify)))
  18073. (goto-char origin)
  18074. (set-marker origin nil))))
  18075. (t (org-fill-element justify)))
  18076. ;; If we didn't change anything in the buffer (and the buffer was
  18077. ;; previously unmodified), then flip the modification status back
  18078. ;; to "unchanged".
  18079. (when (and hash (equal hash (org-buffer-hash)))
  18080. (set-buffer-modified-p nil))))
  18081. (defun org-auto-fill-function ()
  18082. "Auto-fill function."
  18083. ;; Check if auto-filling is meaningful.
  18084. (let ((fc (current-fill-column)))
  18085. (when (and fc (> (current-column) fc))
  18086. (let* ((fill-prefix (org-adaptive-fill-function))
  18087. ;; Enforce empty fill prefix, if required. Otherwise, it
  18088. ;; will be computed again.
  18089. (adaptive-fill-mode (not (equal fill-prefix ""))))
  18090. (when fill-prefix (do-auto-fill))))))
  18091. (defun org-comment-line-break-function (&optional soft)
  18092. "Break line at point and indent, continuing comment if within one.
  18093. The inserted newline is marked hard if variable
  18094. `use-hard-newlines' is true, unless optional argument SOFT is
  18095. non-nil."
  18096. (if soft (insert-and-inherit ?\n) (newline 1))
  18097. (save-excursion (forward-char -1) (delete-horizontal-space))
  18098. (delete-horizontal-space)
  18099. (indent-to-left-margin)
  18100. (insert-before-markers-and-inherit fill-prefix))
  18101. ;;; Fixed Width Areas
  18102. (defun org-toggle-fixed-width ()
  18103. "Toggle fixed-width markup.
  18104. Add or remove fixed-width markup on current line, whenever it
  18105. makes sense. Return an error otherwise.
  18106. If a region is active and if it contains only fixed-width areas
  18107. or blank lines, remove all fixed-width markup in it. If the
  18108. region contains anything else, convert all non-fixed-width lines
  18109. to fixed-width ones.
  18110. Blank lines at the end of the region are ignored unless the
  18111. region only contains such lines."
  18112. (interactive)
  18113. (if (not (org-region-active-p))
  18114. ;; No region:
  18115. ;;
  18116. ;; Remove fixed width marker only in a fixed-with element.
  18117. ;;
  18118. ;; Add fixed width maker in paragraphs, in blank lines after
  18119. ;; elements or at the beginning of a headline or an inlinetask,
  18120. ;; and before any one-line elements (e.g., a clock).
  18121. (progn
  18122. (beginning-of-line)
  18123. (let* ((element (org-element-at-point))
  18124. (type (org-element-type element)))
  18125. (cond
  18126. ((and (eq type 'fixed-width)
  18127. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  18128. (replace-match
  18129. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  18130. ((and (memq type '(babel-call clock comment diary-sexp headline
  18131. horizontal-rule keyword paragraph
  18132. planning))
  18133. (<= (org-element-property :post-affiliated element) (point)))
  18134. (skip-chars-forward " \t")
  18135. (insert ": "))
  18136. ((and (looking-at-p "[ \t]*$")
  18137. (or (eq type 'inlinetask)
  18138. (save-excursion
  18139. (skip-chars-forward " \r\t\n")
  18140. (<= (org-element-property :end element) (point)))))
  18141. (delete-region (point) (line-end-position))
  18142. (org-indent-line)
  18143. (insert ": "))
  18144. (t (user-error "Cannot insert a fixed-width line here")))))
  18145. ;; Region active.
  18146. (let* ((begin (save-excursion
  18147. (goto-char (region-beginning))
  18148. (line-beginning-position)))
  18149. (end (copy-marker
  18150. (save-excursion
  18151. (goto-char (region-end))
  18152. (unless (eolp) (beginning-of-line))
  18153. (if (save-excursion (re-search-backward "\\S-" begin t))
  18154. (progn (skip-chars-backward " \r\t\n") (point))
  18155. (point)))))
  18156. (all-fixed-width-p
  18157. (catch 'not-all-p
  18158. (save-excursion
  18159. (goto-char begin)
  18160. (skip-chars-forward " \r\t\n")
  18161. (when (eobp) (throw 'not-all-p nil))
  18162. (while (< (point) end)
  18163. (let ((element (org-element-at-point)))
  18164. (if (eq (org-element-type element) 'fixed-width)
  18165. (goto-char (org-element-property :end element))
  18166. (throw 'not-all-p nil))))
  18167. t))))
  18168. (if all-fixed-width-p
  18169. (save-excursion
  18170. (goto-char begin)
  18171. (while (< (point) end)
  18172. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  18173. (replace-match
  18174. "" nil nil nil
  18175. (if (= (line-end-position) (match-end 0)) 0 1)))
  18176. (forward-line)))
  18177. (let ((min-ind (point-max)))
  18178. ;; Find minimum indentation across all lines.
  18179. (save-excursion
  18180. (goto-char begin)
  18181. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  18182. (setq min-ind 0)
  18183. (catch 'zerop
  18184. (while (< (point) end)
  18185. (unless (looking-at-p "[ \t]*$")
  18186. (let ((ind (current-indentation)))
  18187. (setq min-ind (min min-ind ind))
  18188. (when (zerop ind) (throw 'zerop t))))
  18189. (forward-line)))))
  18190. ;; Loop over all lines and add fixed-width markup everywhere
  18191. ;; but in fixed-width lines.
  18192. (save-excursion
  18193. (goto-char begin)
  18194. (while (< (point) end)
  18195. (cond
  18196. ((org-at-heading-p)
  18197. (insert ": ")
  18198. (forward-line)
  18199. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  18200. (insert ":")
  18201. (forward-line)))
  18202. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  18203. (let* ((element (org-element-at-point))
  18204. (element-end (org-element-property :end element)))
  18205. (if (eq (org-element-type element) 'fixed-width)
  18206. (progn (goto-char element-end)
  18207. (skip-chars-backward " \r\t\n")
  18208. (forward-line))
  18209. (let ((limit (min end element-end)))
  18210. (while (< (point) limit)
  18211. (org-move-to-column min-ind t)
  18212. (insert ": ")
  18213. (forward-line))))))
  18214. (t
  18215. (org-move-to-column min-ind t)
  18216. (insert ": ")
  18217. (forward-line)))))))
  18218. (set-marker end nil))))
  18219. ;;; Blocks
  18220. (defun org-block-map (function &optional start end)
  18221. "Call FUNCTION at the head of all source blocks in the current buffer.
  18222. Optional arguments START and END can be used to limit the range."
  18223. (let ((start (or start (point-min)))
  18224. (end (or end (point-max))))
  18225. (save-excursion
  18226. (goto-char start)
  18227. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  18228. (save-excursion
  18229. (save-match-data
  18230. (goto-char (match-beginning 0))
  18231. (funcall function)))))))
  18232. (defun org-next-block (arg &optional backward block-regexp)
  18233. "Jump to the next block.
  18234. With a prefix argument ARG, jump forward ARG many blocks.
  18235. When BACKWARD is non-nil, jump to the previous block.
  18236. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  18237. Match data is set according to this regexp when the function
  18238. returns.
  18239. Return point at beginning of the opening line of found block.
  18240. Throw an error if no block is found."
  18241. (interactive "p")
  18242. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  18243. (case-fold-search t)
  18244. (search-fn (if backward #'re-search-backward #'re-search-forward))
  18245. (count (or arg 1))
  18246. (origin (point))
  18247. last-element)
  18248. (if backward (beginning-of-line) (end-of-line))
  18249. (while (and (> count 0) (funcall search-fn re nil t))
  18250. (let ((element (save-excursion
  18251. (goto-char (match-beginning 0))
  18252. (save-match-data (org-element-at-point)))))
  18253. (when (and (memq (org-element-type element)
  18254. '(center-block comment-block dynamic-block
  18255. example-block export-block quote-block
  18256. special-block src-block verse-block))
  18257. (<= (match-beginning 0)
  18258. (org-element-property :post-affiliated element)))
  18259. (setq last-element element)
  18260. (cl-decf count))))
  18261. (if (= count 0)
  18262. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  18263. (save-match-data (org-show-context)))
  18264. (goto-char origin)
  18265. (user-error "No %s code blocks" (if backward "previous" "further")))))
  18266. (defun org-previous-block (arg &optional block-regexp)
  18267. "Jump to the previous block.
  18268. With a prefix argument ARG, jump backward ARG many source blocks.
  18269. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  18270. (interactive "p")
  18271. (org-next-block arg t block-regexp))
  18272. ;;; Comments
  18273. ;; Org comments syntax is quite complex. It requires the entire line
  18274. ;; to be just a comment. Also, even with the right syntax at the
  18275. ;; beginning of line, some elements (e.g., verse-block or
  18276. ;; example-block) don't accept comments. Usual Emacs comment commands
  18277. ;; cannot cope with those requirements. Therefore, Org replaces them.
  18278. ;; Org still relies on `comment-dwim', but cannot trust
  18279. ;; `comment-only-p'. So, `comment-region-function' and
  18280. ;; `uncomment-region-function' both point
  18281. ;; to`org-comment-or-uncomment-region'. Eventually,
  18282. ;; `org-insert-comment' takes care of insertion of comments at the
  18283. ;; beginning of line.
  18284. ;; `org-setup-comments-handling' install comments related variables
  18285. ;; during `org-mode' initialization.
  18286. (defun org-setup-comments-handling ()
  18287. (interactive)
  18288. (setq-local comment-use-syntax nil)
  18289. (setq-local comment-start "# ")
  18290. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  18291. (setq-local comment-insert-comment-function 'org-insert-comment)
  18292. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  18293. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  18294. (defun org-insert-comment ()
  18295. "Insert an empty comment above current line.
  18296. If the line is empty, insert comment at its beginning. When
  18297. point is within a source block, comment according to the related
  18298. major mode."
  18299. (if (let ((element (org-element-at-point)))
  18300. (and (eq (org-element-type element) 'src-block)
  18301. (< (save-excursion
  18302. (goto-char (org-element-property :post-affiliated element))
  18303. (line-end-position))
  18304. (point))
  18305. (> (save-excursion
  18306. (goto-char (org-element-property :end element))
  18307. (skip-chars-backward " \r\t\n")
  18308. (line-beginning-position))
  18309. (point))))
  18310. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  18311. (beginning-of-line)
  18312. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  18313. (open-line 1))
  18314. (org-indent-line)
  18315. (insert "# ")))
  18316. (defvar comment-empty-lines) ; From newcomment.el.
  18317. (defun org-comment-or-uncomment-region (beg end &rest _)
  18318. "Comment or uncomment each non-blank line in the region.
  18319. Uncomment each non-blank line between BEG and END if it only
  18320. contains commented lines. Otherwise, comment them. If region is
  18321. strictly within a source block, use appropriate comment syntax."
  18322. (if (let ((element (org-element-at-point)))
  18323. (and (eq (org-element-type element) 'src-block)
  18324. (< (save-excursion
  18325. (goto-char (org-element-property :post-affiliated element))
  18326. (line-end-position))
  18327. beg)
  18328. (>= (save-excursion
  18329. (goto-char (org-element-property :end element))
  18330. (skip-chars-backward " \r\t\n")
  18331. (line-beginning-position))
  18332. end)))
  18333. ;; Translate region boundaries for the Org buffer to the source
  18334. ;; buffer.
  18335. (let ((offset (- end beg)))
  18336. (save-excursion
  18337. (goto-char beg)
  18338. (org-babel-do-in-edit-buffer
  18339. (comment-or-uncomment-region (point) (+ offset (point))))))
  18340. (save-restriction
  18341. ;; Restrict region
  18342. (narrow-to-region (save-excursion (goto-char beg)
  18343. (skip-chars-forward " \r\t\n" end)
  18344. (line-beginning-position))
  18345. (save-excursion (goto-char end)
  18346. (skip-chars-backward " \r\t\n" beg)
  18347. (line-end-position)))
  18348. (let ((uncommentp
  18349. ;; UNCOMMENTP is non-nil when every non blank line between
  18350. ;; BEG and END is a comment.
  18351. (save-excursion
  18352. (goto-char (point-min))
  18353. (while (and (not (eobp))
  18354. (let ((element (org-element-at-point)))
  18355. (and (eq (org-element-type element) 'comment)
  18356. (goto-char (min (point-max)
  18357. (org-element-property
  18358. :end element)))))))
  18359. (eobp))))
  18360. (if uncommentp
  18361. ;; Only blank lines and comments in region: uncomment it.
  18362. (save-excursion
  18363. (goto-char (point-min))
  18364. (while (not (eobp))
  18365. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  18366. (replace-match "" nil nil nil 1))
  18367. (forward-line)))
  18368. ;; Comment each line in region.
  18369. (let ((min-indent (point-max)))
  18370. ;; First find the minimum indentation across all lines.
  18371. (save-excursion
  18372. (goto-char (point-min))
  18373. (while (and (not (eobp)) (not (zerop min-indent)))
  18374. (unless (looking-at "[ \t]*$")
  18375. (setq min-indent (min min-indent (current-indentation))))
  18376. (forward-line)))
  18377. ;; Then loop over all lines.
  18378. (save-excursion
  18379. (goto-char (point-min))
  18380. (while (not (eobp))
  18381. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18382. ;; Don't get fooled by invisible text (e.g. link path)
  18383. ;; when moving to column MIN-INDENT.
  18384. (let ((buffer-invisibility-spec nil))
  18385. (org-move-to-column min-indent t))
  18386. (insert comment-start))
  18387. (forward-line)))))))))
  18388. (defun org-comment-dwim (_arg)
  18389. "Call the comment command you mean.
  18390. Call `org-toggle-comment' if on a heading, otherwise call
  18391. `comment-dwim', within a source edit buffer if needed."
  18392. (interactive "*P")
  18393. (cond ((org-at-heading-p)
  18394. (call-interactively #'org-toggle-comment))
  18395. ((org-in-src-block-p)
  18396. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18397. (t (call-interactively #'comment-dwim))))
  18398. ;;; Timestamps API
  18399. ;; This section contains tools to operate on, or create, timestamp
  18400. ;; objects, as returned by, e.g. `org-element-context'.
  18401. (defun org-timestamp-from-string (s)
  18402. "Convert Org timestamp S, as a string, into a timestamp object.
  18403. Return nil if S is not a valid timestamp string."
  18404. (when (org-string-nw-p s)
  18405. (with-temp-buffer
  18406. (save-excursion (insert s))
  18407. (org-element-timestamp-parser))))
  18408. (defun org-timestamp-from-time (time &optional with-time inactive)
  18409. "Convert a time value into a timestamp object.
  18410. TIME is an Emacs internal time representation, as returned, e.g.,
  18411. by `current-time'.
  18412. When optional argument WITH-TIME is non-nil, return a timestamp
  18413. object with a time part, i.e., with hours and minutes.
  18414. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18415. return an active timestamp."
  18416. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18417. (org-element-create 'timestamp
  18418. (list :type (if inactive 'inactive 'active)
  18419. :year-start year
  18420. :month-start month
  18421. :day-start day
  18422. :hour-start (and with-time hour)
  18423. :minute-start (and with-time minute)))))
  18424. (defun org-timestamp-to-time (timestamp &optional end)
  18425. "Convert TIMESTAMP object into an Emacs internal time value.
  18426. Use end of date range or time range when END is non-nil.
  18427. Otherwise, use its start."
  18428. (apply #'encode-time 0
  18429. (mapcar
  18430. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18431. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18432. '(:minute-start :hour-start :day-start :month-start
  18433. :year-start)))))
  18434. (defun org-timestamp-has-time-p (timestamp)
  18435. "Non-nil when TIMESTAMP has a time specified."
  18436. (org-element-property :hour-start timestamp))
  18437. (defun org-timestamp-format (timestamp format &optional end utc)
  18438. "Format a TIMESTAMP object into a string.
  18439. FORMAT is a format specifier to be passed to
  18440. `format-time-string'.
  18441. When optional argument END is non-nil, use end of date-range or
  18442. time-range, if possible.
  18443. When optional argument UTC is non-nil, time is be expressed as
  18444. Universal Time."
  18445. (format-time-string format (org-timestamp-to-time timestamp end)
  18446. (and utc t)))
  18447. (defun org-timestamp-split-range (timestamp &optional end)
  18448. "Extract a TIMESTAMP object from a date or time range.
  18449. END, when non-nil, means extract the end of the range.
  18450. Otherwise, extract its start.
  18451. Return a new timestamp object."
  18452. (let ((type (org-element-property :type timestamp)))
  18453. (if (memq type '(active inactive diary)) timestamp
  18454. (let ((split-ts (org-element-copy timestamp)))
  18455. ;; Set new type.
  18456. (org-element-put-property
  18457. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18458. ;; Copy start properties over end properties if END is
  18459. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18460. (let ((p-alist '((:minute-start . :minute-end)
  18461. (:hour-start . :hour-end)
  18462. (:day-start . :day-end)
  18463. (:month-start . :month-end)
  18464. (:year-start . :year-end))))
  18465. (dolist (p-cell p-alist)
  18466. (org-element-put-property
  18467. split-ts
  18468. (funcall (if end #'car #'cdr) p-cell)
  18469. (org-element-property
  18470. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18471. ;; Eventually refresh `:raw-value'.
  18472. (org-element-put-property split-ts :raw-value nil)
  18473. (org-element-put-property
  18474. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18475. (defun org-timestamp-translate (timestamp &optional boundary)
  18476. "Translate TIMESTAMP object to custom format.
  18477. Format string is defined in `org-time-stamp-custom-formats',
  18478. which see.
  18479. When optional argument BOUNDARY is non-nil, it is either the
  18480. symbol `start' or `end'. In this case, only translate the
  18481. starting or ending part of TIMESTAMP if it is a date or time
  18482. range. Otherwise, translate both parts.
  18483. Return timestamp as-is if `org-display-custom-times' is nil or if
  18484. it has a `diary' type."
  18485. (let ((type (org-element-property :type timestamp)))
  18486. (if (or (not org-display-custom-times) (eq type 'diary))
  18487. (org-element-interpret-data timestamp)
  18488. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18489. org-time-stamp-custom-formats)))
  18490. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18491. (concat (org-timestamp-format timestamp fmt)
  18492. "--"
  18493. (org-timestamp-format timestamp fmt t))
  18494. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18495. ;;; Other stuff
  18496. (defvar reftex-docstruct-symbol)
  18497. (defvar org--rds)
  18498. (defun org-reftex-citation ()
  18499. "Use reftex-citation to insert a citation into the buffer.
  18500. This looks for a line like
  18501. #+BIBLIOGRAPHY: foo plain option:-d
  18502. and derives from it that foo.bib is the bibliography file relevant
  18503. for this document. It then installs the necessary environment for RefTeX
  18504. to work in this buffer and calls `reftex-citation' to insert a citation
  18505. into the buffer.
  18506. Export of such citations to both LaTeX and HTML is handled by the contributed
  18507. package ox-bibtex by Taru Karttunen."
  18508. (interactive)
  18509. (let ((reftex-docstruct-symbol 'org--rds)
  18510. org--rds bib)
  18511. (org-with-wide-buffer
  18512. (let ((case-fold-search t)
  18513. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18514. (if (not (save-excursion
  18515. (or (re-search-forward re nil t)
  18516. (re-search-backward re nil t))))
  18517. (user-error "No bibliography defined in file")
  18518. (setq bib (concat (match-string 1) ".bib")
  18519. org--rds (list (list 'bib bib))))))
  18520. (call-interactively 'reftex-citation)))
  18521. ;;;; Functions extending outline functionality
  18522. (defun org-beginning-of-line (&optional n)
  18523. "Go to the beginning of the current visible line.
  18524. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18525. symbol `reversed', on the first attempt move to where the
  18526. headline text starts, and only move to beginning of line when the
  18527. cursor is already before the start of the text of the headline.
  18528. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18529. start of the text on the second attempt.
  18530. With argument N not nil or 1, move forward N - 1 lines first."
  18531. (interactive "^p")
  18532. (let ((origin (point))
  18533. (special (pcase org-special-ctrl-a/e
  18534. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18535. deactivate-mark)
  18536. ;; First move to a visible line.
  18537. (if (bound-and-true-p visual-line-mode)
  18538. (beginning-of-visual-line n)
  18539. (move-beginning-of-line n)
  18540. ;; `move-beginning-of-line' may leave point after invisible
  18541. ;; characters if line starts with such of these (e.g., with
  18542. ;; a link at column 0). Really move to the beginning of the
  18543. ;; current visible line.
  18544. (beginning-of-line))
  18545. (cond
  18546. ;; No special behavior. Point is already at the beginning of
  18547. ;; a line, logical or visual.
  18548. ((not special))
  18549. ;; `beginning-of-visual-line' left point before logical beginning
  18550. ;; of line: point is at the beginning of a visual line. Bail
  18551. ;; out.
  18552. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18553. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18554. ;; At a headline, special position is before the title, but
  18555. ;; after any TODO keyword or priority cookie.
  18556. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18557. (line-end-position)))
  18558. (bol (point)))
  18559. (if (eq special 'reversed)
  18560. (when (and (= origin bol) (eq last-command this-command))
  18561. (goto-char refpos))
  18562. (when (or (> origin refpos) (= origin bol))
  18563. (goto-char refpos)))))
  18564. ((and (looking-at org-list-full-item-re)
  18565. (memq (org-element-type (save-match-data (org-element-at-point)))
  18566. '(item plain-list)))
  18567. ;; Set special position at first white space character after
  18568. ;; bullet, and check-box, if any.
  18569. (let ((after-bullet
  18570. (let ((box (match-end 3)))
  18571. (cond ((not box) (match-end 1))
  18572. ((eq (char-after box) ?\s) (1+ box))
  18573. (t box)))))
  18574. (if (eq special 'reversed)
  18575. (when (and (= (point) origin) (eq last-command this-command))
  18576. (goto-char after-bullet))
  18577. (when (or (> origin after-bullet) (= (point) origin))
  18578. (goto-char after-bullet)))))
  18579. ;; No special context. Point is already at beginning of line.
  18580. (t nil))))
  18581. (defun org-end-of-line (&optional n)
  18582. "Go to the end of the line, but before ellipsis, if any.
  18583. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18584. symbol `reversed', ignore tags on the first attempt, and only
  18585. move to after the tags when the cursor is already beyond the end
  18586. of the headline.
  18587. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18588. on the second attempt.
  18589. With argument N not nil or 1, move forward N - 1 lines first."
  18590. (interactive "^p")
  18591. (let ((origin (point))
  18592. (special (pcase org-special-ctrl-a/e
  18593. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18594. deactivate-mark)
  18595. ;; First move to a visible line.
  18596. (if (bound-and-true-p visual-line-mode)
  18597. (beginning-of-visual-line n)
  18598. (move-beginning-of-line n))
  18599. (cond
  18600. ;; At a headline, with tags.
  18601. ((and special
  18602. (save-excursion
  18603. (beginning-of-line)
  18604. (let ((case-fold-search nil))
  18605. (looking-at org-complex-heading-regexp)))
  18606. (match-end 5))
  18607. (let ((tags (save-excursion
  18608. (goto-char (match-beginning 5))
  18609. (skip-chars-backward " \t")
  18610. (point)))
  18611. (visual-end (and (bound-and-true-p visual-line-mode)
  18612. (save-excursion
  18613. (end-of-visual-line)
  18614. (point)))))
  18615. ;; If `end-of-visual-line' brings us before end of line or
  18616. ;; even tags, i.e., the headline spans over multiple visual
  18617. ;; lines, move there.
  18618. (cond ((and visual-end
  18619. (< visual-end tags)
  18620. (<= origin visual-end))
  18621. (goto-char visual-end))
  18622. ((eq special 'reversed)
  18623. (if (and (= origin (line-end-position))
  18624. (eq this-command last-command))
  18625. (goto-char tags)
  18626. (end-of-line)))
  18627. (t
  18628. (if (or (< origin tags) (= origin (line-end-position)))
  18629. (goto-char tags)
  18630. (end-of-line))))))
  18631. ((bound-and-true-p visual-line-mode)
  18632. (let ((bol (line-beginning-position)))
  18633. (end-of-visual-line)
  18634. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18635. ;; end of a line, backtrack and use `end-of-line' instead.
  18636. (when (/= bol (line-beginning-position))
  18637. (goto-char bol)
  18638. (end-of-line))))
  18639. (t (end-of-line)))))
  18640. (defun org-backward-sentence (&optional _arg)
  18641. "Go to beginning of sentence, or beginning of table field.
  18642. This will call `backward-sentence' or `org-table-beginning-of-field',
  18643. depending on context."
  18644. (interactive)
  18645. (let* ((element (org-element-at-point))
  18646. (contents-begin (org-element-property :contents-begin element))
  18647. (table (org-element-lineage element '(table) t)))
  18648. (if (and table
  18649. (> (point) contents-begin)
  18650. (<= (point) (org-element-property :contents-end table)))
  18651. (call-interactively #'org-table-beginning-of-field)
  18652. (save-restriction
  18653. (when (and contents-begin
  18654. (< (point-min) contents-begin)
  18655. (> (point) contents-begin))
  18656. (narrow-to-region contents-begin
  18657. (org-element-property :contents-end element)))
  18658. (call-interactively #'backward-sentence)))))
  18659. (defun org-forward-sentence (&optional _arg)
  18660. "Go to end of sentence, or end of table field.
  18661. This will call `forward-sentence' or `org-table-end-of-field',
  18662. depending on context."
  18663. (interactive)
  18664. (if (and (org-at-heading-p)
  18665. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18666. (save-restriction
  18667. (narrow-to-region (line-beginning-position) (line-end-position))
  18668. (call-interactively #'forward-sentence))
  18669. (let* ((element (org-element-at-point))
  18670. (contents-end (org-element-property :contents-end element))
  18671. (table (org-element-lineage element '(table) t)))
  18672. (if (and table
  18673. (>= (point) (org-element-property :contents-begin table))
  18674. (< (point) contents-end))
  18675. (call-interactively #'org-table-end-of-field)
  18676. (save-restriction
  18677. (when (and contents-end
  18678. (> (point-max) contents-end)
  18679. ;; Skip blank lines between elements.
  18680. (< (org-element-property :end element)
  18681. (save-excursion (goto-char contents-end)
  18682. (skip-chars-forward " \r\t\n"))))
  18683. (narrow-to-region (org-element-property :contents-begin element)
  18684. contents-end))
  18685. ;; End of heading is considered as the end of a sentence.
  18686. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18687. (call-interactively #'forward-sentence)))))))
  18688. (defun org-kill-line (&optional _arg)
  18689. "Kill line, to tags or end of line."
  18690. (interactive)
  18691. (cond
  18692. ((or (not org-special-ctrl-k)
  18693. (bolp)
  18694. (not (org-at-heading-p)))
  18695. (when (and (get-char-property (line-end-position) 'invisible)
  18696. org-ctrl-k-protect-subtree
  18697. (or (eq org-ctrl-k-protect-subtree 'error)
  18698. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18699. (user-error
  18700. (substitute-command-keys
  18701. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18702. (call-interactively
  18703. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18704. ((org-match-line org-tag-line-re)
  18705. (let ((end (save-excursion
  18706. (goto-char (match-beginning 1))
  18707. (skip-chars-backward " \t")
  18708. (point))))
  18709. (if (<= end (point)) ;on tags part
  18710. (kill-region (point) (line-end-position))
  18711. (kill-region (point) end)))
  18712. (org-align-tags))
  18713. (t (kill-region (point) (line-end-position)))))
  18714. (defun org-yank (&optional arg)
  18715. "Yank. If the kill is a subtree, treat it specially.
  18716. This command will look at the current kill and check if is a single
  18717. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18718. cursor is at the beginning of a line or after the stars of a currently
  18719. empty headline, then the yank is handled specially. How exactly depends
  18720. on the value of the following variables.
  18721. `org-yank-folded-subtrees'
  18722. By default, this variable is non-nil, which results in
  18723. subtree(s) being folded after insertion, except if doing so
  18724. would swallow text after the yanked text.
  18725. `org-yank-adjusted-subtrees'
  18726. When non-nil (the default value is nil), the subtree will be
  18727. promoted or demoted in order to fit into the local outline tree
  18728. structure, which means that the level will be adjusted so that it
  18729. becomes the smaller one of the two *visible* surrounding headings.
  18730. Any prefix to this command will cause `yank' to be called directly with
  18731. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18732. will just
  18733. plainly yank the text as it is.
  18734. \[1] The test checks if the first non-white line is a heading
  18735. and if there are no other headings with fewer stars."
  18736. (interactive "P")
  18737. (org-yank-generic 'yank arg))
  18738. (defun org-yank-generic (command arg)
  18739. "Perform some yank-like command.
  18740. This function implements the behavior described in the `org-yank'
  18741. documentation. However, it has been generalized to work for any
  18742. interactive command with similar behavior."
  18743. ;; pretend to be command COMMAND
  18744. (setq this-command command)
  18745. (if arg
  18746. (call-interactively command)
  18747. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18748. (and (org-kill-is-subtree-p)
  18749. (or (bolp)
  18750. (and (looking-at "[ \t]*$")
  18751. (string-match
  18752. "\\`\\*+\\'"
  18753. (buffer-substring (point-at-bol) (point)))))))
  18754. swallowp)
  18755. (cond
  18756. ((and subtreep org-yank-folded-subtrees)
  18757. (let ((beg (point))
  18758. end)
  18759. (if (and subtreep org-yank-adjusted-subtrees)
  18760. (org-paste-subtree nil nil 'for-yank)
  18761. (call-interactively command))
  18762. (setq end (point))
  18763. (goto-char beg)
  18764. (when (and (bolp) subtreep
  18765. (not (setq swallowp
  18766. (org-yank-folding-would-swallow-text beg end))))
  18767. (org-with-limited-levels
  18768. (or (looking-at org-outline-regexp)
  18769. (re-search-forward org-outline-regexp-bol end t))
  18770. (while (and (< (point) end) (looking-at org-outline-regexp))
  18771. (org-flag-subtree t)
  18772. (org-cycle-show-empty-lines 'folded)
  18773. (condition-case nil
  18774. (outline-forward-same-level 1)
  18775. (error (goto-char end))))))
  18776. (when swallowp
  18777. (message
  18778. "Inserted text not folded because that would swallow text"))
  18779. (goto-char end)
  18780. (skip-chars-forward " \t\n\r")
  18781. (beginning-of-line 1)
  18782. (push-mark beg 'nomsg)))
  18783. ((and subtreep org-yank-adjusted-subtrees)
  18784. (let ((beg (point-at-bol)))
  18785. (org-paste-subtree nil nil 'for-yank)
  18786. (push-mark beg 'nomsg)))
  18787. (t
  18788. (call-interactively command))))))
  18789. (defun org-yank-folding-would-swallow-text (beg end)
  18790. "Would hide-subtree at BEG swallow any text after END?"
  18791. (let (level)
  18792. (org-with-limited-levels
  18793. (save-excursion
  18794. (goto-char beg)
  18795. (when (or (looking-at org-outline-regexp)
  18796. (re-search-forward org-outline-regexp-bol end t))
  18797. (setq level (org-outline-level)))
  18798. (goto-char end)
  18799. (skip-chars-forward " \t\r\n\v\f")
  18800. (not (or (eobp)
  18801. (and (bolp) (looking-at-p org-outline-regexp)
  18802. (<= (org-outline-level) level))))))))
  18803. (defun org-back-to-heading (&optional invisible-ok)
  18804. "Call `outline-back-to-heading', but provide a better error message."
  18805. (condition-case nil
  18806. (outline-back-to-heading invisible-ok)
  18807. (error
  18808. (user-error "Before first headline at position %d in buffer %s"
  18809. (point) (current-buffer)))))
  18810. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18811. "Go back to heading or first point in buffer.
  18812. If point is before first heading go to first point in buffer
  18813. instead of back to heading."
  18814. (condition-case nil
  18815. (outline-back-to-heading invisible-ok)
  18816. (error
  18817. (goto-char (point-min)))))
  18818. (defun org-before-first-heading-p ()
  18819. "Before first heading?"
  18820. (org-with-limited-levels
  18821. (save-excursion
  18822. (end-of-line)
  18823. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18824. (defun org-at-heading-p (&optional _)
  18825. "Non-nil when on a headline."
  18826. (outline-on-heading-p t))
  18827. (defun org-in-commented-heading-p (&optional no-inheritance)
  18828. "Non-nil if point is under a commented heading.
  18829. This function also checks ancestors of the current headline,
  18830. unless optional argument NO-INHERITANCE is non-nil."
  18831. (cond
  18832. ((org-before-first-heading-p) nil)
  18833. ((let ((headline (nth 4 (org-heading-components))))
  18834. (and headline
  18835. (let ((case-fold-search nil))
  18836. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18837. headline)))))
  18838. (no-inheritance nil)
  18839. (t
  18840. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18841. (defun org-at-comment-p nil
  18842. "Return t if cursor is in a commented line."
  18843. (save-excursion
  18844. (save-match-data
  18845. (beginning-of-line)
  18846. (looking-at "^[ \t]*# "))))
  18847. (defun org-at-keyword-p nil
  18848. "Return t if cursor is at a keyword-line."
  18849. (save-excursion
  18850. (move-beginning-of-line 1)
  18851. (looking-at org-keyword-regexp)))
  18852. (defun org-at-drawer-p nil
  18853. "Return t if cursor is at a drawer keyword."
  18854. (save-excursion
  18855. (move-beginning-of-line 1)
  18856. (looking-at org-drawer-regexp)))
  18857. (defun org-at-block-p nil
  18858. "Return t if cursor is at a block keyword."
  18859. (save-excursion
  18860. (move-beginning-of-line 1)
  18861. (looking-at org-block-regexp)))
  18862. (defun org-point-at-end-of-empty-headline ()
  18863. "If point is at the end of an empty headline, return t, else nil.
  18864. If the heading only contains a TODO keyword, it is still still considered
  18865. empty."
  18866. (let ((case-fold-search nil))
  18867. (and (looking-at "[ \t]*$")
  18868. org-todo-line-regexp
  18869. (save-excursion
  18870. (beginning-of-line)
  18871. (looking-at org-todo-line-regexp)
  18872. (string= (match-string 3) "")))))
  18873. (defun org-at-heading-or-item-p ()
  18874. (or (org-at-heading-p) (org-at-item-p)))
  18875. (defun org-up-heading-all (arg)
  18876. "Move to the heading line of which the present line is a subheading.
  18877. This function considers both visible and invisible heading lines.
  18878. With argument, move up ARG levels."
  18879. (outline-up-heading arg t))
  18880. (defun org-up-heading-safe ()
  18881. "Move to the heading line of which the present line is a subheading.
  18882. This version will not throw an error. It will return the level of the
  18883. headline found, or nil if no higher level is found.
  18884. Also, this function will be a lot faster than `outline-up-heading',
  18885. because it relies on stars being the outline starters. This can really
  18886. make a significant difference in outlines with very many siblings."
  18887. (when (ignore-errors (org-back-to-heading t))
  18888. (let ((level-up (1- (funcall outline-level))))
  18889. (and (> level-up 0)
  18890. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  18891. (funcall outline-level)))))
  18892. (defun org-up-heading-or-point-min ()
  18893. "Move to the heading line of which the present is a subheading, or point-min.
  18894. This version is needed to make point-min behave like a virtual
  18895. heading of level 0 for property-inheritance. It will return the
  18896. level of the headline found (down to 0) or nil if already at a
  18897. point before the first headline or at point-min."
  18898. (when (ignore-errors (org-back-to-heading t))
  18899. (if (< 1 (funcall outline-level))
  18900. (org-up-heading-safe)
  18901. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18902. (defun org-first-sibling-p ()
  18903. "Is this heading the first child of its parents?"
  18904. (interactive)
  18905. (let ((re org-outline-regexp-bol)
  18906. level l)
  18907. (unless (org-at-heading-p t)
  18908. (user-error "Not at a heading"))
  18909. (setq level (funcall outline-level))
  18910. (save-excursion
  18911. (if (not (re-search-backward re nil t))
  18912. t
  18913. (setq l (funcall outline-level))
  18914. (< l level)))))
  18915. (defun org-goto-sibling (&optional previous)
  18916. "Goto the next sibling, even if it is invisible.
  18917. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18918. when a sibling was found. When none is found, return nil and don't
  18919. move point."
  18920. (let ((fun (if previous 're-search-backward 're-search-forward))
  18921. (pos (point))
  18922. (re org-outline-regexp-bol)
  18923. level l)
  18924. (when (ignore-errors (org-back-to-heading t))
  18925. (setq level (funcall outline-level))
  18926. (catch 'exit
  18927. (or previous (forward-char 1))
  18928. (while (funcall fun re nil t)
  18929. (setq l (funcall outline-level))
  18930. (when (< l level) (goto-char pos) (throw 'exit nil))
  18931. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18932. (goto-char pos)
  18933. nil))))
  18934. (defun org-show-siblings ()
  18935. "Show all siblings of the current headline."
  18936. (save-excursion
  18937. (while (org-goto-sibling) (org-flag-heading nil)))
  18938. (save-excursion
  18939. (while (org-goto-sibling 'previous)
  18940. (org-flag-heading nil))))
  18941. (defun org-goto-first-child ()
  18942. "Goto the first child, even if it is invisible.
  18943. Return t when a child was found. Otherwise don't move point and
  18944. return nil."
  18945. (let (level (pos (point)) (re org-outline-regexp-bol))
  18946. (when (ignore-errors (org-back-to-heading t))
  18947. (setq level (outline-level))
  18948. (forward-char 1)
  18949. (if (and (re-search-forward re nil t) (> (outline-level) level))
  18950. (progn (goto-char (match-beginning 0)) t)
  18951. (goto-char pos) nil))))
  18952. (defun org-show-hidden-entry ()
  18953. "Show an entry where even the heading is hidden."
  18954. (save-excursion
  18955. (org-show-entry)))
  18956. (defun org-flag-heading (flag &optional entry)
  18957. "Flag the current heading. FLAG non-nil means make invisible.
  18958. When ENTRY is non-nil, show the entire entry."
  18959. (save-excursion
  18960. (org-back-to-heading t)
  18961. ;; Check if we should show the entire entry
  18962. (if (not entry)
  18963. (org-flag-region
  18964. (line-end-position 0) (line-end-position) flag 'outline)
  18965. (org-show-entry)
  18966. (save-excursion
  18967. (and (outline-next-heading)
  18968. (org-flag-heading nil))))))
  18969. (defun org-get-next-sibling ()
  18970. "Move to next heading of the same level, and return point.
  18971. If there is no such heading, return nil.
  18972. This is like outline-next-sibling, but invisible headings are ok."
  18973. (let ((level (funcall outline-level)))
  18974. (outline-next-heading)
  18975. (while (and (not (eobp)) (> (funcall outline-level) level))
  18976. (outline-next-heading))
  18977. (unless (or (eobp) (< (funcall outline-level) level))
  18978. (point))))
  18979. (defun org-get-last-sibling ()
  18980. "Move to previous heading of the same level, and return point.
  18981. If there is no such heading, return nil."
  18982. (let ((opoint (point))
  18983. (level (funcall outline-level)))
  18984. (outline-previous-heading)
  18985. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18986. (while (and (> (funcall outline-level) level)
  18987. (not (bobp)))
  18988. (outline-previous-heading))
  18989. (unless (< (funcall outline-level) level)
  18990. (point)))))
  18991. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18992. "Goto to the end of a subtree."
  18993. ;; This contains an exact copy of the original function, but it uses
  18994. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18995. ;; trees and before first headline. And is uses an invisible-ok argument.
  18996. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18997. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18998. ;; with many children and grandchildren etc, this can be much faster
  18999. ;; than the outline version.
  19000. (org-back-to-heading-or-point-min invisible-ok)
  19001. (let ((first t)
  19002. (level (funcall outline-level)))
  19003. (cond ((= level 0)
  19004. (goto-char (point-max)))
  19005. ((and (derived-mode-p 'org-mode) (< level 1000))
  19006. ;; A true heading (not a plain list item), in Org
  19007. ;; This means we can easily find the end by looking
  19008. ;; only for the right number of stars. Using a regexp to do
  19009. ;; this is so much faster than using a Lisp loop.
  19010. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  19011. (forward-char 1)
  19012. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  19013. (t
  19014. ;; something else, do it the slow way
  19015. (while (and (not (eobp))
  19016. (or first (> (funcall outline-level) level)))
  19017. (setq first nil)
  19018. (outline-next-heading))))
  19019. (unless to-heading
  19020. (when (memq (preceding-char) '(?\n ?\^M))
  19021. ;; Go to end of line before heading
  19022. (forward-char -1)
  19023. (when (memq (preceding-char) '(?\n ?\^M))
  19024. ;; leave blank line before heading
  19025. (forward-char -1)))))
  19026. (point))
  19027. (defun org-end-of-meta-data (&optional full)
  19028. "Skip planning line and properties drawer in current entry.
  19029. When optional argument FULL is non-nil, also skip empty lines,
  19030. clocking lines and regular drawers at the beginning of the
  19031. entry."
  19032. (org-back-to-heading t)
  19033. (forward-line)
  19034. (when (looking-at-p org-planning-line-re) (forward-line))
  19035. (when (looking-at org-property-drawer-re)
  19036. (goto-char (match-end 0))
  19037. (forward-line))
  19038. (when (and full (not (org-at-heading-p)))
  19039. (catch 'exit
  19040. (let ((end (save-excursion (outline-next-heading) (point)))
  19041. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  19042. (while (not (eobp))
  19043. (cond ((looking-at-p org-drawer-regexp)
  19044. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  19045. (forward-line)
  19046. (throw 'exit t)))
  19047. ((looking-at-p re) (forward-line))
  19048. (t (throw 'exit t))))))))
  19049. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  19050. "Move forward to the ARG'th subheading at same level as this one.
  19051. Stop at the first and last subheadings of a superior heading.
  19052. Normally this only looks at visible headings, but when INVISIBLE-OK is
  19053. non-nil it will also look at invisible ones."
  19054. (interactive "p")
  19055. (let ((backward? (and arg (< arg 0))))
  19056. (if (org-before-first-heading-p)
  19057. (if backward? (goto-char (point-min)) (outline-next-heading))
  19058. (org-back-to-heading invisible-ok)
  19059. (unless backward? (end-of-line)) ;do not match current headline
  19060. (let ((level (- (match-end 0) (match-beginning 0) 1))
  19061. (f (if backward? #'re-search-backward #'re-search-forward))
  19062. (count (if arg (abs arg) 1))
  19063. (result (point)))
  19064. (while (and (> count 0)
  19065. (funcall f org-outline-regexp-bol nil 'move))
  19066. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  19067. (cond ((< l level) (setq count 0))
  19068. ((and (= l level)
  19069. (or invisible-ok
  19070. (not (org-invisible-p
  19071. (line-beginning-position)))))
  19072. (cl-decf count)
  19073. (when (= l level) (setq result (point)))))))
  19074. (goto-char result))
  19075. (beginning-of-line))))
  19076. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  19077. "Move backward to the ARG'th subheading at same level as this one.
  19078. Stop at the first and last subheadings of a superior heading."
  19079. (interactive "p")
  19080. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  19081. (defun org-next-visible-heading (arg)
  19082. "Move to the next visible heading.
  19083. This function wraps `outline-next-visible-heading' with
  19084. `org-with-limited-levels' in order to skip over inline tasks and
  19085. respect customization of `org-odd-levels-only'."
  19086. (interactive "p")
  19087. (org-with-limited-levels
  19088. (outline-next-visible-heading arg)))
  19089. (defun org-previous-visible-heading (arg)
  19090. "Move to the previous visible heading.
  19091. This function wraps `outline-previous-visible-heading' with
  19092. `org-with-limited-levels' in order to skip over inline tasks and
  19093. respect customization of `org-odd-levels-only'."
  19094. (interactive "p")
  19095. (org-with-limited-levels
  19096. (outline-previous-visible-heading arg)))
  19097. (defun org-forward-paragraph ()
  19098. "Move forward to beginning of next paragraph or equivalent.
  19099. The function moves point to the beginning of the next visible
  19100. structural element, which can be a paragraph, a table, a list
  19101. item, etc. It also provides some special moves for convenience:
  19102. - On an affiliated keyword, jump to the beginning of the
  19103. relative element.
  19104. - On an item or a footnote definition, move to the second
  19105. element inside, if any.
  19106. - On a table or a property drawer, jump after it.
  19107. - On a verse or source block, stop after blank lines."
  19108. (interactive)
  19109. (unless (eobp)
  19110. (let* ((deactivate-mark nil)
  19111. (element (org-element-at-point))
  19112. (type (org-element-type element))
  19113. (post-affiliated (org-element-property :post-affiliated element))
  19114. (contents-begin (org-element-property :contents-begin element))
  19115. (contents-end (org-element-property :contents-end element))
  19116. (end (let ((end (org-element-property :end element)) (parent element))
  19117. (while (and (setq parent (org-element-property :parent parent))
  19118. (= (org-element-property :contents-end parent) end))
  19119. (setq end (org-element-property :end parent)))
  19120. end)))
  19121. (cond ((not element)
  19122. (skip-chars-forward " \r\t\n")
  19123. (or (eobp) (beginning-of-line)))
  19124. ;; On affiliated keywords, move to element's beginning.
  19125. ((< (point) post-affiliated)
  19126. (goto-char post-affiliated))
  19127. ;; At a table row, move to the end of the table. Similarly,
  19128. ;; at a node property, move to the end of the property
  19129. ;; drawer.
  19130. ((memq type '(node-property table-row))
  19131. (goto-char (org-element-property
  19132. :end (org-element-property :parent element))))
  19133. ((memq type '(property-drawer table)) (goto-char end))
  19134. ;; Consider blank lines as separators in verse and source
  19135. ;; blocks to ease editing.
  19136. ((memq type '(src-block verse-block))
  19137. (when (eq type 'src-block)
  19138. (setq contents-end
  19139. (save-excursion (goto-char end)
  19140. (skip-chars-backward " \r\t\n")
  19141. (line-beginning-position))))
  19142. (beginning-of-line)
  19143. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  19144. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  19145. (goto-char end)
  19146. (skip-chars-forward " \r\t\n")
  19147. (if (= (point) contents-end) (goto-char end)
  19148. (beginning-of-line))))
  19149. ;; With no contents, just skip element.
  19150. ((not contents-begin) (goto-char end))
  19151. ;; If contents are invisible, skip the element altogether.
  19152. ((org-invisible-p (line-end-position))
  19153. (cl-case type
  19154. (headline
  19155. (org-with-limited-levels (outline-next-visible-heading 1)))
  19156. ;; At a plain list, make sure we move to the next item
  19157. ;; instead of skipping the whole list.
  19158. (plain-list (forward-char)
  19159. (org-forward-paragraph))
  19160. (otherwise (goto-char end))))
  19161. ((>= (point) contents-end) (goto-char end))
  19162. ((>= (point) contents-begin)
  19163. ;; This can only happen on paragraphs and plain lists.
  19164. (cl-case type
  19165. (paragraph (goto-char end))
  19166. ;; At a plain list, try to move to second element in
  19167. ;; first item, if possible.
  19168. (plain-list (end-of-line)
  19169. (org-forward-paragraph))))
  19170. ;; When contents start on the middle of a line (e.g. in
  19171. ;; items and footnote definitions), try to reach first
  19172. ;; element starting after current line.
  19173. ((> (line-end-position) contents-begin)
  19174. (end-of-line)
  19175. (org-forward-paragraph))
  19176. (t (goto-char contents-begin))))))
  19177. (defun org-backward-paragraph ()
  19178. "Move backward to start of previous paragraph or equivalent.
  19179. The function moves point to the beginning of the current
  19180. structural element, which can be a paragraph, a table, a list
  19181. item, etc., or to the beginning of the previous visible one if
  19182. point is already there. It also provides some special moves for
  19183. convenience:
  19184. - On an affiliated keyword, jump to the first one.
  19185. - On a table or a property drawer, move to its beginning.
  19186. - On comment, example, export, src and verse blocks, stop
  19187. before blank lines."
  19188. (interactive)
  19189. (unless (bobp)
  19190. (let* ((deactivate-mark nil)
  19191. (element (org-element-at-point))
  19192. (type (org-element-type element))
  19193. (contents-end (org-element-property :contents-end element))
  19194. (post-affiliated (org-element-property :post-affiliated element))
  19195. (begin (org-element-property :begin element))
  19196. (special? ;blocks handled specially
  19197. (memq type '(comment-block example-block export-block src-block
  19198. verse-block)))
  19199. (contents-begin
  19200. (if special?
  19201. ;; These types have no proper contents. Fake line
  19202. ;; below the block opening line as contents beginning.
  19203. (save-excursion (goto-char begin) (line-beginning-position 2))
  19204. (org-element-property :contents-begin element))))
  19205. (cond
  19206. ((not element) (goto-char (point-min)))
  19207. ((= (point) begin)
  19208. (backward-char)
  19209. (org-backward-paragraph))
  19210. ((<= (point) post-affiliated) (goto-char begin))
  19211. ;; Special behavior: on a table or a property drawer, move to
  19212. ;; its beginning.
  19213. ((memq type '(node-property table-row))
  19214. (goto-char (org-element-property
  19215. :post-affiliated (org-element-property :parent element))))
  19216. (special?
  19217. (if (<= (point) contents-begin) (goto-char post-affiliated)
  19218. ;; Inside a verse block, see blank lines as paragraph
  19219. ;; separators.
  19220. (let ((origin (point)))
  19221. (skip-chars-backward " \r\t\n" contents-begin)
  19222. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  19223. (skip-chars-forward " \r\t\n" origin)
  19224. (if (= (point) origin) (goto-char contents-begin)
  19225. (beginning-of-line))))))
  19226. ((eq type 'paragraph) (goto-char contents-begin)
  19227. ;; When at first paragraph in an item or a footnote definition,
  19228. ;; move directly to beginning of line.
  19229. (let ((parent-contents
  19230. (org-element-property
  19231. :contents-begin (org-element-property :parent element))))
  19232. (when (and parent-contents (= parent-contents contents-begin))
  19233. (beginning-of-line))))
  19234. ;; At the end of a greater element, move to the beginning of
  19235. ;; the last element within.
  19236. ((and contents-end (>= (point) contents-end))
  19237. (goto-char (1- contents-end))
  19238. (org-backward-paragraph))
  19239. (t (goto-char (or post-affiliated begin))))
  19240. ;; Ensure we never leave point invisible.
  19241. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  19242. (defun org-forward-element ()
  19243. "Move forward by one element.
  19244. Move to the next element at the same level, when possible."
  19245. (interactive)
  19246. (cond ((eobp) (user-error "Cannot move further down"))
  19247. ((org-with-limited-levels (org-at-heading-p))
  19248. (let ((origin (point)))
  19249. (goto-char (org-end-of-subtree nil t))
  19250. (unless (org-with-limited-levels (org-at-heading-p))
  19251. (goto-char origin)
  19252. (user-error "Cannot move further down"))))
  19253. (t
  19254. (let* ((elem (org-element-at-point))
  19255. (end (org-element-property :end elem))
  19256. (parent (org-element-property :parent elem)))
  19257. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19258. (goto-char (org-element-property :end parent)))
  19259. ((integer-or-marker-p end) (goto-char end))
  19260. (t (message "No element at point")))))))
  19261. (defun org-backward-element ()
  19262. "Move backward by one element.
  19263. Move to the previous element at the same level, when possible."
  19264. (interactive)
  19265. (cond ((bobp) (user-error "Cannot move further up"))
  19266. ((org-with-limited-levels (org-at-heading-p))
  19267. ;; At a headline, move to the previous one, if any, or stay
  19268. ;; here.
  19269. (let ((origin (point)))
  19270. (org-with-limited-levels (org-backward-heading-same-level 1))
  19271. ;; When current headline has no sibling above, move to its
  19272. ;; parent.
  19273. (when (= (point) origin)
  19274. (or (org-with-limited-levels (org-up-heading-safe))
  19275. (progn (goto-char origin)
  19276. (user-error "Cannot move further up"))))))
  19277. (t
  19278. (let* ((elem (org-element-at-point))
  19279. (beg (org-element-property :begin elem)))
  19280. (cond
  19281. ;; Move to beginning of current element if point isn't
  19282. ;; there already.
  19283. ((null beg) (message "No element at point"))
  19284. ((/= (point) beg) (goto-char beg))
  19285. (t (goto-char beg)
  19286. (skip-chars-backward " \r\t\n")
  19287. (unless (bobp)
  19288. (let ((prev (org-element-at-point)))
  19289. (goto-char (org-element-property :begin prev))
  19290. (while (and (setq prev (org-element-property :parent prev))
  19291. (<= (org-element-property :end prev) beg))
  19292. (goto-char (org-element-property :begin prev)))))))))))
  19293. (defun org-up-element ()
  19294. "Move to upper element."
  19295. (interactive)
  19296. (if (org-with-limited-levels (org-at-heading-p))
  19297. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19298. (let* ((elem (org-element-at-point))
  19299. (parent (org-element-property :parent elem)))
  19300. (if parent (goto-char (org-element-property :begin parent))
  19301. (if (org-with-limited-levels (org-before-first-heading-p))
  19302. (user-error "No surrounding element")
  19303. (org-with-limited-levels (org-back-to-heading)))))))
  19304. (defun org-down-element ()
  19305. "Move to inner element."
  19306. (interactive)
  19307. (let ((element (org-element-at-point)))
  19308. (cond
  19309. ((memq (org-element-type element) '(plain-list table))
  19310. (goto-char (org-element-property :contents-begin element))
  19311. (forward-char))
  19312. ((memq (org-element-type element) org-element-greater-elements)
  19313. ;; If contents are hidden, first disclose them.
  19314. (when (org-invisible-p (line-end-position)) (org-cycle))
  19315. (goto-char (or (org-element-property :contents-begin element)
  19316. (user-error "No content for this element"))))
  19317. (t (user-error "No inner element")))))
  19318. (defun org-drag-element-backward ()
  19319. "Move backward element at point."
  19320. (interactive)
  19321. (let ((elem (or (org-element-at-point)
  19322. (user-error "No element at point"))))
  19323. (if (eq (org-element-type elem) 'headline)
  19324. ;; Preserve point when moving a whole tree, even if point was
  19325. ;; on blank lines below the headline.
  19326. (let ((offset (skip-chars-backward " \t\n")))
  19327. (unwind-protect (org-move-subtree-up)
  19328. (forward-char (- offset))))
  19329. (let ((prev-elem
  19330. (save-excursion
  19331. (goto-char (org-element-property :begin elem))
  19332. (skip-chars-backward " \r\t\n")
  19333. (unless (bobp)
  19334. (let* ((beg (org-element-property :begin elem))
  19335. (prev (org-element-at-point))
  19336. (up prev))
  19337. (while (and (setq up (org-element-property :parent up))
  19338. (<= (org-element-property :end up) beg))
  19339. (setq prev up))
  19340. prev)))))
  19341. ;; Error out if no previous element or previous element is
  19342. ;; a parent of the current one.
  19343. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19344. (user-error "Cannot drag element backward")
  19345. (let ((pos (point)))
  19346. (org-element-swap-A-B prev-elem elem)
  19347. (goto-char (+ (org-element-property :begin prev-elem)
  19348. (- pos (org-element-property :begin elem))))))))))
  19349. (defun org-drag-element-forward ()
  19350. "Move forward element at point."
  19351. (interactive)
  19352. (let* ((pos (point))
  19353. (elem (or (org-element-at-point)
  19354. (user-error "No element at point"))))
  19355. (when (= (point-max) (org-element-property :end elem))
  19356. (user-error "Cannot drag element forward"))
  19357. (goto-char (org-element-property :end elem))
  19358. (let ((next-elem (org-element-at-point)))
  19359. (when (or (org-element-nested-p elem next-elem)
  19360. (and (eq (org-element-type next-elem) 'headline)
  19361. (not (eq (org-element-type elem) 'headline))))
  19362. (goto-char pos)
  19363. (user-error "Cannot drag element forward"))
  19364. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19365. ;; body's length (without final blanks) and by the length of
  19366. ;; blanks between ELEM and NEXT-ELEM.
  19367. (let ((size-next (- (save-excursion
  19368. (goto-char (org-element-property :end next-elem))
  19369. (skip-chars-backward " \r\t\n")
  19370. (forward-line)
  19371. ;; Small correction if buffer doesn't end
  19372. ;; with a newline character.
  19373. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19374. (org-element-property :begin next-elem)))
  19375. (size-blank (- (org-element-property :end elem)
  19376. (save-excursion
  19377. (goto-char (org-element-property :end elem))
  19378. (skip-chars-backward " \r\t\n")
  19379. (forward-line)
  19380. (point)))))
  19381. (org-element-swap-A-B elem next-elem)
  19382. (goto-char (+ pos size-next size-blank))))))
  19383. (defun org-drag-line-forward (arg)
  19384. "Drag the line at point ARG lines forward."
  19385. (interactive "p")
  19386. (dotimes (_ (abs arg))
  19387. (let ((c (current-column)))
  19388. (if (< 0 arg)
  19389. (progn
  19390. (beginning-of-line 2)
  19391. (transpose-lines 1)
  19392. (beginning-of-line 0))
  19393. (transpose-lines 1)
  19394. (beginning-of-line -1))
  19395. (org-move-to-column c))))
  19396. (defun org-drag-line-backward (arg)
  19397. "Drag the line at point ARG lines backward."
  19398. (interactive "p")
  19399. (org-drag-line-forward (- arg)))
  19400. (defun org-mark-element ()
  19401. "Put point at beginning of this element, mark at end.
  19402. Interactively, if this command is repeated or (in Transient Mark
  19403. mode) if the mark is active, it marks the next element after the
  19404. ones already marked."
  19405. (interactive)
  19406. (let (deactivate-mark)
  19407. (if (and (called-interactively-p 'any)
  19408. (or (and (eq last-command this-command) (mark t))
  19409. (and transient-mark-mode mark-active)))
  19410. (set-mark
  19411. (save-excursion
  19412. (goto-char (mark))
  19413. (goto-char (org-element-property :end (org-element-at-point)))))
  19414. (let ((element (org-element-at-point)))
  19415. (end-of-line)
  19416. (push-mark (org-element-property :end element) t t)
  19417. (goto-char (org-element-property :begin element))))))
  19418. (defun org-narrow-to-element ()
  19419. "Narrow buffer to current element."
  19420. (interactive)
  19421. (let ((elem (org-element-at-point)))
  19422. (cond
  19423. ((eq (car elem) 'headline)
  19424. (narrow-to-region
  19425. (org-element-property :begin elem)
  19426. (org-element-property :end elem)))
  19427. ((memq (car elem) org-element-greater-elements)
  19428. (narrow-to-region
  19429. (org-element-property :contents-begin elem)
  19430. (org-element-property :contents-end elem)))
  19431. (t
  19432. (narrow-to-region
  19433. (org-element-property :begin elem)
  19434. (org-element-property :end elem))))))
  19435. (defun org-transpose-element ()
  19436. "Transpose current and previous elements, keeping blank lines between.
  19437. Point is moved after both elements."
  19438. (interactive)
  19439. (org-skip-whitespace)
  19440. (let ((end (org-element-property :end (org-element-at-point))))
  19441. (org-drag-element-backward)
  19442. (goto-char end)))
  19443. (defun org-unindent-buffer ()
  19444. "Un-indent the visible part of the buffer.
  19445. Relative indentation (between items, inside blocks, etc.) isn't
  19446. modified."
  19447. (interactive)
  19448. (unless (eq major-mode 'org-mode)
  19449. (user-error "Cannot un-indent a buffer not in Org mode"))
  19450. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19451. (unindent-tree
  19452. (lambda (contents)
  19453. (dolist (element (reverse contents))
  19454. (if (memq (org-element-type element) '(headline section))
  19455. (funcall unindent-tree (org-element-contents element))
  19456. (save-excursion
  19457. (save-restriction
  19458. (narrow-to-region
  19459. (org-element-property :begin element)
  19460. (org-element-property :end element))
  19461. (org-do-remove-indentation))))))))
  19462. (funcall unindent-tree (org-element-contents parse-tree))))
  19463. (defun org-make-options-regexp (kwds &optional extra)
  19464. "Make a regular expression for keyword lines.
  19465. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19466. when non-nil, is a regexp matching keywords names."
  19467. (concat "^[ \t]*#\\+\\("
  19468. (regexp-opt kwds)
  19469. (and extra (concat (and kwds "\\|") extra))
  19470. "\\):[ \t]*\\(.*\\)"))
  19471. ;;; Conveniently switch to Info nodes
  19472. (defun org-info-find-node (&optional nodename)
  19473. "Find Info documentation NODENAME or Org documentation according context.
  19474. Started from `gnus-info-find-node'."
  19475. (interactive)
  19476. (Info-goto-node
  19477. (or nodename
  19478. (let ((default-org-info-node "(org) Top"))
  19479. (cond
  19480. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19481. ((eq 'org-mode major-mode)
  19482. (let* ((context (org-element-at-point))
  19483. (element-info-nodes ; compare to `org-element-all-elements'.
  19484. `((babel-call . "(org) Evaluating Code Blocks")
  19485. (center-block . "(org) Paragraphs")
  19486. (clock . ,default-org-info-node)
  19487. (comment . "(org) Comment Lines")
  19488. (comment-block . "(org) Comment Lines")
  19489. (diary-sexp . ,default-org-info-node)
  19490. (drawer . "(org) Drawers")
  19491. (dynamic-block . "(org) Dynamic Blocks")
  19492. (example-block . "(org) Literal Examples")
  19493. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19494. (fixed-width . ,default-org-info-node)
  19495. (footnote-definition . "(org) Creating Footnotes")
  19496. (headline . "(org) Document Structure")
  19497. (horizontal-rule . "(org) Built-in Table Editor")
  19498. (inlinetask . ,default-org-info-node)
  19499. (item . "(org) Plain Lists")
  19500. (keyword . "(org) Per-file keywords")
  19501. (latex-environment . "(org) LaTeX Export")
  19502. (node-property . "(org) Properties and Columns")
  19503. (paragraph . "(org) Paragraphs")
  19504. (plain-list . "(org) Plain Lists")
  19505. (planning . "(org) Deadlines and Scheduling")
  19506. (property-drawer . "(org) Properties and Columns")
  19507. (quote-block . "(org) Paragraphs")
  19508. (section . ,default-org-info-node)
  19509. (special-block . ,default-org-info-node)
  19510. (src-block . "(org) Working with Source Code")
  19511. (table . "(org) Tables")
  19512. (table-row . "(org) Tables")
  19513. (verse-block . "(org) Paragraphs"))))
  19514. (or (cdr (assoc (car context) element-info-nodes))
  19515. default-org-info-node)))
  19516. (t default-org-info-node))))))
  19517. ;;; Finish up
  19518. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19519. (lambda () (add-hook 'change-major-mode-hook
  19520. 'org-show-all 'append 'local)))
  19521. (provide 'org)
  19522. (run-hooks 'org-load-hook)
  19523. ;;; org.el ends here