org.el 898 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672
  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-2018 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Version: 9.1.13
  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-local org-table-formula-constants-local nil
  65. "Local version of `org-table-formula-constants'.")
  66. (defvar org-inlinetask-min-level)
  67. ;;;; Require other packages
  68. (require 'cl-lib)
  69. (eval-when-compile (require 'gnus-sum))
  70. (require 'calendar)
  71. (require 'find-func)
  72. (require 'format-spec)
  73. (or (eq this-command 'eval-buffer)
  74. (condition-case nil
  75. (load (concat (file-name-directory load-file-name)
  76. "org-loaddefs.el")
  77. nil t t t)
  78. (error
  79. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  80. (sit-for 3)
  81. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  82. (sit-for 3))))
  83. (eval-and-compile (require 'org-macs))
  84. (require 'org-compat)
  85. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  86. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  87. (defvar org-outline-regexp "\\*+ "
  88. "Regexp to match Org headlines.")
  89. (defvar org-outline-regexp-bol "^\\*+ "
  90. "Regexp to match Org headlines.
  91. This is similar to `org-outline-regexp' but additionally makes
  92. sure that we are at the beginning of the line.")
  93. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  94. "Matches a headline, putting stars and text into groups.
  95. Stars are put in group 1 and the trimmed body in group 2.")
  96. (declare-function calendar-check-holidays "holidays" (date))
  97. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  98. (declare-function cdlatex-math-symbol "ext:cdlatex")
  99. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  100. (declare-function org-add-archive-files "org-archive" (files))
  101. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  102. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  103. (declare-function org-agenda-redo "org-agenda" (&optional all))
  104. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  105. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  106. (declare-function org-archive-subtree-default "org-archive" ())
  107. (declare-function org-archive-to-archive-sibling "org-archive" ())
  108. (declare-function org-attach "org-attach" ())
  109. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  110. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  111. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  112. (declare-function org-clock-cancel "org-clock" ())
  113. (declare-function org-clock-display "org-clock" (&optional arg))
  114. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  115. (declare-function org-clock-goto "org-clock" (&optional select))
  116. (declare-function org-clock-in "org-clock" (&optional select start-time))
  117. (declare-function org-clock-in-last "org-clock" (&optional arg))
  118. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  119. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  120. (declare-function org-clock-report "org-clock" (&optional arg))
  121. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  122. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  123. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  124. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  125. (declare-function org-clock-update-time-maybe "org-clock" ())
  126. (declare-function org-clocking-buffer "org-clock" ())
  127. (declare-function org-clocktable-shift "org-clock" (dir n))
  128. (declare-function org-columns-insert-dblock "org-colview" ())
  129. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  130. (declare-function org-element-at-point "org-element" ())
  131. (declare-function org-element-cache-refresh "org-element" (pos))
  132. (declare-function org-element-cache-reset "org-element" (&optional all))
  133. (declare-function org-element-contents "org-element" (element))
  134. (declare-function org-element-context "org-element" (&optional element))
  135. (declare-function org-element-copy "org-element" (datum))
  136. (declare-function org-element-create "org-element" (type &optional props &rest children))
  137. (declare-function org-element-interpret-data "org-element" (data))
  138. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  139. (declare-function org-element-link-parser "org-element" ())
  140. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  141. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  142. (declare-function org-element-property "org-element" (property element))
  143. (declare-function org-element-put-property "org-element" (element property value))
  144. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  145. (declare-function org-element-timestamp-parser "org-element" ())
  146. (declare-function org-element-type "org-element" (element))
  147. (declare-function org-element-update-syntax "org-element" ())
  148. (declare-function org-export-dispatch "ox" (&optional arg))
  149. (declare-function org-export-get-backend "ox" (name))
  150. (declare-function org-export-get-backend "ox" (name))
  151. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  152. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  153. (declare-function org-feed-goto-inbox "org-feed" (feed))
  154. (declare-function org-feed-update-all "org-feed" ())
  155. (declare-function org-goto "org-goto" (&optional alternative-interface))
  156. (declare-function org-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-latex-make-preamble "ox-latex" (info &optional template snippet?))
  164. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  165. (declare-function org-table--shrunk-field "org-table" ()) ;; For `org-table-with-shrunk-field'.
  166. (declare-function org-table-align "org-table" ())
  167. (declare-function org-table-begin "org-table" (&optional table-type))
  168. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  169. (declare-function org-table-blank-field "org-table" ())
  170. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  171. (declare-function org-table-copy-down "org-table" (N))
  172. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  173. (declare-function org-table-create-or-convert-from-region "org-table" (arg))
  174. (declare-function org-table-create-with-table.el "org-table" ())
  175. (declare-function org-table-cut-region "org-table" (beg end))
  176. (declare-function org-table-edit-field "org-table" (arg))
  177. (declare-function org-table-end "org-table" (&optional table-type))
  178. (declare-function org-table-end-of-field "org-table" (&optional n))
  179. (declare-function org-table-eval-formula "org-table" (&optional arg equation suppress-align suppress-const suppress-store suppress-analysis))
  180. (declare-function org-table-field-info "org-table" (arg))
  181. (declare-function org-table-insert-row "org-table" (&optional arg))
  182. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  183. (declare-function org-table-maybe-eval-formula "org-table" ())
  184. (declare-function org-table-maybe-recalculate-line "org-table" ())
  185. (declare-function org-table-next-row "org-table" ())
  186. (declare-function org-table-paste-rectangle "org-table" ())
  187. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  188. (declare-function org-table-rotate-recalc-marks "org-table" (&optional newchar))
  189. (declare-function org-table-shrink "org-table" (&optional begin end))
  190. (declare-function org-table-sort-lines "org-table" (&optional with-case sorting-type getkey-func compare-func interactive?))
  191. (declare-function org-table-sum "org-table" (&optional beg end nlast))
  192. (declare-function org-table-toggle-column-width "org-table" (&optional arg))
  193. (declare-function org-table-toggle-coordinate-overlays "org-table" ())
  194. (declare-function org-table-toggle-formula-debugger "org-table" ())
  195. (declare-function org-table-wrap-region "org-table" (arg))
  196. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  197. (declare-function org-timer "org-timer" (&optional restart no-insert))
  198. (declare-function org-timer-item "org-timer" (&optional arg))
  199. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  200. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  201. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  202. (declare-function org-timer-start "org-timer" (&optional offset))
  203. (declare-function org-timer-stop "org-timer" ())
  204. (declare-function org-timer-stop "org-timer" ())
  205. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  206. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  207. (declare-function orgtbl-mode "org-table" (&optional arg))
  208. (defvar ffap-url-regexp)
  209. (defvar org-element-paragraph-separate)
  210. (defvar org-indent-indentation-per-level)
  211. ;; load languages based on value of `org-babel-load-languages'
  212. (defvar org-babel-load-languages)
  213. ;;;###autoload
  214. (defun org-babel-do-load-languages (sym value)
  215. "Load the languages defined in `org-babel-load-languages'."
  216. (set-default sym value)
  217. (dolist (pair org-babel-load-languages)
  218. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  219. (if active
  220. (require (intern (concat "ob-" lang)))
  221. (fmakunbound
  222. (intern (concat "org-babel-execute:" lang)))
  223. (fmakunbound
  224. (intern (concat "org-babel-expand-body:" lang)))))))
  225. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  226. ;;;###autoload
  227. (defun org-babel-load-file (file &optional compile)
  228. "Load Emacs Lisp source code blocks in the Org FILE.
  229. This function exports the source code using `org-babel-tangle'
  230. and then loads the resulting file using `load-file'. With prefix
  231. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  232. file to byte-code before it is loaded."
  233. (interactive "fFile to load: \nP")
  234. (let* ((age (lambda (file)
  235. (float-time
  236. (time-subtract (current-time)
  237. (nth 5 (or (file-attributes (file-truename file))
  238. (file-attributes file)))))))
  239. (base-name (file-name-sans-extension file))
  240. (exported-file (concat base-name ".el")))
  241. ;; tangle if the Org file is newer than the elisp file
  242. (unless (and (file-exists-p exported-file)
  243. (> (funcall age file) (funcall age exported-file)))
  244. ;; Tangle-file traversal returns reversed list of tangled files
  245. ;; and we want to evaluate the first target.
  246. (setq exported-file
  247. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  248. (message "%s %s"
  249. (if compile
  250. (progn (byte-compile-file exported-file 'load)
  251. "Compiled and loaded")
  252. (progn (load-file exported-file) "Loaded"))
  253. exported-file)))
  254. (defcustom org-babel-load-languages '((emacs-lisp . t))
  255. "Languages which can be evaluated in Org buffers.
  256. \\<org-mode-map>
  257. This list can be used to load support for any of the languages
  258. below. Each language will depend on a different set of system
  259. executables and/or Emacs modes.
  260. When a language is \"loaded\", code blocks in that language can
  261. be evaluated with `org-babel-execute-src-block', which is bound
  262. by default to \\[org-ctrl-c-ctrl-c].
  263. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  264. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  265. default, only Emacs Lisp is loaded, since it has no specific
  266. requirement."
  267. :group 'org-babel
  268. :set 'org-babel-do-load-languages
  269. :version "24.1"
  270. :type '(alist :tag "Babel Languages"
  271. :key-type
  272. (choice
  273. (const :tag "Awk" awk)
  274. (const :tag "C" C)
  275. (const :tag "R" R)
  276. (const :tag "Asymptote" asymptote)
  277. (const :tag "Calc" calc)
  278. (const :tag "Clojure" clojure)
  279. (const :tag "CSS" css)
  280. (const :tag "Ditaa" ditaa)
  281. (const :tag "Dot" dot)
  282. (const :tag "Ebnf2ps" ebnf2ps)
  283. (const :tag "Emacs Lisp" emacs-lisp)
  284. (const :tag "Forth" forth)
  285. (const :tag "Fortran" fortran)
  286. (const :tag "Gnuplot" gnuplot)
  287. (const :tag "Haskell" haskell)
  288. (const :tag "hledger" hledger)
  289. (const :tag "IO" io)
  290. (const :tag "J" J)
  291. (const :tag "Java" java)
  292. (const :tag "Javascript" js)
  293. (const :tag "LaTeX" latex)
  294. (const :tag "Ledger" ledger)
  295. (const :tag "Lilypond" lilypond)
  296. (const :tag "Lisp" lisp)
  297. (const :tag "Makefile" makefile)
  298. (const :tag "Maxima" maxima)
  299. (const :tag "Matlab" matlab)
  300. (const :tag "Mscgen" mscgen)
  301. (const :tag "Ocaml" ocaml)
  302. (const :tag "Octave" octave)
  303. (const :tag "Org" org)
  304. (const :tag "Perl" perl)
  305. (const :tag "Pico Lisp" picolisp)
  306. (const :tag "PlantUML" plantuml)
  307. (const :tag "Python" python)
  308. (const :tag "Ruby" ruby)
  309. (const :tag "Sass" sass)
  310. (const :tag "Scala" scala)
  311. (const :tag "Scheme" scheme)
  312. (const :tag "Screen" screen)
  313. (const :tag "Shell Script" shell)
  314. (const :tag "Shen" shen)
  315. (const :tag "Sql" sql)
  316. (const :tag "Sqlite" sqlite)
  317. (const :tag "Stan" stan)
  318. (const :tag "Vala" vala))
  319. :value-type (boolean :tag "Activate" :value t)))
  320. ;;;; Customization variables
  321. (defcustom org-clone-delete-id nil
  322. "Remove ID property of clones of a subtree.
  323. When non-nil, clones of a subtree don't inherit the ID property.
  324. Otherwise they inherit the ID property with a new unique
  325. identifier."
  326. :type 'boolean
  327. :version "24.1"
  328. :group 'org-id)
  329. ;;; Version
  330. (org-check-version)
  331. ;;;###autoload
  332. (defun org-version (&optional here full message)
  333. "Show the Org version.
  334. Interactively, or when MESSAGE is non-nil, show it in echo area.
  335. With prefix argument, or when HERE is non-nil, insert it at point.
  336. In non-interactive uses, a reduced version string is output unless
  337. FULL is given."
  338. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  339. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  340. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  341. (load-suffixes (list ".el"))
  342. (org-install-dir
  343. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  344. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  345. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  346. (let* ((load-suffixes save-load-suffixes)
  347. (release (org-release))
  348. (git-version (org-git-version))
  349. (version (format "Org mode version %s (%s @ %s)"
  350. release
  351. git-version
  352. (if org-install-dir
  353. (if (string= org-dir org-install-dir)
  354. org-install-dir
  355. (concat "mixed installation! "
  356. org-install-dir
  357. " and "
  358. org-dir))
  359. "org-loaddefs.el can not be found!")))
  360. (version1 (if full version release)))
  361. (when here (insert version1))
  362. (when message (message "%s" version1))
  363. version1)))
  364. (defconst org-version (org-version))
  365. ;;; Syntax Constants
  366. ;;;; Block
  367. (defconst org-block-regexp
  368. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  369. "Regular expression for hiding blocks.")
  370. (defconst org-dblock-start-re
  371. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  372. "Matches the start line of a dynamic block, with parameters.")
  373. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  374. "Matches the end of a dynamic block.")
  375. ;;;; Clock and Planning
  376. (defconst org-clock-string "CLOCK:"
  377. "String used as prefix for timestamps clocking work hours on an item.")
  378. (defvar org-closed-string "CLOSED:"
  379. "String used as the prefix for timestamps logging closing a TODO entry.")
  380. (defvar org-deadline-string "DEADLINE:"
  381. "String to mark deadline entries.
  382. \\<org-mode-map>
  383. A deadline is this string, followed by a time stamp. It must be
  384. a word, terminated by a colon. You can insert a schedule keyword
  385. and a timestamp with `\\[org-deadline]'.")
  386. (defvar org-scheduled-string "SCHEDULED:"
  387. "String to mark scheduled TODO entries.
  388. \\<org-mode-map>
  389. A schedule is this string, followed by a time stamp. It must be
  390. a word, terminated by a colon. You can insert a schedule keyword
  391. and a timestamp with `\\[org-schedule]'.")
  392. (defconst org-ds-keyword-length
  393. (+ 2
  394. (apply #'max
  395. (mapcar #'length
  396. (list org-deadline-string org-scheduled-string
  397. org-clock-string org-closed-string))))
  398. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  399. (defconst org-planning-line-re
  400. (concat "^[ \t]*"
  401. (regexp-opt
  402. (list org-closed-string org-deadline-string org-scheduled-string)
  403. t))
  404. "Matches a line with planning info.
  405. Matched keyword is in group 1.")
  406. (defconst org-clock-line-re
  407. (concat "^[ \t]*" org-clock-string)
  408. "Matches a line with clock info.")
  409. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  410. "Matches the DEADLINE keyword.")
  411. (defconst org-deadline-time-regexp
  412. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  413. "Matches the DEADLINE keyword together with a time stamp.")
  414. (defconst org-deadline-time-hour-regexp
  415. (concat "\\<" org-deadline-string
  416. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  417. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  418. (defconst org-deadline-line-regexp
  419. (concat "\\<\\(" org-deadline-string "\\).*")
  420. "Matches the DEADLINE keyword and the rest of the line.")
  421. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  422. "Matches the SCHEDULED keyword.")
  423. (defconst org-scheduled-time-regexp
  424. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  425. "Matches the SCHEDULED keyword together with a time stamp.")
  426. (defconst org-scheduled-time-hour-regexp
  427. (concat "\\<" org-scheduled-string
  428. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  429. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  430. (defconst org-closed-time-regexp
  431. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  432. "Matches the CLOSED keyword together with a time stamp.")
  433. (defconst org-keyword-time-regexp
  434. (concat "\\<"
  435. (regexp-opt
  436. (list org-scheduled-string org-deadline-string org-closed-string
  437. org-clock-string)
  438. t)
  439. " *[[<]\\([^]>]+\\)[]>]")
  440. "Matches any of the 4 keywords, together with the time stamp.")
  441. (defconst org-keyword-time-not-clock-regexp
  442. (concat
  443. "\\<"
  444. (regexp-opt
  445. (list org-scheduled-string org-deadline-string org-closed-string) t)
  446. " *[[<]\\([^]>]+\\)[]>]")
  447. "Matches any of the 3 keywords, together with the time stamp.")
  448. (defconst org-maybe-keyword-time-regexp
  449. (concat "\\(\\<"
  450. (regexp-opt
  451. (list org-scheduled-string org-deadline-string org-closed-string
  452. org-clock-string)
  453. t)
  454. "\\)?"
  455. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  456. "\\|"
  457. "<%%([^\r\n>]*>\\)")
  458. "Matches a timestamp, possibly preceded by a keyword.")
  459. (defconst org-all-time-keywords
  460. (mapcar (lambda (w) (substring w 0 -1))
  461. (list org-scheduled-string org-deadline-string
  462. org-clock-string org-closed-string))
  463. "List of time keywords.")
  464. ;;;; Drawer
  465. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  466. "Matches first or last line of a hidden block.
  467. Group 1 contains drawer's name or \"END\".")
  468. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  469. "Regular expression matching the first line of a property drawer.")
  470. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  471. "Regular expression matching the last line of a property drawer.")
  472. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  473. "Regular expression matching the first line of a clock drawer.")
  474. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  475. "Regular expression matching the last line of a clock drawer.")
  476. (defconst org-property-drawer-re
  477. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  478. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  479. "[ \t]*:END:[ \t]*$")
  480. "Matches an entire property drawer.")
  481. (defconst org-clock-drawer-re
  482. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  483. org-clock-drawer-end-re "\\)\n?")
  484. "Matches an entire clock drawer.")
  485. ;;;; Headline
  486. (defconst org-heading-keyword-regexp-format
  487. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  488. "Printf format for a regexp matching a headline with some keyword.
  489. This regexp will match the headline of any node which has the
  490. exact keyword that is put into the format. The keyword isn't in
  491. any group by default, but the stars and the body are.")
  492. (defconst org-heading-keyword-maybe-regexp-format
  493. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  494. "Printf format for a regexp matching a headline, possibly with some keyword.
  495. This regexp can match any headline with the specified keyword, or
  496. without a keyword. The keyword isn't in any group by default,
  497. but the stars and the body are.")
  498. (defconst org-archive-tag "ARCHIVE"
  499. "The tag that marks a subtree as archived.
  500. An archived subtree does not open during visibility cycling, and does
  501. not contribute to the agenda listings.")
  502. (defconst org-tag-re "[[:alnum:]_@#%]+"
  503. "Regexp matching a single tag.")
  504. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  505. "Regexp matching the tag group at the end of a line, with leading spaces.
  506. Tags are stored in match group 1. Match group 2 stores the tags
  507. without the enclosing colons.")
  508. (defconst org-tag-line-re
  509. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  510. "Regexp matching tags in a headline.
  511. Tags are stored in match group 1. Match group 2 stores the tags
  512. without the enclosing colons.")
  513. (eval-and-compile
  514. (defconst org-comment-string "COMMENT"
  515. "Entries starting with this keyword will never be exported.
  516. \\<org-mode-map>
  517. An entry can be toggled between COMMENT and normal with
  518. `\\[org-toggle-comment]'."))
  519. ;;;; LaTeX Environments and Fragments
  520. (defconst org-latex-regexps
  521. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  522. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  523. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  524. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  525. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  526. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  527. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  528. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  529. "Regular expressions for matching embedded LaTeX.")
  530. ;;;; Node Property
  531. (defconst org-effort-property "Effort"
  532. "The property that is being used to keep track of effort estimates.
  533. Effort estimates given in this property need to have the format H:MM.")
  534. ;;;; Table
  535. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  536. "Detect an org-type or table-type table.")
  537. (defconst org-table-line-regexp "^[ \t]*|"
  538. "Detect an org-type table line.")
  539. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  540. "Detect an org-type table line.")
  541. (defconst org-table-hline-regexp "^[ \t]*|-"
  542. "Detect an org-type table hline.")
  543. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  544. "Detect a table-type table hline.")
  545. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  546. "Detect the first line outside a table when searching from within it.
  547. This works for both table types.")
  548. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  549. "Detect a #+TBLFM line.")
  550. ;;;; Timestamp
  551. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  552. "Regular expression for fast time stamp matching.")
  553. (defconst org-ts-regexp-inactive
  554. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  555. "Regular expression for fast inactive time stamp matching.")
  556. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  557. "Regular expression for fast time stamp matching.")
  558. (defconst org-ts-regexp0
  559. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  560. "Regular expression matching time strings for analysis.
  561. This one does not require the space after the date, so it can be used
  562. on a string that terminates immediately after the date.")
  563. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  564. "Regular expression matching time strings for analysis.")
  565. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  566. "Regular expression matching time stamps, with groups.")
  567. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  568. "Regular expression matching time stamps (also [..]), with groups.")
  569. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  570. "Regular expression matching a time stamp range.")
  571. (defconst org-tr-regexp-both
  572. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  573. "Regular expression matching a time stamp range.")
  574. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  575. org-ts-regexp "\\)?")
  576. "Regular expression matching a time stamp or time stamp range.")
  577. (defconst org-tsr-regexp-both
  578. (concat org-ts-regexp-both "\\(--?-?"
  579. org-ts-regexp-both "\\)?")
  580. "Regular expression matching a time stamp or time stamp range.
  581. The time stamps may be either active or inactive.")
  582. (defconst org-repeat-re
  583. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  584. "Regular expression for specifying repeated events.
  585. After a match, group 1 contains the repeat expression.")
  586. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  587. "Formats for `format-time-string' which are used for time stamps.")
  588. ;;; The custom variables
  589. (defgroup org nil
  590. "Outline-based notes management and organizer."
  591. :tag "Org"
  592. :group 'outlines
  593. :group 'calendar)
  594. (defcustom org-mode-hook nil
  595. "Mode hook for Org mode, run after the mode was turned on."
  596. :group 'org
  597. :type 'hook)
  598. (defcustom org-load-hook nil
  599. "Hook that is run after org.el has been loaded."
  600. :group 'org
  601. :type 'hook)
  602. (defcustom org-log-buffer-setup-hook nil
  603. "Hook that is run after an Org log buffer is created."
  604. :group 'org
  605. :version "24.1"
  606. :type 'hook)
  607. (defvar org-modules) ; defined below
  608. (defvar org-modules-loaded nil
  609. "Have the modules been loaded already?")
  610. (defun org-load-modules-maybe (&optional force)
  611. "Load all extensions listed in `org-modules'."
  612. (when (or force (not org-modules-loaded))
  613. (dolist (ext org-modules)
  614. (condition-case nil (require ext)
  615. (error (message "Problems while trying to load feature `%s'" ext))))
  616. (setq org-modules-loaded t)))
  617. (defun org-set-modules (var value)
  618. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  619. (set var value)
  620. (when (featurep 'org)
  621. (org-load-modules-maybe 'force)
  622. (org-element-cache-reset 'all)))
  623. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail org-eww)
  624. "Modules that should always be loaded together with org.el.
  625. If a description starts with <C>, the file is not part of Emacs
  626. and loading it will require that you have downloaded and properly
  627. installed the Org mode distribution.
  628. You can also use this system to load external packages (i.e. neither Org
  629. core modules, nor modules from the CONTRIB directory). Just add symbols
  630. to the end of the list. If the package is called org-xyz.el, then you need
  631. to add the symbol `xyz', and the package must have a call to:
  632. (provide \\='org-xyz)
  633. For export specific modules, see also `org-export-backends'."
  634. :group 'org
  635. :set 'org-set-modules
  636. :version "26.1"
  637. :package-version '(Org . "9.2")
  638. :type
  639. '(set :greedy t
  640. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  641. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  642. (const :tag " crypt: Encryption of subtrees" org-crypt)
  643. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  644. (const :tag " docview: Links to doc-view buffers" org-docview)
  645. (const :tag " eww: Store link to url of eww" org-eww)
  646. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  647. (const :tag " habit: Track your consistency with habits" org-habit)
  648. (const :tag " id: Global IDs for identifying entries" org-id)
  649. (const :tag " info: Links to Info nodes" org-info)
  650. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  651. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  652. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  653. (const :tag " mouse: Additional mouse support" org-mouse)
  654. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  655. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  656. (const :tag " tempo: Fast completion for structures" org-tempo)
  657. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  658. (const :tag " eshell: Support for links to working directories in eshell" org-eshell)
  659. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  660. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  661. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  662. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  663. (const :tag "C collector: Collect properties into tables" org-collector)
  664. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  665. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  666. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  667. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  668. (const :tag "C eval: Include command output as text" org-eval)
  669. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  670. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  671. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  672. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  673. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  674. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  675. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  676. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  677. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  678. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  679. (const :tag "C notify: Notifications for Org-mode" org-notify)
  680. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  681. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  682. (const :tag "C registry: A registry for Org links" org-registry)
  683. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  684. (const :tag "C screenshot: Take and manage screenshots in Org-mode files" org-screenshot)
  685. (const :tag "C secretary: Team management with Org" org-secretary)
  686. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  687. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  688. (const :tag "C track: Keep up with Org mode development" org-track)
  689. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  690. (const :tag "C vm: Links to VM folders/messages" org-vm)
  691. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  692. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  693. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  694. (defvar org-export-registered-backends) ; From ox.el.
  695. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  696. (declare-function org-export-backend-name "ox" (backend) t)
  697. (defcustom org-export-backends '(ascii html icalendar latex odt)
  698. "List of export back-ends that should be always available.
  699. If a description starts with <C>, the file is not part of Emacs
  700. and loading it will require that you have downloaded and properly
  701. installed the Org mode distribution.
  702. Unlike to `org-modules', libraries in this list will not be
  703. loaded along with Org, but only once the export framework is
  704. needed.
  705. This variable needs to be set before org.el is loaded. If you
  706. need to make a change while Emacs is running, use the customize
  707. interface or run the following code, where VAL stands for the new
  708. value of the variable, after updating it:
  709. (progn
  710. (setq org-export-registered-backends
  711. (cl-remove-if-not
  712. (lambda (backend)
  713. (let ((name (org-export-backend-name backend)))
  714. (or (memq name val)
  715. (catch \\='parentp
  716. (dolist (b val)
  717. (and (org-export-derived-backend-p b name)
  718. (throw \\='parentp t)))))))
  719. org-export-registered-backends))
  720. (let ((new-list (mapcar #\\='org-export-backend-name
  721. org-export-registered-backends)))
  722. (dolist (backend val)
  723. (cond
  724. ((not (load (format \"ox-%s\" backend) t t))
  725. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  726. backend))
  727. ((not (memq backend new-list)) (push backend new-list))))
  728. (set-default \\='org-export-backends new-list)))
  729. Adding a back-end to this list will also pull the back-end it
  730. depends on, if any."
  731. :group 'org
  732. :group 'org-export
  733. :version "26.1"
  734. :package-version '(Org . "9.0")
  735. :initialize 'custom-initialize-set
  736. :set (lambda (var val)
  737. (if (not (featurep 'ox)) (set-default var val)
  738. ;; Any back-end not required anymore (not present in VAL and not
  739. ;; a parent of any back-end in the new value) is removed from the
  740. ;; list of registered back-ends.
  741. (setq org-export-registered-backends
  742. (cl-remove-if-not
  743. (lambda (backend)
  744. (let ((name (org-export-backend-name backend)))
  745. (or (memq name val)
  746. (catch 'parentp
  747. (dolist (b val)
  748. (and (org-export-derived-backend-p b name)
  749. (throw 'parentp t)))))))
  750. org-export-registered-backends))
  751. ;; Now build NEW-LIST of both new back-ends and required
  752. ;; parents.
  753. (let ((new-list (mapcar #'org-export-backend-name
  754. org-export-registered-backends)))
  755. (dolist (backend val)
  756. (cond
  757. ((not (load (format "ox-%s" backend) t t))
  758. (message "Problems while trying to load export back-end `%s'"
  759. backend))
  760. ((not (memq backend new-list)) (push backend new-list))))
  761. ;; Set VAR to that list with fixed dependencies.
  762. (set-default var new-list))))
  763. :type '(set :greedy t
  764. (const :tag " ascii Export buffer to ASCII format" ascii)
  765. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  766. (const :tag " html Export buffer to HTML format" html)
  767. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  768. (const :tag " latex Export buffer to LaTeX format" latex)
  769. (const :tag " man Export buffer to MAN format" man)
  770. (const :tag " md Export buffer to Markdown format" md)
  771. (const :tag " odt Export buffer to ODT format" odt)
  772. (const :tag " org Export buffer to Org format" org)
  773. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  774. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  775. (const :tag "C deck Export buffer to deck.js presentations" deck)
  776. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  777. (const :tag "C groff Export buffer to Groff format" groff)
  778. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  779. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  780. (const :tag "C s5 Export buffer to s5 presentations" s5)
  781. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  782. (eval-after-load 'ox
  783. '(dolist (backend org-export-backends)
  784. (condition-case nil (require (intern (format "ox-%s" backend)))
  785. (error (message "Problems while trying to load export back-end `%s'"
  786. backend)))))
  787. (defcustom org-support-shift-select nil
  788. "Non-nil means make shift-cursor commands select text when possible.
  789. \\<org-mode-map>\
  790. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  791. start selecting a region, or enlarge regions started in this way.
  792. In Org mode, in special contexts, these same keys are used for
  793. other purposes, important enough to compete with shift selection.
  794. Org tries to balance these needs by supporting `shift-select-mode'
  795. outside these special contexts, under control of this variable.
  796. The default of this variable is nil, to avoid confusing behavior. Shifted
  797. cursor keys will then execute Org commands in the following contexts:
  798. - on a headline, changing TODO state (left/right) and priority (up/down)
  799. - on a time stamp, changing the time
  800. - in a plain list item, changing the bullet type
  801. - in a property definition line, switching between allowed values
  802. - in the BEGIN line of a clock table (changing the time block).
  803. Outside these contexts, the commands will throw an error.
  804. When this variable is t and the cursor is not in a special
  805. context, Org mode will support shift-selection for making and
  806. enlarging regions. To make this more effective, the bullet
  807. cycling will no longer happen anywhere in an item line, but only
  808. if the cursor is exactly on the bullet.
  809. If you set this variable to the symbol `always', then the keys
  810. will not be special in headlines, property lines, and item lines,
  811. to make shift selection work there as well. If this is what you
  812. want, you can use the following alternative commands:
  813. `\\[org-todo]' and `\\[org-priority]' \
  814. to change TODO state and priority,
  815. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  816. can be used to switch TODO sets,
  817. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  818. and properties can be edited by hand or in column view.
  819. However, when the cursor is on a timestamp, shift-cursor commands
  820. will still edit the time stamp - this is just too good to give up."
  821. :group 'org
  822. :type '(choice
  823. (const :tag "Never" nil)
  824. (const :tag "When outside special context" t)
  825. (const :tag "Everywhere except timestamps" always)))
  826. (defcustom org-loop-over-headlines-in-active-region nil
  827. "Shall some commands act upon headlines in the active region?
  828. When set to t, some commands will be performed in all headlines
  829. within the active region.
  830. When set to `start-level', some commands will be performed in all
  831. headlines within the active region, provided that these headlines
  832. are of the same level than the first one.
  833. When set to a string, those commands will be performed on the
  834. matching headlines within the active region. Such string must be
  835. a tags/property/todo match as it is used in the agenda tags view.
  836. The list of commands is: `org-schedule', `org-deadline',
  837. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  838. `org-archive-to-archive-sibling'. The archiving commands skip
  839. already archived entries."
  840. :type '(choice (const :tag "Don't loop" nil)
  841. (const :tag "All headlines in active region" t)
  842. (const :tag "In active region, headlines at the same level than the first one" start-level)
  843. (string :tag "Tags/Property/Todo matcher"))
  844. :version "24.1"
  845. :group 'org-todo
  846. :group 'org-archive)
  847. (defcustom org-startup-folded t
  848. "Non-nil means entering Org mode will switch to OVERVIEW.
  849. This can also be configured on a per-file basis by adding one of
  850. the following lines anywhere in the buffer:
  851. #+STARTUP: fold (or `overview', this is equivalent)
  852. #+STARTUP: nofold (or `showall', this is equivalent)
  853. #+STARTUP: content
  854. #+STARTUP: showeverything
  855. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  856. to ignore this option when Org opens agenda files for the first
  857. time."
  858. :group 'org-startup
  859. :type '(choice
  860. (const :tag "nofold: show all" nil)
  861. (const :tag "fold: overview" t)
  862. (const :tag "content: all headlines" content)
  863. (const :tag "show everything, even drawers" showeverything)))
  864. (defcustom org-startup-truncated t
  865. "Non-nil means entering Org mode will set `truncate-lines'.
  866. This is useful since some lines containing links can be very long and
  867. uninteresting. Also tables look terrible when wrapped.
  868. The variable `org-startup-truncated' allows to configure
  869. truncation for Org mode different to the other modes that use the
  870. variable `truncate-lines' and as a shortcut instead of putting
  871. the variable `truncate-lines' into the `org-mode-hook'. If one
  872. wants to configure truncation for Org mode not statically but
  873. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  874. the variable `truncate-lines' has to be used because in such a
  875. case it is too late to set the variable `org-startup-truncated'."
  876. :group 'org-startup
  877. :type 'boolean)
  878. (defcustom org-startup-indented nil
  879. "Non-nil means turn on `org-indent-mode' on startup.
  880. This can also be configured on a per-file basis by adding one of
  881. the following lines anywhere in the buffer:
  882. #+STARTUP: indent
  883. #+STARTUP: noindent"
  884. :group 'org-structure
  885. :type '(choice
  886. (const :tag "Not" nil)
  887. (const :tag "Globally (slow on startup in large files)" t)))
  888. (defcustom org-use-sub-superscripts t
  889. "Non-nil means interpret \"_\" and \"^\" for display.
  890. If you want to control how Org exports those characters, see
  891. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  892. used to be an alias for `org-export-with-sub-superscripts' in
  893. Org <8.0, it is not anymore.
  894. When this option is turned on, you can use TeX-like syntax for
  895. sub- and superscripts within the buffer. Several characters after
  896. \"_\" or \"^\" will be considered as a single item - so grouping
  897. with {} is normally not needed. For example, the following things
  898. will be parsed as single sub- or superscripts:
  899. 10^24 or 10^tau several digits will be considered 1 item.
  900. 10^-12 or 10^-tau a leading sign with digits or a word
  901. x^2-y^3 will be read as x^2 - y^3, because items are
  902. terminated by almost any nonword/nondigit char.
  903. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  904. Still, ambiguity is possible. So when in doubt, use {} to enclose
  905. the sub/superscript. If you set this variable to the symbol `{}',
  906. the braces are *required* in order to trigger interpretations as
  907. sub/superscript. This can be helpful in documents that need \"_\"
  908. frequently in plain text."
  909. :group 'org-startup
  910. :version "24.4"
  911. :package-version '(Org . "8.0")
  912. :type '(choice
  913. (const :tag "Always interpret" t)
  914. (const :tag "Only with braces" {})
  915. (const :tag "Never interpret" nil)))
  916. (defcustom org-startup-with-beamer-mode nil
  917. "Non-nil means turn on `org-beamer-mode' on startup.
  918. This can also be configured on a per-file basis by adding one of
  919. the following lines anywhere in the buffer:
  920. #+STARTUP: beamer"
  921. :group 'org-startup
  922. :version "24.1"
  923. :type 'boolean)
  924. (defcustom org-startup-align-all-tables nil
  925. "Non-nil means align all tables when visiting a file.
  926. This can also be configured on a per-file basis by adding one of
  927. the following lines anywhere in the buffer:
  928. #+STARTUP: align
  929. #+STARTUP: noalign"
  930. :group 'org-startup
  931. :type 'boolean)
  932. (defcustom org-startup-shrink-all-tables nil
  933. "Non-nil means shrink all table columns with a width cookie.
  934. This can also be configured on a per-file basis by adding one of
  935. the following lines anywhere in the buffer:
  936. #+STARTUP: shrink"
  937. :group 'org-startup
  938. :type 'boolean
  939. :version "27.1"
  940. :package-version '(Org . "9.2")
  941. :safe #'booleanp)
  942. (defcustom org-startup-with-inline-images nil
  943. "Non-nil means show inline images when loading a new Org file.
  944. This can also be configured on a per-file basis by adding one of
  945. the following lines anywhere in the buffer:
  946. #+STARTUP: inlineimages
  947. #+STARTUP: noinlineimages"
  948. :group 'org-startup
  949. :version "24.1"
  950. :type 'boolean)
  951. (defcustom org-startup-with-latex-preview nil
  952. "Non-nil means preview LaTeX fragments when loading a new Org file.
  953. This can also be configured on a per-file basis by adding one of
  954. the following lines anywhere in the buffer:
  955. #+STARTUP: latexpreview
  956. #+STARTUP: nolatexpreview"
  957. :group 'org-startup
  958. :version "24.4"
  959. :package-version '(Org . "8.0")
  960. :type 'boolean)
  961. (defcustom org-insert-mode-line-in-empty-file nil
  962. "Non-nil means insert the first line setting Org mode in empty files.
  963. When the function `org-mode' is called interactively in an empty file, this
  964. normally means that the file name does not automatically trigger Org mode.
  965. To ensure that the file will always be in Org mode in the future, a
  966. line enforcing Org mode will be inserted into the buffer, if this option
  967. has been set."
  968. :group 'org-startup
  969. :type 'boolean)
  970. (defcustom org-replace-disputed-keys nil
  971. "Non-nil means use alternative key bindings for some keys.
  972. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  973. These keys are also used by other packages like Shift Select mode,
  974. CUA mode or Windmove. If you want to use Org mode together with
  975. one of these other modes, or more generally if you would like to
  976. move some Org mode commands to other keys, set this variable and
  977. configure the keys with the variable `org-disputed-keys'.
  978. This option is only relevant at load-time of Org mode, and must be set
  979. *before* org.el is loaded. Changing it requires a restart of Emacs to
  980. become effective."
  981. :group 'org-startup
  982. :type 'boolean)
  983. (defcustom org-use-extra-keys nil
  984. "Non-nil means use extra key sequence definitions for certain commands.
  985. This happens automatically if `window-system' is nil. This
  986. variable lets you do the same manually. You must set it before
  987. loading Org."
  988. :group 'org-startup
  989. :type 'boolean)
  990. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  991. (defcustom org-disputed-keys
  992. '(([(shift up)] . [(meta p)])
  993. ([(shift down)] . [(meta n)])
  994. ([(shift left)] . [(meta -)])
  995. ([(shift right)] . [(meta +)])
  996. ([(control shift right)] . [(meta shift +)])
  997. ([(control shift left)] . [(meta shift -)]))
  998. "Keys for which Org mode and other modes compete.
  999. This is an alist, cars are the default keys, second element specifies
  1000. the alternative to use when `org-replace-disputed-keys' is t.
  1001. Keys can be specified in any syntax supported by `define-key'.
  1002. The value of this option takes effect only at Org mode startup,
  1003. therefore you'll have to restart Emacs to apply it after changing."
  1004. :group 'org-startup
  1005. :type 'alist)
  1006. (defun org-key (key)
  1007. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  1008. Or return the original if not disputed."
  1009. (when org-replace-disputed-keys
  1010. (let* ((nkey (key-description key))
  1011. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  1012. org-disputed-keys)))
  1013. (setq key (if x (cdr x) key))))
  1014. key)
  1015. (defun org-defkey (keymap key def)
  1016. "Define a key, possibly translated, as returned by `org-key'."
  1017. (define-key keymap (org-key key) def))
  1018. (defcustom org-ellipsis nil
  1019. "The ellipsis to use in the Org mode outline.
  1020. When nil, just use the standard three dots. When a non-empty string,
  1021. use that string instead.
  1022. The change affects only Org mode (which will then use its own display table).
  1023. Changing this requires executing `\\[org-mode]' in a buffer to become
  1024. effective."
  1025. :group 'org-startup
  1026. :type '(choice (const :tag "Default" nil)
  1027. (string :tag "String" :value "...#"))
  1028. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  1029. (defvar org-display-table nil
  1030. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  1031. (defgroup org-keywords nil
  1032. "Keywords in Org mode."
  1033. :tag "Org Keywords"
  1034. :group 'org)
  1035. (defcustom org-closed-keep-when-no-todo nil
  1036. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1037. :group 'org-todo
  1038. :group 'org-keywords
  1039. :version "24.4"
  1040. :package-version '(Org . "8.0")
  1041. :type 'boolean)
  1042. (defgroup org-structure nil
  1043. "Options concerning the general structure of Org files."
  1044. :tag "Org Structure"
  1045. :group 'org)
  1046. (defgroup org-reveal-location nil
  1047. "Options about how to make context of a location visible."
  1048. :tag "Org Reveal Location"
  1049. :group 'org-structure)
  1050. (defcustom org-show-context-detail '((agenda . local)
  1051. (bookmark-jump . lineage)
  1052. (isearch . lineage)
  1053. (default . ancestors))
  1054. "Alist between context and visibility span when revealing a location.
  1055. \\<org-mode-map>Some actions may move point into invisible
  1056. locations. As a consequence, Org always expose a neighborhood
  1057. around point. How much is shown depends on the initial action,
  1058. or context. Valid contexts are
  1059. agenda when exposing an entry from the agenda
  1060. org-goto when using the command `org-goto' (`\\[org-goto]')
  1061. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1062. tags-tree when constructing a sparse tree based on tags matches
  1063. link-search when exposing search matches associated with a link
  1064. mark-goto when exposing the jump goal of a mark
  1065. bookmark-jump when exposing a bookmark location
  1066. isearch when exiting from an incremental search
  1067. default default for all contexts not set explicitly
  1068. Allowed visibility spans are
  1069. minimal show current headline; if point is not on headline,
  1070. also show entry
  1071. local show current headline, entry and next headline
  1072. ancestors show current headline and its direct ancestors; if
  1073. point is not on headline, also show entry
  1074. lineage show current headline, its direct ancestors and all
  1075. their children; if point is not on headline, also show
  1076. entry and first child
  1077. tree show current headline, its direct ancestors and all
  1078. their children; if point is not on headline, also show
  1079. entry and all children
  1080. canonical show current headline, its direct ancestors along with
  1081. their entries and children; if point is not located on
  1082. the headline, also show current entry and all children
  1083. As special cases, a nil or t value means show all contexts in
  1084. `minimal' or `canonical' view, respectively.
  1085. Some views can make displayed information very compact, but also
  1086. make it harder to edit the location of the match. In such
  1087. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1088. more context."
  1089. :group 'org-reveal-location
  1090. :version "26.1"
  1091. :package-version '(Org . "9.0")
  1092. :type '(choice
  1093. (const :tag "Canonical" t)
  1094. (const :tag "Minimal" nil)
  1095. (repeat :greedy t :tag "Individual contexts"
  1096. (cons
  1097. (choice :tag "Context"
  1098. (const agenda)
  1099. (const org-goto)
  1100. (const occur-tree)
  1101. (const tags-tree)
  1102. (const link-search)
  1103. (const mark-goto)
  1104. (const bookmark-jump)
  1105. (const isearch)
  1106. (const default))
  1107. (choice :tag "Detail level"
  1108. (const minimal)
  1109. (const local)
  1110. (const ancestors)
  1111. (const lineage)
  1112. (const tree)
  1113. (const canonical))))))
  1114. (defcustom org-indirect-buffer-display 'other-window
  1115. "How should indirect tree buffers be displayed?
  1116. This applies to indirect buffers created with the commands
  1117. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1118. Valid values are:
  1119. current-window Display in the current window
  1120. other-window Just display in another window.
  1121. dedicated-frame Create one new frame, and re-use it each time.
  1122. new-frame Make a new frame each time. Note that in this case
  1123. previously-made indirect buffers are kept, and you need to
  1124. kill these buffers yourself."
  1125. :group 'org-structure
  1126. :group 'org-agenda-windows
  1127. :type '(choice
  1128. (const :tag "In current window" current-window)
  1129. (const :tag "In current frame, other window" other-window)
  1130. (const :tag "Each time a new frame" new-frame)
  1131. (const :tag "One dedicated frame" dedicated-frame)))
  1132. (defcustom org-use-speed-commands nil
  1133. "Non-nil means activate single letter commands at beginning of a headline.
  1134. This may also be a function to test for appropriate locations where speed
  1135. commands should be active.
  1136. For example, to activate speed commands when the point is on any
  1137. star at the beginning of the headline, you can do this:
  1138. (setq org-use-speed-commands
  1139. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1140. :group 'org-structure
  1141. :type '(choice
  1142. (const :tag "Never" nil)
  1143. (const :tag "At beginning of headline stars" t)
  1144. (function)))
  1145. (defcustom org-speed-commands-user nil
  1146. "Alist of additional speed commands.
  1147. This list will be checked before `org-speed-commands-default'
  1148. when the variable `org-use-speed-commands' is non-nil
  1149. and when the cursor is at the beginning of a headline.
  1150. The car of each entry is a string with a single letter, which must
  1151. be assigned to `self-insert-command' in the global map.
  1152. The cdr is either a command to be called interactively, a function
  1153. to be called, or a form to be evaluated.
  1154. An entry that is just a list with a single string will be interpreted
  1155. as a descriptive headline that will be added when listing the speed
  1156. commands in the Help buffer using the `?' speed command."
  1157. :group 'org-structure
  1158. :type '(repeat :value ("k" . ignore)
  1159. (choice :value ("k" . ignore)
  1160. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1161. (cons :tag "Letter and Command"
  1162. (string :tag "Command letter")
  1163. (choice
  1164. (function)
  1165. (sexp))))))
  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. (defcustom org-special-ctrl-a/e nil
  1326. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1327. When t, `C-a' will bring back the cursor to the beginning of the
  1328. headline text, i.e. after the stars and after a possible TODO
  1329. keyword. In an item, this will be the position after bullet and
  1330. check-box, if any. When the cursor is already at that position,
  1331. another `C-a' will bring it to the beginning of the line.
  1332. `C-e' will jump to the end of the headline, ignoring the presence
  1333. of tags in the headline. A second `C-e' will then jump to the
  1334. true end of the line, after any tags. This also means that, when
  1335. this variable is non-nil, `C-e' also will never jump beyond the
  1336. end of the heading of a folded section, i.e. not after the
  1337. ellipses.
  1338. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1339. normally, going to the true line boundary first. Only a directly
  1340. following, identical keypress will bring the cursor to the
  1341. special positions.
  1342. This may also be a cons cell where the behavior for `C-a' and
  1343. `C-e' is set separately."
  1344. :group 'org-edit-structure
  1345. :type '(choice
  1346. (const :tag "off" nil)
  1347. (const :tag "on: after stars/bullet and before tags first" t)
  1348. (const :tag "reversed: true line boundary first" reversed)
  1349. (cons :tag "Set C-a and C-e separately"
  1350. (choice :tag "Special C-a"
  1351. (const :tag "off" nil)
  1352. (const :tag "on: after stars/bullet first" t)
  1353. (const :tag "reversed: before stars/bullet first" reversed))
  1354. (choice :tag "Special C-e"
  1355. (const :tag "off" nil)
  1356. (const :tag "on: before tags first" t)
  1357. (const :tag "reversed: after tags first" reversed)))))
  1358. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  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. (defcustom org-enable-fixed-width-editor t
  1475. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1476. This currently only means they are never auto-wrapped.
  1477. When nil, such lines will be treated like ordinary lines."
  1478. :group 'org-edit-structure
  1479. :type 'boolean)
  1480. (defgroup org-sparse-trees nil
  1481. "Options concerning sparse trees in Org mode."
  1482. :tag "Org Sparse Trees"
  1483. :group 'org-structure)
  1484. (defcustom org-highlight-sparse-tree-matches t
  1485. "Non-nil means highlight all matches that define a sparse tree.
  1486. The highlights will automatically disappear the next time the buffer is
  1487. changed by an edit command."
  1488. :group 'org-sparse-trees
  1489. :type 'boolean)
  1490. (defcustom org-remove-highlights-with-change t
  1491. "Non-nil means any change to the buffer will remove temporary highlights.
  1492. \\<org-mode-map>\
  1493. Such highlights are created by `org-occur' and `org-clock-display'.
  1494. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1495. to get rid of the highlights.
  1496. The highlights created by `org-toggle-latex-fragment' always need
  1497. `\\[org-toggle-latex-fragment]' to be removed."
  1498. :group 'org-sparse-trees
  1499. :group 'org-time
  1500. :type 'boolean)
  1501. (defcustom org-occur-case-fold-search t
  1502. "Non-nil means `org-occur' should be case-insensitive.
  1503. If set to `smart' the search will be case-insensitive only if it
  1504. doesn't specify any upper case character."
  1505. :group 'org-sparse-trees
  1506. :version "26.1"
  1507. :type '(choice
  1508. (const :tag "Case-sensitive" nil)
  1509. (const :tag "Case-insensitive" t)
  1510. (const :tag "Case-insensitive for lower case searches only" smart)))
  1511. (defcustom org-occur-hook '(org-first-headline-recenter)
  1512. "Hook that is run after `org-occur' has constructed a sparse tree.
  1513. This can be used to recenter the window to show as much of the structure
  1514. as possible."
  1515. :group 'org-sparse-trees
  1516. :type 'hook)
  1517. (defgroup org-table nil
  1518. "Options concerning tables in Org mode."
  1519. :tag "Org Table"
  1520. :group 'org)
  1521. (defcustom org-self-insert-cluster-for-undo nil
  1522. "Non-nil means cluster self-insert commands for undo when possible.
  1523. If this is set, then, like in the Emacs command loop, 20 consecutive
  1524. characters will be undone together.
  1525. This is configurable, because there is some impact on typing performance."
  1526. :group 'org-table
  1527. :type 'boolean)
  1528. (defcustom org-table-tab-recognizes-table.el t
  1529. "Non-nil means TAB will automatically notice a table.el table.
  1530. When it sees such a table, it moves point into it and - if necessary -
  1531. calls `table-recognize-table'."
  1532. :group 'org-table-editing
  1533. :type 'boolean)
  1534. (defgroup org-link nil
  1535. "Options concerning links in Org mode."
  1536. :tag "Org Link"
  1537. :group 'org)
  1538. (defvar-local org-link-abbrev-alist-local nil
  1539. "Buffer-local version of `org-link-abbrev-alist', which see.
  1540. The value of this is taken from the #+LINK lines.")
  1541. (defcustom org-link-parameters
  1542. '(("doi" :follow org--open-doi-link)
  1543. ("elisp" :follow org--open-elisp-link)
  1544. ("file" :complete org-file-complete-link)
  1545. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1546. ("help" :follow org--open-help-link)
  1547. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1548. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1549. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1550. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1551. ("shell" :follow org--open-shell-link))
  1552. "An alist of properties that defines all the links in Org mode.
  1553. The key in each association is a string of the link type.
  1554. Subsequent optional elements make up a p-list of link properties.
  1555. :follow - A function that takes the link path as an argument.
  1556. :export - A function that takes the link path, description and
  1557. export-backend as arguments.
  1558. :store - A function responsible for storing the link. See the
  1559. function `org-store-link-functions'.
  1560. :complete - A function that inserts a link with completion. The
  1561. function takes one optional prefix arg.
  1562. :face - A face for the link, or a function that returns a face.
  1563. The function takes one argument which is the link path. The
  1564. default face is `org-link'.
  1565. :mouse-face - The mouse-face. The default is `highlight'.
  1566. :display - `full' will not fold the link in descriptive
  1567. display. Default is `org-link'.
  1568. :help-echo - A string or function that takes (window object position)
  1569. as arguments and returns a string.
  1570. :keymap - A keymap that is active on the link. The default is
  1571. `org-mouse-map'.
  1572. :htmlize-link - A function for the htmlize-link. Defaults
  1573. to (list :uri \"type:path\")
  1574. :activate-func - A function to run at the end of font-lock
  1575. activation. The function must accept (link-start link-end path bracketp)
  1576. as arguments."
  1577. :group 'org-link
  1578. :type '(alist :tag "Link display parameters"
  1579. :value-type plist)
  1580. :version "26.1"
  1581. :package-version '(Org . "9.1"))
  1582. (defun org-link-get-parameter (type key)
  1583. "Get TYPE link property for KEY.
  1584. TYPE is a string and KEY is a plist keyword."
  1585. (plist-get
  1586. (cdr (assoc type org-link-parameters))
  1587. key))
  1588. (defun org-link-set-parameters (type &rest parameters)
  1589. "Set link TYPE properties to PARAMETERS.
  1590. PARAMETERS should be :key val pairs."
  1591. (let ((data (assoc type org-link-parameters)))
  1592. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1593. (push (cons type parameters) org-link-parameters)
  1594. (org-make-link-regexps)
  1595. (org-element-update-syntax))))
  1596. (defun org-link-types ()
  1597. "Return a list of known link types."
  1598. (mapcar #'car org-link-parameters))
  1599. (defcustom org-link-abbrev-alist nil
  1600. "Alist of link abbreviations.
  1601. The car of each element is a string, to be replaced at the start of a link.
  1602. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1603. links in Org buffers can have an optional tag after a double colon, e.g.,
  1604. [[linkkey:tag][description]]
  1605. The `linkkey' must be a single word, starting with a letter, followed
  1606. by letters, numbers, `-' or `_'.
  1607. If REPLACE is a string, the tag will simply be appended to create the link.
  1608. If the string contains \"%s\", the tag will be inserted there. If the string
  1609. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1610. at that point (see the function `url-hexify-string'). If the string contains
  1611. the specifier \"%(my-function)\", then the custom function `my-function' will
  1612. be invoked: this function takes the tag as its only argument and must return
  1613. a string.
  1614. REPLACE may also be a function that will be called with the tag as the
  1615. only argument to create the link, which should be returned as a string.
  1616. See the manual for examples."
  1617. :group 'org-link
  1618. :type '(repeat
  1619. (cons
  1620. (string :tag "Protocol")
  1621. (choice
  1622. (string :tag "Format")
  1623. (function)))))
  1624. (defcustom org-descriptive-links t
  1625. "Non-nil means Org will display descriptive links.
  1626. E.g. [[https://orgmode.org][Org website]] will be displayed as
  1627. \"Org Website\", hiding the link itself and just displaying its
  1628. description. When set to nil, Org will display the full links
  1629. literally.
  1630. You can interactively set the value of this variable by calling
  1631. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1632. :group 'org-link
  1633. :type 'boolean)
  1634. (defcustom org-link-file-path-type 'adaptive
  1635. "How the path name in file links should be stored.
  1636. Valid values are:
  1637. relative Relative to the current directory, i.e. the directory of the file
  1638. into which the link is being inserted.
  1639. absolute Absolute path, if possible with ~ for home directory.
  1640. noabbrev Absolute path, no abbreviation of home directory.
  1641. adaptive Use relative path for files in the current directory and sub-
  1642. directories of it. For other files, use an absolute path."
  1643. :group 'org-link
  1644. :type '(choice
  1645. (const relative)
  1646. (const absolute)
  1647. (const noabbrev)
  1648. (const adaptive)))
  1649. (defvaralias 'org-activate-links 'org-highlight-links)
  1650. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1651. "Types of links that should be highlighted in Org files.
  1652. This is a list of symbols, each one of them leading to the
  1653. highlighting of a certain link type.
  1654. You can still open links that are not highlighted.
  1655. In principle, it does not hurt to turn on highlighting for all
  1656. link types. There may be a small gain when turning off unused
  1657. link types. The types are:
  1658. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1659. angle Links in angular brackets that may contain whitespace like
  1660. <bbdb:Carsten Dominik>.
  1661. plain Plain links in normal text, no whitespace, like http://google.com.
  1662. radio Text that is matched by a radio target, see manual for details.
  1663. tag Tag settings in a headline (link to tag search).
  1664. date Time stamps (link to calendar).
  1665. footnote Footnote labels.
  1666. If you set this variable during an Emacs session, use `org-mode-restart'
  1667. in the Org buffer so that the change takes effect."
  1668. :group 'org-link
  1669. :group 'org-appearance
  1670. :type '(set :greedy t
  1671. (const :tag "Double bracket links" bracket)
  1672. (const :tag "Angular bracket links" angle)
  1673. (const :tag "Plain text links" plain)
  1674. (const :tag "Radio target matches" radio)
  1675. (const :tag "Tags" tag)
  1676. (const :tag "Timestamps" date)
  1677. (const :tag "Footnotes" footnote)))
  1678. (defcustom org-make-link-description-function nil
  1679. "Function to use for generating link descriptions from links.
  1680. This function must take two parameters: the first one is the
  1681. link, the second one is the description generated by
  1682. `org-insert-link'. The function should return the description to
  1683. use."
  1684. :group 'org-link
  1685. :type '(choice (const nil) (function)))
  1686. (defgroup org-link-store nil
  1687. "Options concerning storing links in Org mode."
  1688. :tag "Org Store Link"
  1689. :group 'org-link)
  1690. (defcustom org-url-hexify-p t
  1691. "When non-nil, hexify URL when creating a link."
  1692. :type 'boolean
  1693. :version "24.3"
  1694. :group 'org-link-store)
  1695. (defcustom org-email-link-description-format "Email %c: %.30s"
  1696. "Format of the description part of a link to an email or usenet message.
  1697. The following %-escapes will be replaced by corresponding information:
  1698. %F full \"From\" field
  1699. %f name, taken from \"From\" field, address if no name
  1700. %T full \"To\" field
  1701. %t first name in \"To\" field, address if no name
  1702. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1703. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1704. %s subject
  1705. %d date
  1706. %m message-id.
  1707. You may use normal field width specification between the % and the letter.
  1708. This is for example useful to limit the length of the subject.
  1709. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1710. :group 'org-link-store
  1711. :type 'string)
  1712. (defcustom org-from-is-user-regexp
  1713. (let (r1 r2)
  1714. (when (and user-mail-address (not (string= user-mail-address "")))
  1715. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1716. (when (and user-full-name (not (string= user-full-name "")))
  1717. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1718. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1719. "Regexp matched against the \"From:\" header of an email or usenet message.
  1720. It should match if the message is from the user him/herself."
  1721. :group 'org-link-store
  1722. :type 'regexp)
  1723. (defcustom org-context-in-file-links t
  1724. "Non-nil means file links from `org-store-link' contain context.
  1725. \\<org-mode-map>
  1726. A search string will be added to the file name with :: as separator
  1727. and used to find the context when the link is activated by the command
  1728. `org-open-at-point'. When this option is t, the entire active region
  1729. will be placed in the search string of the file link. If set to a
  1730. positive integer, only the first n lines of context will be stored.
  1731. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1732. \\[org-store-link]')
  1733. negates this setting for the duration of the command."
  1734. :group 'org-link-store
  1735. :type '(choice boolean integer))
  1736. (defcustom org-keep-stored-link-after-insertion nil
  1737. "Non-nil means keep link in list for entire session.
  1738. \\<org-mode-map>
  1739. The command `org-store-link' adds a link pointing to the current
  1740. location to an internal list. These links accumulate during a session.
  1741. The command `org-insert-link' can be used to insert links into any
  1742. Org file (offering completion for all stored links).
  1743. When this option is nil, every link which has been inserted once using
  1744. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1745. unused
  1746. links more efficient."
  1747. :group 'org-link-store
  1748. :type 'boolean)
  1749. (defgroup org-link-follow nil
  1750. "Options concerning following links in Org mode."
  1751. :tag "Org Follow Link"
  1752. :group 'org-link)
  1753. (defcustom org-link-translation-function nil
  1754. "Function to translate links with different syntax to Org syntax.
  1755. This can be used to translate links created for example by the Planner
  1756. or emacs-wiki packages to Org syntax.
  1757. The function must accept two parameters, a TYPE containing the link
  1758. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1759. which is everything after the link protocol. It should return a cons
  1760. with possibly modified values of type and path.
  1761. Org contains a function for this, so if you set this variable to
  1762. `org-translate-link-from-planner', you should be able follow many
  1763. links created by planner."
  1764. :group 'org-link-follow
  1765. :type '(choice (const nil) (function)))
  1766. (defcustom org-follow-link-hook nil
  1767. "Hook that is run after a link has been followed."
  1768. :group 'org-link-follow
  1769. :type 'hook)
  1770. (defcustom org-tab-follows-link nil
  1771. "Non-nil means on links TAB will follow the link.
  1772. Needs to be set before org.el is loaded.
  1773. This really should not be used, it does not make sense, and the
  1774. implementation is bad."
  1775. :group 'org-link-follow
  1776. :type 'boolean)
  1777. (defcustom org-return-follows-link nil
  1778. "Non-nil means on links RET will follow the link.
  1779. In tables, the special behavior of RET has precedence."
  1780. :group 'org-link-follow
  1781. :type 'boolean)
  1782. (defcustom org-mouse-1-follows-link
  1783. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1784. "Non-nil means mouse-1 on a link will follow the link.
  1785. A longer mouse click will still set point. Needs to be set
  1786. before org.el is loaded."
  1787. :group 'org-link-follow
  1788. :version "26.1"
  1789. :package-version '(Org . "8.3")
  1790. :type '(choice
  1791. (const :tag "A double click follows the link" double)
  1792. (const :tag "Unconditionally follow the link with mouse-1" t)
  1793. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1794. (defcustom org-mark-ring-length 4
  1795. "Number of different positions to be recorded in the ring.
  1796. Changing this requires a restart of Emacs to work correctly."
  1797. :group 'org-link-follow
  1798. :type 'integer)
  1799. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1800. "Non-nil means internal fuzzy links can only match headlines.
  1801. When nil, the a fuzzy link may point to a target or a named
  1802. construct in the document. When set to the special value
  1803. `query-to-create', offer to create a new headline when none
  1804. matched.
  1805. Spaces and statistics cookies are ignored during heading searches."
  1806. :group 'org-link-follow
  1807. :version "24.1"
  1808. :type '(choice
  1809. (const :tag "Use fuzzy text search" nil)
  1810. (const :tag "Match only exact headline" t)
  1811. (const :tag "Match exact headline or query to create it"
  1812. query-to-create))
  1813. :safe #'symbolp)
  1814. (defcustom org-link-frame-setup
  1815. '((vm . vm-visit-folder-other-frame)
  1816. (vm-imap . vm-visit-imap-folder-other-frame)
  1817. (gnus . org-gnus-no-new-news)
  1818. (file . find-file-other-window)
  1819. (wl . wl-other-frame))
  1820. "Setup the frame configuration for following links.
  1821. When following a link with Emacs, it may often be useful to display
  1822. this link in another window or frame. This variable can be used to
  1823. set this up for the different types of links.
  1824. For VM, use any of
  1825. `vm-visit-folder'
  1826. `vm-visit-folder-other-window'
  1827. `vm-visit-folder-other-frame'
  1828. For Gnus, use any of
  1829. `gnus'
  1830. `gnus-other-frame'
  1831. `org-gnus-no-new-news'
  1832. For FILE, use any of
  1833. `find-file'
  1834. `find-file-other-window'
  1835. `find-file-other-frame'
  1836. For Wanderlust use any of
  1837. `wl'
  1838. `wl-other-frame'
  1839. For the calendar, use the variable `calendar-setup'.
  1840. For BBDB, it is currently only possible to display the matches in
  1841. another window."
  1842. :group 'org-link-follow
  1843. :type '(list
  1844. (cons (const vm)
  1845. (choice
  1846. (const vm-visit-folder)
  1847. (const vm-visit-folder-other-window)
  1848. (const vm-visit-folder-other-frame)))
  1849. (cons (const vm-imap)
  1850. (choice
  1851. (const vm-visit-imap-folder)
  1852. (const vm-visit-imap-folder-other-window)
  1853. (const vm-visit-imap-folder-other-frame)))
  1854. (cons (const gnus)
  1855. (choice
  1856. (const gnus)
  1857. (const gnus-other-frame)
  1858. (const org-gnus-no-new-news)))
  1859. (cons (const file)
  1860. (choice
  1861. (const find-file)
  1862. (const find-file-other-window)
  1863. (const find-file-other-frame)))
  1864. (cons (const wl)
  1865. (choice
  1866. (const wl)
  1867. (const wl-other-frame)))))
  1868. (defcustom org-display-internal-link-with-indirect-buffer nil
  1869. "Non-nil means use indirect buffer to display infile links.
  1870. Activating internal links (from one location in a file to another location
  1871. in the same file) normally just jumps to the location. When the link is
  1872. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1873. is displayed in
  1874. another window. When this option is set, the other window actually displays
  1875. an indirect buffer clone of the current buffer, to avoid any visibility
  1876. changes to the current buffer."
  1877. :group 'org-link-follow
  1878. :type 'boolean)
  1879. (defcustom org-open-non-existing-files nil
  1880. "Non-nil means `org-open-file' will open non-existing files.
  1881. When nil, an error will be generated.
  1882. This variable applies only to external applications because they
  1883. might choke on non-existing files. If the link is to a file that
  1884. will be opened in Emacs, the variable is ignored."
  1885. :group 'org-link-follow
  1886. :type 'boolean)
  1887. (defcustom org-open-directory-means-index-dot-org nil
  1888. "Non-nil means a link to a directory really means to index.org.
  1889. When nil, following a directory link will run dired or open a finder/explorer
  1890. window on that directory."
  1891. :group 'org-link-follow
  1892. :type 'boolean)
  1893. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1894. "Non-nil means ask for confirmation before executing shell links.
  1895. Shell links can be dangerous: just think about a link
  1896. [[shell:rm -rf ~/*][Google Search]]
  1897. This link would show up in your Org document as \"Google Search\",
  1898. but really it would remove your entire home directory.
  1899. Therefore we advise against setting this variable to nil.
  1900. Just change it to `y-or-n-p' if you want to confirm with a
  1901. single keystroke rather than having to type \"yes\"."
  1902. :group 'org-link-follow
  1903. :type '(choice
  1904. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1905. (const :tag "with y-or-n (faster)" y-or-n-p)
  1906. (const :tag "no confirmation (dangerous)" nil)))
  1907. (put 'org-confirm-shell-link-function
  1908. 'safe-local-variable
  1909. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1910. (defcustom org-confirm-shell-link-not-regexp ""
  1911. "A regexp to skip confirmation for shell links."
  1912. :group 'org-link-follow
  1913. :version "24.1"
  1914. :type 'regexp)
  1915. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1916. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1917. Elisp links can be dangerous: just think about a link
  1918. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1919. This link would show up in your Org document as \"Google Search\",
  1920. but really it would remove your entire home directory.
  1921. Therefore we advise against setting this variable to nil.
  1922. Just change it to `y-or-n-p' if you want to confirm with a
  1923. single keystroke rather than having to type \"yes\"."
  1924. :group 'org-link-follow
  1925. :type '(choice
  1926. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1927. (const :tag "with y-or-n (faster)" y-or-n-p)
  1928. (const :tag "no confirmation (dangerous)" nil)))
  1929. (put 'org-confirm-shell-link-function
  1930. 'safe-local-variable
  1931. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1932. (defcustom org-confirm-elisp-link-not-regexp ""
  1933. "A regexp to skip confirmation for Elisp links."
  1934. :group 'org-link-follow
  1935. :version "24.1"
  1936. :type 'regexp)
  1937. (defconst org-file-apps-defaults-gnu
  1938. '((remote . emacs)
  1939. (system . mailcap)
  1940. (t . mailcap))
  1941. "Default file applications on a UNIX or GNU/Linux system.
  1942. See `org-file-apps'.")
  1943. (defconst org-file-apps-defaults-macosx
  1944. '((remote . emacs)
  1945. (system . "open %s")
  1946. ("ps.gz" . "gv %s")
  1947. ("eps.gz" . "gv %s")
  1948. ("dvi" . "xdvi %s")
  1949. ("fig" . "xfig %s")
  1950. (t . "open %s"))
  1951. "Default file applications on a macOS system.
  1952. The system \"open\" is known as a default, but we use X11 applications
  1953. for some files for which the OS does not have a good default.
  1954. See `org-file-apps'.")
  1955. (defconst org-file-apps-defaults-windowsnt
  1956. (list '(remote . emacs)
  1957. (cons 'system (lambda (file _path)
  1958. (with-no-warnings (w32-shell-execute "open" file))))
  1959. (cons t (lambda (file _path)
  1960. (with-no-warnings (w32-shell-execute "open" file)))))
  1961. "Default file applications on a Windows NT system.
  1962. The system \"open\" is used for most files.
  1963. See `org-file-apps'.")
  1964. (defcustom org-file-apps
  1965. '((auto-mode . emacs)
  1966. ("\\.mm\\'" . default)
  1967. ("\\.x?html?\\'" . default)
  1968. ("\\.pdf\\'" . default))
  1969. "External applications for opening `file:path' items in a document.
  1970. \\<org-mode-map>\
  1971. Org mode uses system defaults for different file types, but
  1972. you can use this variable to set the application for a given file
  1973. extension. The entries in this list are cons cells where the car identifies
  1974. files and the cdr the corresponding command.
  1975. Possible values for the file identifier are:
  1976. \"string\" A string as a file identifier can be interpreted in different
  1977. ways, depending on its contents:
  1978. - Alphanumeric characters only:
  1979. Match links with this file extension.
  1980. Example: (\"pdf\" . \"evince %s\")
  1981. to open PDFs with evince.
  1982. - Regular expression: Match links where the
  1983. filename matches the regexp. If you want to
  1984. use groups here, use shy groups.
  1985. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1986. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1987. to open *.html and *.xhtml with firefox.
  1988. - Regular expression which contains (non-shy) groups:
  1989. Match links where the whole link, including \"::\", and
  1990. anything after that, matches the regexp.
  1991. In a custom command string, %1, %2, etc. are replaced with
  1992. the parts of the link that were matched by the groups.
  1993. For backwards compatibility, if a command string is given
  1994. that does not use any of the group matches, this case is
  1995. handled identically to the second one (i.e. match against
  1996. file name only).
  1997. In a custom function, you can access the group matches with
  1998. (match-string n link).
  1999. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  2000. \"evince -p %1 %s\")
  2001. to open [[file:document.pdf::5]] with evince at page 5.
  2002. `directory' Matches a directory
  2003. `remote' Matches a remote file, accessible through tramp or efs.
  2004. Remote files most likely should be visited through Emacs
  2005. because external applications cannot handle such paths.
  2006. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  2007. so all files Emacs knows how to handle. Using this with
  2008. command `emacs' will open most files in Emacs. Beware that this
  2009. will also open html files inside Emacs, unless you add
  2010. (\"html\" . default) to the list as well.
  2011. `system' The system command to open files, like `open' on Windows
  2012. and macOS, and mailcap under GNU/Linux. This is the command
  2013. that will be selected if you call `org-open-at-point' with a
  2014. double prefix argument (`\\[universal-argument] \
  2015. \\[universal-argument] \\[org-open-at-point]').
  2016. t Default for files not matched by any of the other options.
  2017. Possible values for the command are:
  2018. `emacs' The file will be visited by the current Emacs process.
  2019. `default' Use the default application for this file type, which is the
  2020. association for t in the list, most likely in the system-specific
  2021. part. This can be used to overrule an unwanted setting in the
  2022. system-specific variable.
  2023. `system' Use the system command for opening files, like \"open\".
  2024. This command is specified by the entry whose car is `system'.
  2025. Most likely, the system-specific version of this variable
  2026. does define this command, but you can overrule/replace it
  2027. here.
  2028. `mailcap' Use command specified in the mailcaps.
  2029. string A command to be executed by a shell; %s will be replaced
  2030. by the path to the file.
  2031. function A Lisp function, which will be called with two arguments:
  2032. the file path and the original link string, without the
  2033. \"file:\" prefix.
  2034. For more examples, see the system specific constants
  2035. `org-file-apps-defaults-macosx'
  2036. `org-file-apps-defaults-windowsnt'
  2037. `org-file-apps-defaults-gnu'."
  2038. :group 'org-link-follow
  2039. :type '(repeat
  2040. (cons (choice :value ""
  2041. (string :tag "Extension")
  2042. (const :tag "System command to open files" system)
  2043. (const :tag "Default for unrecognized files" t)
  2044. (const :tag "Remote file" remote)
  2045. (const :tag "Links to a directory" directory)
  2046. (const :tag "Any files that have Emacs modes"
  2047. auto-mode))
  2048. (choice :value ""
  2049. (const :tag "Visit with Emacs" emacs)
  2050. (const :tag "Use default" default)
  2051. (const :tag "Use the system command" system)
  2052. (string :tag "Command")
  2053. (function :tag "Function")))))
  2054. (defcustom org-doi-server-url "http://dx.doi.org/"
  2055. "The URL of the DOI server."
  2056. :type 'string
  2057. :version "24.3"
  2058. :group 'org-link-follow)
  2059. (defgroup org-refile nil
  2060. "Options concerning refiling entries in Org mode."
  2061. :tag "Org Refile"
  2062. :group 'org)
  2063. (defcustom org-directory "~/org"
  2064. "Directory with Org files.
  2065. This is just a default location to look for Org files. There is no need
  2066. at all to put your files into this directory. It is used in the
  2067. following situations:
  2068. 1. When a capture template specifies a target file that is not an
  2069. absolute path. The path will then be interpreted relative to
  2070. `org-directory'
  2071. 2. When the value of variable `org-agenda-files' is a single file, any
  2072. relative paths in this file will be taken as relative to
  2073. `org-directory'."
  2074. :group 'org-refile
  2075. :group 'org-capture
  2076. :type 'directory)
  2077. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2078. "Default target for storing notes.
  2079. Used as a fall back file for org-capture.el, for templates that
  2080. do not specify a target file."
  2081. :group 'org-refile
  2082. :group 'org-capture
  2083. :type 'file)
  2084. (defcustom org-reverse-note-order nil
  2085. "Non-nil means store new notes at the beginning of a file or entry.
  2086. When nil, new notes will be filed to the end of a file or entry.
  2087. This can also be a list with cons cells of regular expressions that
  2088. are matched against file names, and values."
  2089. :group 'org-capture
  2090. :group 'org-refile
  2091. :type '(choice
  2092. (const :tag "Reverse always" t)
  2093. (const :tag "Reverse never" nil)
  2094. (repeat :tag "By file name regexp"
  2095. (cons regexp boolean))))
  2096. (defcustom org-log-refile nil
  2097. "Information to record when a task is refiled.
  2098. Possible values are:
  2099. nil Don't add anything
  2100. time Add a time stamp to the task
  2101. note Prompt for a note and add it with template `org-log-note-headings'
  2102. This option can also be set with on a per-file-basis with
  2103. #+STARTUP: nologrefile
  2104. #+STARTUP: logrefile
  2105. #+STARTUP: lognoterefile
  2106. You can have local logging settings for a subtree by setting the LOGGING
  2107. property to one or more of these keywords.
  2108. When bulk-refiling from the agenda, the value `note' is forbidden and
  2109. will temporarily be changed to `time'."
  2110. :group 'org-refile
  2111. :group 'org-progress
  2112. :version "24.1"
  2113. :type '(choice
  2114. (const :tag "No logging" nil)
  2115. (const :tag "Record timestamp" time)
  2116. (const :tag "Record timestamp with note." note)))
  2117. (defcustom org-refile-targets nil
  2118. "Targets for refiling entries with `\\[org-refile]'.
  2119. This is a list of cons cells. Each cell contains:
  2120. - a specification of the files to be considered, either a list of files,
  2121. or a symbol whose function or variable value will be used to retrieve
  2122. a file name or a list of file names. If you use `org-agenda-files' for
  2123. that, all agenda files will be scanned for targets. Nil means consider
  2124. headings in the current buffer.
  2125. - A specification of how to find candidate refile targets. This may be
  2126. any of:
  2127. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2128. This tag has to be present in all target headlines, inheritance will
  2129. not be considered.
  2130. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2131. todo keyword.
  2132. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2133. headlines that are refiling targets.
  2134. - a cons cell (:level . N). Any headline of level N is considered a target.
  2135. Note that, when `org-odd-levels-only' is set, level corresponds to
  2136. order in hierarchy, not to the number of stars.
  2137. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2138. Note that, when `org-odd-levels-only' is set, level corresponds to
  2139. order in hierarchy, not to the number of stars.
  2140. Each element of this list generates a set of possible targets.
  2141. The union of these sets is presented (with completion) to
  2142. the user by `org-refile'.
  2143. You can set the variable `org-refile-target-verify-function' to a function
  2144. to verify each headline found by the simple criteria above.
  2145. When this variable is nil, all top-level headlines in the current buffer
  2146. are used, equivalent to the value `((nil . (:level . 1))'."
  2147. :group 'org-refile
  2148. :type '(repeat
  2149. (cons
  2150. (choice :value org-agenda-files
  2151. (const :tag "All agenda files" org-agenda-files)
  2152. (const :tag "Current buffer" nil)
  2153. (function) (variable) (file))
  2154. (choice :tag "Identify target headline by"
  2155. (cons :tag "Specific tag" (const :value :tag) (string))
  2156. (cons :tag "TODO keyword" (const :value :todo) (string))
  2157. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2158. (cons :tag "Level number" (const :value :level) (integer))
  2159. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2160. (defcustom org-refile-target-verify-function nil
  2161. "Function to verify if the headline at point should be a refile target.
  2162. The function will be called without arguments, with point at the
  2163. beginning of the headline. It should return t and leave point
  2164. where it is if the headline is a valid target for refiling.
  2165. If the target should not be selected, the function must return nil.
  2166. In addition to this, it may move point to a place from where the search
  2167. should be continued. For example, the function may decide that the entire
  2168. subtree of the current entry should be excluded and move point to the end
  2169. of the subtree."
  2170. :group 'org-refile
  2171. :type '(choice
  2172. (const nil)
  2173. (function)))
  2174. (defcustom org-refile-use-cache nil
  2175. "Non-nil means cache refile targets to speed up the process.
  2176. \\<org-mode-map>\
  2177. The cache for a particular file will be updated automatically when
  2178. the buffer has been killed, or when any of the marker used for flagging
  2179. refile targets no longer points at a live buffer.
  2180. If you have added new entries to a buffer that might themselves be targets,
  2181. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2182. if you find that easier, \
  2183. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2184. \\[org-refile]'."
  2185. :group 'org-refile
  2186. :version "24.1"
  2187. :type 'boolean)
  2188. (defcustom org-refile-use-outline-path nil
  2189. "Non-nil means provide refile targets as paths.
  2190. So a level 3 headline will be available as level1/level2/level3.
  2191. When the value is `file', also include the file name (without directory)
  2192. into the path. In this case, you can also stop the completion after
  2193. the file name, to get entries inserted as top level in the file.
  2194. When `full-file-path', include the full file path.
  2195. When `buffer-name', use the buffer name."
  2196. :group 'org-refile
  2197. :type '(choice
  2198. (const :tag "Not" nil)
  2199. (const :tag "Yes" t)
  2200. (const :tag "Start with file name" file)
  2201. (const :tag "Start with full file path" full-file-path)
  2202. (const :tag "Start with buffer name" buffer-name)))
  2203. (defcustom org-outline-path-complete-in-steps t
  2204. "Non-nil means complete the outline path in hierarchical steps.
  2205. When Org uses the refile interface to select an outline path (see
  2206. `org-refile-use-outline-path'), the completion of the path can be
  2207. done in a single go, or it can be done in steps down the headline
  2208. hierarchy. Going in steps is probably the best if you do not use
  2209. a special completion package like `ido' or `icicles'. However,
  2210. when using these packages, going in one step can be very fast,
  2211. while still showing the whole path to the entry."
  2212. :group 'org-refile
  2213. :type 'boolean)
  2214. (defcustom org-refile-allow-creating-parent-nodes nil
  2215. "Non-nil means allow the creation of new nodes as refile targets.
  2216. New nodes are then created by adding \"/new node name\" to the completion
  2217. of an existing node. When the value of this variable is `confirm',
  2218. new node creation must be confirmed by the user (recommended).
  2219. When nil, the completion must match an existing entry.
  2220. Note that, if the new heading is not seen by the criteria
  2221. listed in `org-refile-targets', multiple instances of the same
  2222. heading would be created by trying again to file under the new
  2223. heading."
  2224. :group 'org-refile
  2225. :type '(choice
  2226. (const :tag "Never" nil)
  2227. (const :tag "Always" t)
  2228. (const :tag "Prompt for confirmation" confirm)))
  2229. (defcustom org-refile-active-region-within-subtree nil
  2230. "Non-nil means also refile active region within a subtree.
  2231. By default `org-refile' doesn't allow refiling regions if they
  2232. don't contain a set of subtrees, but it might be convenient to
  2233. do so sometimes: in that case, the first line of the region is
  2234. converted to a headline before refiling."
  2235. :group 'org-refile
  2236. :version "24.1"
  2237. :type 'boolean)
  2238. (defgroup org-todo nil
  2239. "Options concerning TODO items in Org mode."
  2240. :tag "Org TODO"
  2241. :group 'org)
  2242. (defgroup org-progress nil
  2243. "Options concerning Progress logging in Org mode."
  2244. :tag "Org Progress"
  2245. :group 'org-time)
  2246. (defvar org-todo-interpretation-widgets
  2247. '((:tag "Sequence (cycling hits every state)" sequence)
  2248. (:tag "Type (cycling directly to DONE)" type))
  2249. "The available interpretation symbols for customizing `org-todo-keywords'.
  2250. Interested libraries should add to this list.")
  2251. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2252. "List of TODO entry keyword sequences and their interpretation.
  2253. \\<org-mode-map>This is a list of sequences.
  2254. Each sequence starts with a symbol, either `sequence' or `type',
  2255. indicating if the keywords should be interpreted as a sequence of
  2256. action steps, or as different types of TODO items. The first
  2257. keywords are states requiring action - these states will select a headline
  2258. for inclusion into the global TODO list Org produces. If one of the
  2259. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2260. signify that no further action is necessary. If \"|\" is not found,
  2261. the last keyword is treated as the only DONE state of the sequence.
  2262. The command `\\[org-todo]' cycles an entry through these states, and one
  2263. additional state where no keyword is present. For details about this
  2264. cycling, see the manual.
  2265. TODO keywords and interpretation can also be set on a per-file basis with
  2266. the special #+SEQ_TODO and #+TYP_TODO lines.
  2267. Each keyword can optionally specify a character for fast state selection
  2268. \(in combination with the variable `org-use-fast-todo-selection')
  2269. and specifiers for state change logging, using the same syntax that
  2270. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2271. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2272. indicates to record a time stamp each time this state is selected.
  2273. Each keyword may also specify if a timestamp or a note should be
  2274. recorded when entering or leaving the state, by adding additional
  2275. characters in the parenthesis after the keyword. This looks like this:
  2276. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2277. record only the time of the state change. With X and Y being either
  2278. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2279. Y when leaving the state if and only if the *target* state does not
  2280. define X. You may omit any of the fast-selection key or X or /Y,
  2281. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2282. For backward compatibility, this variable may also be just a list
  2283. of keywords. In this case the interpretation (sequence or type) will be
  2284. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2285. :group 'org-todo
  2286. :group 'org-keywords
  2287. :type '(choice
  2288. (repeat :tag "Old syntax, just keywords"
  2289. (string :tag "Keyword"))
  2290. (repeat :tag "New syntax"
  2291. (cons
  2292. (choice
  2293. :tag "Interpretation"
  2294. ;;Quick and dirty way to see
  2295. ;;`org-todo-interpretations'. This takes the
  2296. ;;place of item arguments
  2297. :convert-widget
  2298. (lambda (widget)
  2299. (widget-put widget
  2300. :args (mapcar
  2301. (lambda (x)
  2302. (widget-convert
  2303. (cons 'const x)))
  2304. org-todo-interpretation-widgets))
  2305. widget))
  2306. (repeat
  2307. (string :tag "Keyword"))))))
  2308. (defvar-local org-todo-keywords-1 nil
  2309. "All TODO and DONE keywords active in a buffer.")
  2310. (defvar org-todo-keywords-for-agenda nil)
  2311. (defvar org-done-keywords-for-agenda nil)
  2312. (defvar org-todo-keyword-alist-for-agenda nil)
  2313. (defvar org-tag-alist-for-agenda nil
  2314. "Alist of all tags from all agenda files.")
  2315. (defvar org-tag-groups-alist-for-agenda nil
  2316. "Alist of all groups tags from all current agenda files.")
  2317. (defvar-local org-tag-groups-alist nil)
  2318. (defvar org-agenda-contributing-files nil)
  2319. (defvar-local org-current-tag-alist nil
  2320. "Alist of all tag groups in current buffer.
  2321. This variable takes into consideration `org-tag-alist',
  2322. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2323. (defvar-local org-not-done-keywords nil)
  2324. (defvar-local org-done-keywords nil)
  2325. (defvar-local org-todo-heads nil)
  2326. (defvar-local org-todo-sets nil)
  2327. (defvar-local org-todo-log-states nil)
  2328. (defvar-local org-todo-kwd-alist nil)
  2329. (defvar-local org-todo-key-alist nil)
  2330. (defvar-local org-todo-key-trigger nil)
  2331. (defcustom org-todo-interpretation 'sequence
  2332. "Controls how TODO keywords are interpreted.
  2333. This variable is in principle obsolete and is only used for
  2334. backward compatibility, if the interpretation of todo keywords is
  2335. not given already in `org-todo-keywords'. See that variable for
  2336. more information."
  2337. :group 'org-todo
  2338. :group 'org-keywords
  2339. :type '(choice (const sequence)
  2340. (const type)))
  2341. (defcustom org-use-fast-todo-selection t
  2342. "\\<org-mode-map>\
  2343. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2344. This variable describes if and under what circumstances the cycling
  2345. mechanism for TODO keywords will be replaced by a single-key, direct
  2346. selection scheme.
  2347. When nil, fast selection is never used.
  2348. When the symbol `prefix', it will be used when `org-todo' is called
  2349. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2350. in an Org buffer, and
  2351. `\\[universal-argument] t' in an agenda buffer.
  2352. When t, fast selection is used by default. In this case, the prefix
  2353. argument forces cycling instead.
  2354. In all cases, the special interface is only used if access keys have
  2355. actually been assigned by the user, i.e. if keywords in the configuration
  2356. are followed by a letter in parenthesis, like TODO(t)."
  2357. :group 'org-todo
  2358. :type '(choice
  2359. (const :tag "Never" nil)
  2360. (const :tag "By default" t)
  2361. (const :tag "Only with C-u C-c C-t" prefix)))
  2362. (defcustom org-provide-todo-statistics t
  2363. "Non-nil means update todo statistics after insert and toggle.
  2364. ALL-HEADLINES means update todo statistics by including headlines
  2365. with no TODO keyword as well, counting them as not done.
  2366. A list of TODO keywords means the same, but skip keywords that are
  2367. not in this list.
  2368. When set to a list of two lists, the first list contains keywords
  2369. to consider as TODO keywords, the second list contains keywords
  2370. to consider as DONE keywords.
  2371. When this is set, todo statistics is updated in the parent of the
  2372. current entry each time a todo state is changed."
  2373. :group 'org-todo
  2374. :type '(choice
  2375. (const :tag "Yes, only for TODO entries" t)
  2376. (const :tag "Yes, including all entries" all-headlines)
  2377. (repeat :tag "Yes, for TODOs in this list"
  2378. (string :tag "TODO keyword"))
  2379. (list :tag "Yes, for TODOs and DONEs in these lists"
  2380. (repeat (string :tag "TODO keyword"))
  2381. (repeat (string :tag "DONE keyword")))
  2382. (other :tag "No TODO statistics" nil)))
  2383. (defcustom org-hierarchical-todo-statistics t
  2384. "Non-nil means TODO statistics covers just direct children.
  2385. When nil, all entries in the subtree are considered.
  2386. This has only an effect if `org-provide-todo-statistics' is set.
  2387. To set this to nil for only a single subtree, use a COOKIE_DATA
  2388. property and include the word \"recursive\" into the value."
  2389. :group 'org-todo
  2390. :type 'boolean)
  2391. (defcustom org-after-todo-state-change-hook nil
  2392. "Hook which is run after the state of a TODO item was changed.
  2393. The new state (a string with a TODO keyword, or nil) is available in the
  2394. Lisp variable `org-state'."
  2395. :group 'org-todo
  2396. :type 'hook)
  2397. (defvar org-blocker-hook nil
  2398. "Hook for functions that are allowed to block a state change.
  2399. Functions in this hook should not modify the buffer.
  2400. Each function gets as its single argument a property list,
  2401. see `org-trigger-hook' for more information about this list.
  2402. If any of the functions in this hook returns nil, the state change
  2403. is blocked.")
  2404. (defvar org-trigger-hook nil
  2405. "Hook for functions that are triggered by a state change.
  2406. Each function gets as its single argument a property list with at
  2407. least the following elements:
  2408. (:type type-of-change :position pos-at-entry-start
  2409. :from old-state :to new-state)
  2410. Depending on the type, more properties may be present.
  2411. This mechanism is currently implemented for:
  2412. TODO state changes
  2413. ------------------
  2414. :type todo-state-change
  2415. :from previous state (keyword as a string), or nil, or a symbol
  2416. `todo' or `done', to indicate the general type of state.
  2417. :to new state, like in :from")
  2418. (defcustom org-enforce-todo-dependencies nil
  2419. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2420. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2421. be blocked if any prior sibling is not yet done.
  2422. Finally, if the parent is blocked because of ordered siblings of its own,
  2423. the child will also be blocked."
  2424. :set (lambda (var val)
  2425. (set var val)
  2426. (if val
  2427. (add-hook 'org-blocker-hook
  2428. 'org-block-todo-from-children-or-siblings-or-parent)
  2429. (remove-hook 'org-blocker-hook
  2430. 'org-block-todo-from-children-or-siblings-or-parent)))
  2431. :group 'org-todo
  2432. :type 'boolean)
  2433. (defcustom org-enforce-todo-checkbox-dependencies nil
  2434. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2435. When this is nil, checkboxes have no influence on switching TODO states.
  2436. When non-nil, you first need to check off all check boxes before the TODO
  2437. entry can be switched to DONE.
  2438. This variable needs to be set before org.el is loaded, and you need to
  2439. restart Emacs after a change to make the change effective. The only way
  2440. to change is while Emacs is running is through the customize interface."
  2441. :set (lambda (var val)
  2442. (set var val)
  2443. (if val
  2444. (add-hook 'org-blocker-hook
  2445. 'org-block-todo-from-checkboxes)
  2446. (remove-hook 'org-blocker-hook
  2447. 'org-block-todo-from-checkboxes)))
  2448. :group 'org-todo
  2449. :type 'boolean)
  2450. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2451. "Non-nil means inserting a TODO heading is treated as state change.
  2452. So when the command `\\[org-insert-todo-heading]' is used, state change
  2453. logging will apply if appropriate. When nil, the new TODO item will
  2454. be inserted directly, and no logging will take place."
  2455. :group 'org-todo
  2456. :type 'boolean)
  2457. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2458. "Non-nil means switching TODO states with S-cursor counts as state change.
  2459. This is the default behavior. However, setting this to nil allows a
  2460. convenient way to select a TODO state and bypass any logging associated
  2461. with that."
  2462. :group 'org-todo
  2463. :type 'boolean)
  2464. (defcustom org-todo-state-tags-triggers nil
  2465. "Tag changes that should be triggered by TODO state changes.
  2466. This is a list. Each entry is
  2467. (state-change (tag . flag) .......)
  2468. State-change can be a string with a state, and empty string to indicate the
  2469. state that has no TODO keyword, or it can be one of the symbols `todo'
  2470. or `done', meaning any not-done or done state, respectively."
  2471. :group 'org-todo
  2472. :group 'org-tags
  2473. :type '(repeat
  2474. (cons (choice :tag "When changing to"
  2475. (const :tag "Not-done state" todo)
  2476. (const :tag "Done state" done)
  2477. (string :tag "State"))
  2478. (repeat
  2479. (cons :tag "Tag action"
  2480. (string :tag "Tag")
  2481. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2482. (defcustom org-log-done nil
  2483. "Information to record when a task moves to the DONE state.
  2484. Possible values are:
  2485. nil Don't add anything, just change the keyword
  2486. time Add a time stamp to the task
  2487. note Prompt for a note and add it with template `org-log-note-headings'
  2488. This option can also be set with on a per-file-basis with
  2489. #+STARTUP: nologdone
  2490. #+STARTUP: logdone
  2491. #+STARTUP: lognotedone
  2492. You can have local logging settings for a subtree by setting the LOGGING
  2493. property to one or more of these keywords."
  2494. :group 'org-todo
  2495. :group 'org-progress
  2496. :type '(choice
  2497. (const :tag "No logging" nil)
  2498. (const :tag "Record CLOSED timestamp" time)
  2499. (const :tag "Record CLOSED timestamp with note." note)))
  2500. ;; Normalize old uses of org-log-done.
  2501. (cond
  2502. ((eq org-log-done t) (setq org-log-done 'time))
  2503. ((and (listp org-log-done) (memq 'done org-log-done))
  2504. (setq org-log-done 'note)))
  2505. (defcustom org-log-reschedule nil
  2506. "Information to record when the scheduling date of a tasks is modified.
  2507. Possible values are:
  2508. nil Don't add anything, just change the date
  2509. time Add a time stamp to the task
  2510. note Prompt for a note and add it with template `org-log-note-headings'
  2511. This option can also be set with on a per-file-basis with
  2512. #+STARTUP: nologreschedule
  2513. #+STARTUP: logreschedule
  2514. #+STARTUP: lognotereschedule"
  2515. :group 'org-todo
  2516. :group 'org-progress
  2517. :type '(choice
  2518. (const :tag "No logging" nil)
  2519. (const :tag "Record timestamp" time)
  2520. (const :tag "Record timestamp with note." note)))
  2521. (defcustom org-log-redeadline nil
  2522. "Information to record when the deadline date of a tasks is modified.
  2523. Possible values are:
  2524. nil Don't add anything, just change the date
  2525. time Add a time stamp to the task
  2526. note Prompt for a note and add it with template `org-log-note-headings'
  2527. This option can also be set with on a per-file-basis with
  2528. #+STARTUP: nologredeadline
  2529. #+STARTUP: logredeadline
  2530. #+STARTUP: lognoteredeadline
  2531. You can have local logging settings for a subtree by setting the LOGGING
  2532. property to one or more of these keywords."
  2533. :group 'org-todo
  2534. :group 'org-progress
  2535. :type '(choice
  2536. (const :tag "No logging" nil)
  2537. (const :tag "Record timestamp" time)
  2538. (const :tag "Record timestamp with note." note)))
  2539. (defcustom org-log-note-clock-out nil
  2540. "Non-nil means record a note when clocking out of an item.
  2541. This can also be configured on a per-file basis by adding one of
  2542. the following lines anywhere in the buffer:
  2543. #+STARTUP: lognoteclock-out
  2544. #+STARTUP: nolognoteclock-out"
  2545. :group 'org-todo
  2546. :group 'org-progress
  2547. :type 'boolean)
  2548. (defcustom org-log-done-with-time t
  2549. "Non-nil means the CLOSED time stamp will contain date and time.
  2550. When nil, only the date will be recorded."
  2551. :group 'org-progress
  2552. :type 'boolean)
  2553. (defcustom org-log-note-headings
  2554. '((done . "CLOSING NOTE %t")
  2555. (state . "State %-12s from %-12S %t")
  2556. (note . "Note taken on %t")
  2557. (reschedule . "Rescheduled from %S on %t")
  2558. (delschedule . "Not scheduled, was %S on %t")
  2559. (redeadline . "New deadline from %S on %t")
  2560. (deldeadline . "Removed deadline, was %S on %t")
  2561. (refile . "Refiled on %t")
  2562. (clock-out . ""))
  2563. "Headings for notes added to entries.
  2564. The value is an alist, with the car being a symbol indicating the
  2565. note context, and the cdr is the heading to be used. The heading
  2566. may also be the empty string. The following placeholders can be
  2567. used:
  2568. %t a time stamp.
  2569. %T an active time stamp instead the default inactive one
  2570. %d a short-format time stamp.
  2571. %D an active short-format time stamp.
  2572. %s the new TODO state or time stamp (inactive), in double quotes.
  2573. %S the old TODO state or time stamp (inactive), in double quotes.
  2574. %u the user name.
  2575. %U full user name.
  2576. In fact, it is not a good idea to change the `state' entry,
  2577. because Agenda Log mode depends on the format of these entries."
  2578. :group 'org-todo
  2579. :group 'org-progress
  2580. :type '(list :greedy t
  2581. (cons (const :tag "Heading when closing an item" done) string)
  2582. (cons (const :tag
  2583. "Heading when changing todo state (todo sequence only)"
  2584. state) string)
  2585. (cons (const :tag "Heading when just taking a note" note) string)
  2586. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2587. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2588. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2589. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2590. (cons (const :tag "Heading when refiling" refile) string)
  2591. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2592. (unless (assq 'note org-log-note-headings)
  2593. (push '(note . "%t") org-log-note-headings))
  2594. (defcustom org-log-into-drawer nil
  2595. "Non-nil means insert state change notes and time stamps into a drawer.
  2596. When nil, state changes notes will be inserted after the headline and
  2597. any scheduling and clock lines, but not inside a drawer.
  2598. The value of this variable should be the name of the drawer to use.
  2599. LOGBOOK is proposed as the default drawer for this purpose, you can
  2600. also set this to a string to define the drawer of your choice.
  2601. A value of t is also allowed, representing \"LOGBOOK\".
  2602. A value of t or nil can also be set with on a per-file-basis with
  2603. #+STARTUP: logdrawer
  2604. #+STARTUP: nologdrawer
  2605. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2606. will be ignored.
  2607. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2608. a subtree.
  2609. Do not check directly this variable in a Lisp program. Call
  2610. function `org-log-into-drawer' instead."
  2611. :group 'org-todo
  2612. :group 'org-progress
  2613. :type '(choice
  2614. (const :tag "Not into a drawer" nil)
  2615. (const :tag "LOGBOOK" t)
  2616. (string :tag "Other")))
  2617. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2618. (defun org-log-into-drawer ()
  2619. "Name of the log drawer, as a string, or nil.
  2620. This is the value of `org-log-into-drawer'. However, if the
  2621. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2622. be used instead of the default value."
  2623. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2624. (cond ((equal p "nil") nil)
  2625. ((equal p "t") "LOGBOOK")
  2626. ((stringp p) p)
  2627. (p "LOGBOOK")
  2628. ((stringp org-log-into-drawer) org-log-into-drawer)
  2629. (org-log-into-drawer "LOGBOOK"))))
  2630. (defcustom org-log-state-notes-insert-after-drawers nil
  2631. "Non-nil means insert state change notes after any drawers in entry.
  2632. Only the drawers that *immediately* follow the headline and the
  2633. deadline/scheduled line are skipped.
  2634. When nil, insert notes right after the heading and perhaps the line
  2635. with deadline/scheduling if present.
  2636. This variable will have no effect if `org-log-into-drawer' is
  2637. set."
  2638. :group 'org-todo
  2639. :group 'org-progress
  2640. :type 'boolean)
  2641. (defcustom org-log-states-order-reversed t
  2642. "Non-nil means the latest state note will be directly after heading.
  2643. When nil, the state change notes will be ordered according to time.
  2644. This option can also be set with on a per-file-basis with
  2645. #+STARTUP: logstatesreversed
  2646. #+STARTUP: nologstatesreversed"
  2647. :group 'org-todo
  2648. :group 'org-progress
  2649. :type 'boolean)
  2650. (defcustom org-todo-repeat-to-state nil
  2651. "The TODO state to which a repeater should return the repeating task.
  2652. By default this is the first task of a TODO sequence or the
  2653. previous state of a TYPE_TODO set. But you can specify to use
  2654. the previous state in a TODO sequence or a string.
  2655. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2656. entry, which has precedence over this option."
  2657. :group 'org-todo
  2658. :version "24.1"
  2659. :type '(choice (const :tag "Use the previous TODO state" t)
  2660. (const :tag "Use the head of the TODO sequence" nil)
  2661. (string :tag "Use a specific TODO state")))
  2662. (defcustom org-log-repeat 'time
  2663. "Non-nil means record moving through the DONE state when triggering repeat.
  2664. An auto-repeating task is immediately switched back to TODO when
  2665. marked DONE. If you are not logging state changes (by adding \"@\"
  2666. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2667. record a closing note, there will be no record of the task moving
  2668. through DONE. This variable forces taking a note anyway.
  2669. nil Don't force a record
  2670. time Record a time stamp
  2671. note Prompt for a note and add it with template `org-log-note-headings'
  2672. This option can also be set with on a per-file-basis with
  2673. #+STARTUP: nologrepeat
  2674. #+STARTUP: logrepeat
  2675. #+STARTUP: lognoterepeat
  2676. You can have local logging settings for a subtree by setting the LOGGING
  2677. property to one or more of these keywords."
  2678. :group 'org-todo
  2679. :group 'org-progress
  2680. :type '(choice
  2681. (const :tag "Don't force a record" nil)
  2682. (const :tag "Force recording the DONE state" time)
  2683. (const :tag "Force recording a note with the DONE state" note)))
  2684. (defgroup org-priorities nil
  2685. "Priorities in Org mode."
  2686. :tag "Org Priorities"
  2687. :group 'org-todo)
  2688. (defcustom org-enable-priority-commands t
  2689. "Non-nil means priority commands are active.
  2690. When nil, these commands will be disabled, so that you never accidentally
  2691. set a priority."
  2692. :group 'org-priorities
  2693. :type 'boolean)
  2694. (defcustom org-highest-priority ?A
  2695. "The highest priority of TODO items. A character like ?A, ?B etc.
  2696. Must have a smaller ASCII number than `org-lowest-priority'."
  2697. :group 'org-priorities
  2698. :type 'character)
  2699. (defcustom org-lowest-priority ?C
  2700. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2701. Must have a larger ASCII number than `org-highest-priority'."
  2702. :group 'org-priorities
  2703. :type 'character)
  2704. (defcustom org-default-priority ?B
  2705. "The default priority of TODO items.
  2706. This is the priority an item gets if no explicit priority is given.
  2707. When starting to cycle on an empty priority the first step in the cycle
  2708. depends on `org-priority-start-cycle-with-default'. The resulting first
  2709. step priority must not exceed the range from `org-highest-priority' to
  2710. `org-lowest-priority' which means that `org-default-priority' has to be
  2711. in this range exclusive or inclusive the range boundaries. Else the
  2712. first step refuses to set the default and the second will fall back
  2713. to (depending on the command used) the highest or lowest priority."
  2714. :group 'org-priorities
  2715. :type 'character)
  2716. (defcustom org-priority-start-cycle-with-default t
  2717. "Non-nil means start with default priority when starting to cycle.
  2718. When this is nil, the first step in the cycle will be (depending on the
  2719. command used) one higher or lower than the default priority.
  2720. See also `org-default-priority'."
  2721. :group 'org-priorities
  2722. :type 'boolean)
  2723. (defcustom org-get-priority-function nil
  2724. "Function to extract the priority from a string.
  2725. The string is normally the headline. If this is nil Org computes the
  2726. priority from the priority cookie like [#A] in the headline. It returns
  2727. an integer, increasing by 1000 for each priority level.
  2728. The user can set a different function here, which should take a string
  2729. as an argument and return the numeric priority."
  2730. :group 'org-priorities
  2731. :version "24.1"
  2732. :type '(choice
  2733. (const nil)
  2734. (function)))
  2735. (defgroup org-time nil
  2736. "Options concerning time stamps and deadlines in Org mode."
  2737. :tag "Org Time"
  2738. :group 'org)
  2739. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2740. "Number of minutes to round time stamps to.
  2741. \\<org-mode-map>\
  2742. These are two values, the first applies when first creating a time stamp.
  2743. The second applies when changing it with the commands `S-up' and `S-down'.
  2744. When changing the time stamp, this means that it will change in steps
  2745. of N minutes, as given by the second value.
  2746. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2747. numbers should be factors of 60, so for example 5, 10, 15.
  2748. When this is larger than 1, you can still force an exact time stamp by using
  2749. a double prefix argument to a time stamp command like \
  2750. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2751. and by using a prefix arg to `S-up/down' to specify the exact number
  2752. of minutes to shift."
  2753. :group 'org-time
  2754. :get (lambda (var) ; Make sure both elements are there
  2755. (if (integerp (default-value var))
  2756. (list (default-value var) 5)
  2757. (default-value var)))
  2758. :type '(list
  2759. (integer :tag "when inserting times")
  2760. (integer :tag "when modifying times")))
  2761. ;; Normalize old customizations of this variable.
  2762. (when (integerp org-time-stamp-rounding-minutes)
  2763. (setq org-time-stamp-rounding-minutes
  2764. (list org-time-stamp-rounding-minutes
  2765. org-time-stamp-rounding-minutes)))
  2766. (defcustom org-display-custom-times nil
  2767. "Non-nil means overlay custom formats over all time stamps.
  2768. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2769. To turn this on on a per-file basis, insert anywhere in the file:
  2770. #+STARTUP: customtime"
  2771. :group 'org-time
  2772. :set 'set-default
  2773. :type 'sexp)
  2774. (make-variable-buffer-local 'org-display-custom-times)
  2775. (defcustom org-time-stamp-custom-formats
  2776. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2777. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2778. These are overlaid over the default ISO format if the variable
  2779. `org-display-custom-times' is set. Time like %H:%M should be at the
  2780. end of the second format. The custom formats are also honored by export
  2781. commands, if custom time display is turned on at the time of export."
  2782. :group 'org-time
  2783. :type 'sexp)
  2784. (defun org-time-stamp-format (&optional long inactive)
  2785. "Get the right format for a time string."
  2786. (let ((f (if long (cdr org-time-stamp-formats)
  2787. (car org-time-stamp-formats))))
  2788. (if inactive
  2789. (concat "[" (substring f 1 -1) "]")
  2790. f)))
  2791. (defcustom org-deadline-warning-days 14
  2792. "Number of days before expiration during which a deadline becomes active.
  2793. This variable governs the display in sparse trees and in the agenda.
  2794. When 0 or negative, it means use this number (the absolute value of it)
  2795. even if a deadline has a different individual lead time specified.
  2796. Custom commands can set this variable in the options section."
  2797. :group 'org-time
  2798. :group 'org-agenda-daily/weekly
  2799. :type 'integer)
  2800. (defcustom org-scheduled-delay-days 0
  2801. "Number of days before a scheduled item becomes active.
  2802. This variable governs the display in sparse trees and in the agenda.
  2803. The default value (i.e. 0) means: don't delay scheduled item.
  2804. When negative, it means use this number (the absolute value of it)
  2805. even if a scheduled item has a different individual delay time
  2806. specified.
  2807. Custom commands can set this variable in the options section."
  2808. :group 'org-time
  2809. :group 'org-agenda-daily/weekly
  2810. :version "24.4"
  2811. :package-version '(Org . "8.0")
  2812. :type 'integer)
  2813. (defcustom org-read-date-prefer-future t
  2814. "Non-nil means assume future for incomplete date input from user.
  2815. This affects the following situations:
  2816. 1. The user gives a month but not a year.
  2817. For example, if it is April and you enter \"feb 2\", this will be read
  2818. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2819. 2. The user gives a day, but no month.
  2820. For example, if today is the 15th, and you enter \"3\", Org will read
  2821. this as the third of *next* month. However, if you enter \"17\",
  2822. it will be considered as *this* month.
  2823. If you set this variable to the symbol `time', then also the following
  2824. will work:
  2825. 3. If the user gives a time.
  2826. If the time is before now, it will be interpreted as tomorrow.
  2827. Currently none of this works for ISO week specifications.
  2828. When this option is nil, the current day, month and year will always be
  2829. used as defaults.
  2830. See also `org-agenda-jump-prefer-future'."
  2831. :group 'org-time
  2832. :type '(choice
  2833. (const :tag "Never" nil)
  2834. (const :tag "Check month and day" t)
  2835. (const :tag "Check month, day, and time" time)))
  2836. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2837. "Should the agenda jump command prefer the future for incomplete dates?
  2838. The default is to do the same as configured in `org-read-date-prefer-future'.
  2839. But you can also set a deviating value here.
  2840. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2841. :group 'org-agenda
  2842. :group 'org-time
  2843. :version "24.1"
  2844. :type '(choice
  2845. (const :tag "Use org-read-date-prefer-future"
  2846. org-read-date-prefer-future)
  2847. (const :tag "Never" nil)
  2848. (const :tag "Always" t)))
  2849. (defcustom org-read-date-force-compatible-dates t
  2850. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2851. Depending on the system Emacs is running on, certain dates cannot
  2852. be represented with the type used internally to represent time.
  2853. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2854. correctly. Some systems allow for earlier dates, some for later,
  2855. some for both. One way to find out it to insert any date into an
  2856. Org buffer, putting the cursor on the year and hitting S-up and
  2857. S-down to test the range.
  2858. When this variable is set to t, the date/time prompt will not let
  2859. you specify dates outside the 1970-2037 range, so it is certain that
  2860. these dates will work in whatever version of Emacs you are
  2861. running, and also that you can move a file from one Emacs implementation
  2862. to another. WHenever Org is forcing the year for you, it will display
  2863. a message and beep.
  2864. When this variable is nil, Org will check if the date is
  2865. representable in the specific Emacs implementation you are using.
  2866. If not, it will force a year, usually the current year, and beep
  2867. to remind you. Currently this setting is not recommended because
  2868. the likelihood that you will open your Org files in an Emacs that
  2869. has limited date range is not negligible.
  2870. A workaround for this problem is to use diary sexp dates for time
  2871. stamps outside of this range."
  2872. :group 'org-time
  2873. :version "24.1"
  2874. :type 'boolean)
  2875. (defcustom org-read-date-display-live t
  2876. "Non-nil means display current interpretation of date prompt live.
  2877. This display will be in an overlay, in the minibuffer."
  2878. :group 'org-time
  2879. :type 'boolean)
  2880. (defcustom org-read-date-popup-calendar t
  2881. "Non-nil means pop up a calendar when prompting for a date.
  2882. In the calendar, the date can be selected with mouse-1. However, the
  2883. minibuffer will also be active, and you can simply enter the date as well.
  2884. When nil, only the minibuffer will be available."
  2885. :group 'org-time
  2886. :type 'boolean)
  2887. (defvaralias 'org-popup-calendar-for-date-prompt
  2888. 'org-read-date-popup-calendar)
  2889. (defcustom org-extend-today-until 0
  2890. "The hour when your day really ends. Must be an integer.
  2891. This has influence for the following applications:
  2892. - When switching the agenda to \"today\". It it is still earlier than
  2893. the time given here, the day recognized as TODAY is actually yesterday.
  2894. - When a date is read from the user and it is still before the time given
  2895. here, the current date and time will be assumed to be yesterday, 23:59.
  2896. Also, timestamps inserted in capture templates follow this rule.
  2897. IMPORTANT: This is a feature whose implementation is and likely will
  2898. remain incomplete. Really, it is only here because past midnight seems to
  2899. be the favorite working time of John Wiegley :-)"
  2900. :group 'org-time
  2901. :type 'integer)
  2902. (defcustom org-use-effective-time nil
  2903. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2904. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2905. \"effective time\" of any timestamps between midnight and 8am will be
  2906. 23:59 of the previous day."
  2907. :group 'org-time
  2908. :version "24.1"
  2909. :type 'boolean)
  2910. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2911. "When non-nil, use the last clock out time for `org-todo'.
  2912. Note that this option has precedence over the combined use of
  2913. `org-use-effective-time' and `org-extend-today-until'."
  2914. :group 'org-time
  2915. :version "24.4"
  2916. :package-version '(Org . "8.0")
  2917. :type 'boolean)
  2918. (defcustom org-edit-timestamp-down-means-later nil
  2919. "Non-nil means S-down will increase the time in a time stamp.
  2920. When nil, S-up will increase."
  2921. :group 'org-time
  2922. :type 'boolean)
  2923. (defcustom org-calendar-follow-timestamp-change t
  2924. "Non-nil means make the calendar window follow timestamp changes.
  2925. When a timestamp is modified and the calendar window is visible, it will be
  2926. moved to the new date."
  2927. :group 'org-time
  2928. :type 'boolean)
  2929. (defgroup org-tags nil
  2930. "Options concerning tags in Org mode."
  2931. :tag "Org Tags"
  2932. :group 'org)
  2933. (defcustom org-tag-alist nil
  2934. "Default tags available in Org files.
  2935. The value of this variable is an alist. Associations either:
  2936. (TAG)
  2937. (TAG . SELECT)
  2938. (SPECIAL)
  2939. where TAG is a tag as a string, SELECT is character, used to
  2940. select that tag through the fast tag selection interface, and
  2941. SPECIAL is one of the following keywords: `:startgroup',
  2942. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2943. `:newline'. These keywords are used to define a hierarchy of
  2944. tags. See manual for details.
  2945. When this variable is nil, Org mode bases tag input on what is
  2946. already in the buffer. The value can be overridden locally by
  2947. using a TAGS keyword, e.g.,
  2948. #+TAGS: tag1 tag2
  2949. See also `org-tag-persistent-alist' to sidestep this behavior."
  2950. :group 'org-tags
  2951. :type '(repeat
  2952. (choice
  2953. (cons :tag "Tag with key"
  2954. (string :tag "Tag name")
  2955. (character :tag "Access char"))
  2956. (list :tag "Tag" (string :tag "Tag name"))
  2957. (const :tag "Start radio group" (:startgroup))
  2958. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2959. (const :tag "Group tags delimiter" (:grouptags))
  2960. (const :tag "End radio group" (:endgroup))
  2961. (const :tag "End tag group, non distinct" (:endgrouptag))
  2962. (const :tag "New line" (:newline)))))
  2963. (defcustom org-tag-persistent-alist nil
  2964. "Tags always available in Org files.
  2965. The value of this variable is an alist. Associations either:
  2966. (TAG)
  2967. (TAG . SELECT)
  2968. (SPECIAL)
  2969. where TAG is a tag as a string, SELECT is a character, used to
  2970. select that tag through the fast tag selection interface, and
  2971. SPECIAL is one of the following keywords: `:startgroup',
  2972. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2973. `:newline'. These keywords are used to define a hierarchy of
  2974. tags. See manual for details.
  2975. Unlike to `org-tag-alist', tags defined in this variable do not
  2976. depend on a local TAGS keyword. Instead, to disable these tags
  2977. on a per-file basis, insert anywhere in the file:
  2978. #+STARTUP: noptag"
  2979. :group 'org-tags
  2980. :type '(repeat
  2981. (choice
  2982. (cons :tag "Tag with key"
  2983. (string :tag "Tag name")
  2984. (character :tag "Access char"))
  2985. (list :tag "Tag" (string :tag "Tag name"))
  2986. (const :tag "Start radio group" (:startgroup))
  2987. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2988. (const :tag "Group tags delimiter" (:grouptags))
  2989. (const :tag "End radio group" (:endgroup))
  2990. (const :tag "End tag group, non distinct" (:endgrouptag))
  2991. (const :tag "New line" (:newline)))))
  2992. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2993. "If non-nil, always offer completion for all tags of all agenda files.
  2994. Instead of customizing this variable directly, you might want to
  2995. set it locally for capture buffers, because there no list of
  2996. tags in that file can be created dynamically (there are none).
  2997. (add-hook \\='org-capture-mode-hook
  2998. (lambda ()
  2999. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3000. :group 'org-tags
  3001. :version "24.1"
  3002. :type 'boolean)
  3003. (defvar org-file-tags nil
  3004. "List of tags that can be inherited by all entries in the file.
  3005. The tags will be inherited if the variable `org-use-tag-inheritance'
  3006. says they should be.
  3007. This variable is populated from #+FILETAGS lines.")
  3008. (defcustom org-use-fast-tag-selection 'auto
  3009. "Non-nil means use fast tag selection scheme.
  3010. This is a special interface to select and deselect tags with single keys.
  3011. When nil, fast selection is never used.
  3012. When the symbol `auto', fast selection is used if and only if selection
  3013. characters for tags have been configured, either through the variable
  3014. `org-tag-alist' or through a #+TAGS line in the buffer.
  3015. When t, fast selection is always used and selection keys are assigned
  3016. automatically if necessary."
  3017. :group 'org-tags
  3018. :type '(choice
  3019. (const :tag "Always" t)
  3020. (const :tag "Never" nil)
  3021. (const :tag "When selection characters are configured" auto)))
  3022. (defcustom org-fast-tag-selection-single-key nil
  3023. "Non-nil means fast tag selection exits after first change.
  3024. When nil, you have to press RET to exit it.
  3025. During fast tag selection, you can toggle this flag with `C-c'.
  3026. This variable can also have the value `expert'. In this case, the window
  3027. displaying the tags menu is not even shown, until you press C-c again."
  3028. :group 'org-tags
  3029. :type '(choice
  3030. (const :tag "No" nil)
  3031. (const :tag "Yes" t)
  3032. (const :tag "Expert" expert)))
  3033. (defvar org-fast-tag-selection-include-todo nil
  3034. "Non-nil means fast tags selection interface will also offer TODO states.
  3035. This is an undocumented feature, you should not rely on it.")
  3036. (defcustom org-tags-column -77
  3037. "The column to which tags should be indented in a headline.
  3038. If this number is positive, it specifies the column. If it is negative,
  3039. it means that the tags should be flushright to that column. For example,
  3040. -80 works well for a normal 80 character screen.
  3041. When 0, place tags directly after headline text, with only one space in
  3042. between."
  3043. :group 'org-tags
  3044. :type 'integer)
  3045. (defcustom org-auto-align-tags t
  3046. "Non-nil keeps tags aligned when modifying headlines.
  3047. Some operations (i.e. demoting) change the length of a headline and
  3048. therefore shift the tags around. With this option turned on, after
  3049. each such operation the tags are again aligned to `org-tags-column'."
  3050. :group 'org-tags
  3051. :type 'boolean)
  3052. (defcustom org-use-tag-inheritance t
  3053. "Non-nil means tags in levels apply also for sublevels.
  3054. When nil, only the tags directly given in a specific line apply there.
  3055. This may also be a list of tags that should be inherited, or a regexp that
  3056. matches tags that should be inherited. Additional control is possible
  3057. with the variable `org-tags-exclude-from-inheritance' which gives an
  3058. explicit list of tags to be excluded from inheritance, even if the value of
  3059. `org-use-tag-inheritance' would select it for inheritance.
  3060. If this option is t, a match early-on in a tree can lead to a large
  3061. number of matches in the subtree when constructing the agenda or creating
  3062. a sparse tree. If you only want to see the first match in a tree during
  3063. a search, check out the variable `org-tags-match-list-sublevels'."
  3064. :group 'org-tags
  3065. :type '(choice
  3066. (const :tag "Not" nil)
  3067. (const :tag "Always" t)
  3068. (repeat :tag "Specific tags" (string :tag "Tag"))
  3069. (regexp :tag "Tags matched by regexp")))
  3070. (defcustom org-tags-exclude-from-inheritance nil
  3071. "List of tags that should never be inherited.
  3072. This is a way to exclude a few tags from inheritance. For way to do
  3073. the opposite, to actively allow inheritance for selected tags,
  3074. see the variable `org-use-tag-inheritance'."
  3075. :group 'org-tags
  3076. :type '(repeat (string :tag "Tag")))
  3077. (defun org-tag-inherit-p (tag)
  3078. "Check if TAG is one that should be inherited."
  3079. (cond
  3080. ((member tag org-tags-exclude-from-inheritance) nil)
  3081. ((eq org-use-tag-inheritance t) t)
  3082. ((not org-use-tag-inheritance) nil)
  3083. ((stringp org-use-tag-inheritance)
  3084. (string-match org-use-tag-inheritance tag))
  3085. ((listp org-use-tag-inheritance)
  3086. (member tag org-use-tag-inheritance))
  3087. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3088. (defcustom org-tags-match-list-sublevels t
  3089. "Non-nil means list also sublevels of headlines matching a search.
  3090. This variable applies to tags/property searches, and also to stuck
  3091. projects because this search is based on a tags match as well.
  3092. When set to the symbol `indented', sublevels are indented with
  3093. leading dots.
  3094. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3095. the sublevels of a headline matching a tag search often also match
  3096. the same search. Listing all of them can create very long lists.
  3097. Setting this variable to nil causes subtrees of a match to be skipped.
  3098. This variable is semi-obsolete and probably should always be true. It
  3099. is better to limit inheritance to certain tags using the variables
  3100. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3101. :group 'org-tags
  3102. :type '(choice
  3103. (const :tag "No, don't list them" nil)
  3104. (const :tag "Yes, do list them" t)
  3105. (const :tag "List them, indented with leading dots" indented)))
  3106. (defcustom org-tags-sort-function nil
  3107. "When set, tags are sorted using this function as a comparator."
  3108. :group 'org-tags
  3109. :type '(choice
  3110. (const :tag "No sorting" nil)
  3111. (const :tag "Alphabetical" org-string-collate-lessp)
  3112. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  3113. (function :tag "Custom function" nil)))
  3114. (defvar org-tags-history nil
  3115. "History of minibuffer reads for tags.")
  3116. (defvar org-last-tags-completion-table nil
  3117. "The last used completion table for tags.")
  3118. (defvar org-after-tags-change-hook nil
  3119. "Hook that is run after the tags in a line have changed.")
  3120. (defgroup org-properties nil
  3121. "Options concerning properties in Org mode."
  3122. :tag "Org Properties"
  3123. :group 'org)
  3124. (defcustom org-property-format "%-10s %s"
  3125. "How property key/value pairs should be formatted by `indent-line'.
  3126. When `indent-line' hits a property definition, it will format the line
  3127. according to this format, mainly to make sure that the values are
  3128. lined-up with respect to each other."
  3129. :group 'org-properties
  3130. :type 'string)
  3131. (defcustom org-properties-postprocess-alist nil
  3132. "Alist of properties and functions to adjust inserted values.
  3133. Elements of this alist must be of the form
  3134. ([string] [function])
  3135. where [string] must be a property name and [function] must be a
  3136. lambda expression: this lambda expression must take one argument,
  3137. the value to adjust, and return the new value as a string.
  3138. For example, this element will allow the property \"Remaining\"
  3139. to be updated wrt the relation between the \"Effort\" property
  3140. and the clock summary:
  3141. ((\"Remaining\" (lambda(value)
  3142. (let ((clocksum (org-clock-sum-current-item))
  3143. (effort (org-duration-to-minutes
  3144. (org-entry-get (point) \"Effort\"))))
  3145. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3146. :group 'org-properties
  3147. :version "24.1"
  3148. :type '(alist :key-type (string :tag "Property")
  3149. :value-type (function :tag "Function")))
  3150. (defcustom org-use-property-inheritance nil
  3151. "Non-nil means properties apply also for sublevels.
  3152. This setting is chiefly used during property searches. Turning it on can
  3153. cause significant overhead when doing a search, which is why it is not
  3154. on by default.
  3155. When nil, only the properties directly given in the current entry count.
  3156. When t, every property is inherited. The value may also be a list of
  3157. properties that should have inheritance, or a regular expression matching
  3158. properties that should be inherited.
  3159. However, note that some special properties use inheritance under special
  3160. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3161. and the properties ending in \"_ALL\" when they are used as descriptor
  3162. for valid values of a property.
  3163. Note for programmers:
  3164. When querying an entry with `org-entry-get', you can control if inheritance
  3165. should be used. By default, `org-entry-get' looks only at the local
  3166. properties. You can request inheritance by setting the inherit argument
  3167. to t (to force inheritance) or to `selective' (to respect the setting
  3168. in this variable)."
  3169. :group 'org-properties
  3170. :type '(choice
  3171. (const :tag "Not" nil)
  3172. (const :tag "Always" t)
  3173. (repeat :tag "Specific properties" (string :tag "Property"))
  3174. (regexp :tag "Properties matched by regexp")))
  3175. (defun org-property-inherit-p (property)
  3176. "Return a non-nil value if PROPERTY should be inherited."
  3177. (cond
  3178. ((eq org-use-property-inheritance t) t)
  3179. ((not org-use-property-inheritance) nil)
  3180. ((stringp org-use-property-inheritance)
  3181. (string-match org-use-property-inheritance property))
  3182. ((listp org-use-property-inheritance)
  3183. (member-ignore-case property org-use-property-inheritance))
  3184. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3185. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3186. "The default column format, if no other format has been defined.
  3187. This variable can be set on the per-file basis by inserting a line
  3188. #+COLUMNS: %25ITEM ....."
  3189. :group 'org-properties
  3190. :type 'string)
  3191. (defcustom org-columns-ellipses ".."
  3192. "The ellipses to be used when a field in column view is truncated.
  3193. When this is the empty string, as many characters as possible are shown,
  3194. but then there will be no visual indication that the field has been truncated.
  3195. When this is a string of length N, the last N characters of a truncated
  3196. field are replaced by this string. If the column is narrower than the
  3197. ellipses string, only part of the ellipses string will be shown."
  3198. :group 'org-properties
  3199. :type 'string)
  3200. (defconst org-global-properties-fixed
  3201. '(("VISIBILITY_ALL" . "folded children content all")
  3202. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3203. "List of property/value pairs that can be inherited by any entry.
  3204. These are fixed values, for the preset properties. The user variable
  3205. that can be used to add to this list is `org-global-properties'.
  3206. The entries in this list are cons cells where the car is a property
  3207. name and cdr is a string with the value. If the value represents
  3208. multiple items like an \"_ALL\" property, separate the items by
  3209. spaces.")
  3210. (defcustom org-global-properties nil
  3211. "List of property/value pairs that can be inherited by any entry.
  3212. This list will be combined with the constant `org-global-properties-fixed'.
  3213. The entries in this list are cons cells where the car is a property
  3214. name and cdr is a string with the value.
  3215. You can set buffer-local values for the same purpose in the variable
  3216. `org-file-properties' this by adding lines like
  3217. #+PROPERTY: NAME VALUE"
  3218. :group 'org-properties
  3219. :type '(repeat
  3220. (cons (string :tag "Property")
  3221. (string :tag "Value"))))
  3222. (defvar-local org-file-properties nil
  3223. "List of property/value pairs that can be inherited by any entry.
  3224. Valid for the current buffer.
  3225. This variable is populated from #+PROPERTY lines.")
  3226. (defgroup org-agenda nil
  3227. "Options concerning agenda views in Org mode."
  3228. :tag "Org Agenda"
  3229. :group 'org)
  3230. (defvar-local org-category nil
  3231. "Variable used by Org files to set a category for agenda display.
  3232. Such files should use a file variable to set it, for example
  3233. # -*- mode: org; org-category: \"ELisp\"
  3234. or contain a special line
  3235. #+CATEGORY: ELisp
  3236. If the file does not specify a category, then file's base name
  3237. is used instead.")
  3238. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3239. (defcustom org-agenda-files nil
  3240. "The files to be used for agenda display.
  3241. If an entry is a directory, all files in that directory that are matched
  3242. by `org-agenda-file-regexp' will be part of the file list.
  3243. If the value of the variable is not a list but a single file name, then
  3244. the list of agenda files is actually stored and maintained in that file,
  3245. one agenda file per line. In this file paths can be given relative to
  3246. `org-directory'. Tilde expansion and environment variable substitution
  3247. are also made.
  3248. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3249. and removed with `\\[org-remove-file]'."
  3250. :group 'org-agenda
  3251. :type '(choice
  3252. (repeat :tag "List of files and directories" file)
  3253. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3254. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3255. "Regular expression to match files for `org-agenda-files'.
  3256. If any element in the list in that variable contains a directory instead
  3257. of a normal file, all files in that directory that are matched by this
  3258. regular expression will be included."
  3259. :group 'org-agenda
  3260. :type 'regexp)
  3261. (defcustom org-agenda-text-search-extra-files nil
  3262. "List of extra files to be searched by text search commands.
  3263. These files will be searched in addition to the agenda files by the
  3264. commands `org-search-view' (`\\[org-agenda] s') \
  3265. and `org-occur-in-agenda-files'.
  3266. Note that these files will only be searched for text search commands,
  3267. not for the other agenda views like todo lists, tag searches or the weekly
  3268. agenda. This variable is intended to list notes and possibly archive files
  3269. that should also be searched by these two commands.
  3270. In fact, if the first element in the list is the symbol `agenda-archives',
  3271. then all archive files of all agenda files will be added to the search
  3272. scope."
  3273. :group 'org-agenda
  3274. :type '(set :greedy t
  3275. (const :tag "Agenda Archives" agenda-archives)
  3276. (repeat :inline t (file))))
  3277. (defvaralias 'org-agenda-multi-occur-extra-files
  3278. 'org-agenda-text-search-extra-files)
  3279. (defcustom org-agenda-skip-unavailable-files nil
  3280. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3281. A nil value means to remove them, after a query, from the list."
  3282. :group 'org-agenda
  3283. :type 'boolean)
  3284. (defcustom org-agenda-diary-file 'diary-file
  3285. "File to which to add new entries with the `i' key in agenda and calendar.
  3286. When this is the symbol `diary-file', the functionality in the Emacs
  3287. calendar will be used to add entries to the `diary-file'. But when this
  3288. points to a file, `org-agenda-diary-entry' will be used instead."
  3289. :group 'org-agenda
  3290. :type '(choice
  3291. (const :tag "The standard Emacs diary file" diary-file)
  3292. (file :tag "Special Org file diary entries")))
  3293. (defgroup org-latex nil
  3294. "Options for embedding LaTeX code into Org mode."
  3295. :tag "Org LaTeX"
  3296. :group 'org)
  3297. (defcustom org-format-latex-options
  3298. '(:foreground default :background default :scale 1.0
  3299. :html-foreground "Black" :html-background "Transparent"
  3300. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3301. "Options for creating images from LaTeX fragments.
  3302. This is a property list with the following properties:
  3303. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3304. `default' means use the foreground of the default face.
  3305. `auto' means use the foreground from the text face.
  3306. :background the background color, or \"Transparent\".
  3307. `default' means use the background of the default face.
  3308. `auto' means use the background from the text face.
  3309. :scale a scaling factor for the size of the images, to get more pixels
  3310. :html-foreground, :html-background, :html-scale
  3311. the same numbers for HTML export.
  3312. :matchers a list indicating which matchers should be used to
  3313. find LaTeX fragments. Valid members of this list are:
  3314. \"begin\" find environments
  3315. \"$1\" find single characters surrounded by $.$
  3316. \"$\" find math expressions surrounded by $...$
  3317. \"$$\" find math expressions surrounded by $$....$$
  3318. \"\\(\" find math expressions surrounded by \\(...\\)
  3319. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3320. :group 'org-latex
  3321. :type 'plist)
  3322. (defcustom org-format-latex-signal-error t
  3323. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3324. When nil, just push out a message."
  3325. :group 'org-latex
  3326. :version "24.1"
  3327. :type 'boolean)
  3328. (defcustom org-latex-to-mathml-jar-file nil
  3329. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3330. Use this to specify additional executable file say a jar file.
  3331. When using MathToWeb as the converter, specify the full-path to
  3332. your mathtoweb.jar file."
  3333. :group 'org-latex
  3334. :version "24.1"
  3335. :type '(choice
  3336. (const :tag "None" nil)
  3337. (file :tag "JAR file" :must-match t)))
  3338. (defcustom org-latex-to-mathml-convert-command nil
  3339. "Command to convert LaTeX fragments to MathML.
  3340. Replace format-specifiers in the command as noted below and use
  3341. `shell-command' to convert LaTeX to MathML.
  3342. %j: Executable file in fully expanded form as specified by
  3343. `org-latex-to-mathml-jar-file'.
  3344. %I: Input LaTeX file in fully expanded form.
  3345. %i: The latex fragment to be converted.
  3346. %o: Output MathML file.
  3347. This command is used by `org-create-math-formula'.
  3348. When using MathToWeb as the converter, set this option to
  3349. \"java -jar %j -unicode -force -df %o %I\".
  3350. When using LaTeXML set this option to
  3351. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3352. :group 'org-latex
  3353. :version "24.1"
  3354. :type '(choice
  3355. (const :tag "None" nil)
  3356. (string :tag "\nShell command")))
  3357. (defcustom org-preview-latex-default-process 'dvipng
  3358. "The default process to convert LaTeX fragments to image files.
  3359. All available processes and theirs documents can be found in
  3360. `org-preview-latex-process-alist', which see."
  3361. :group 'org-latex
  3362. :version "26.1"
  3363. :package-version '(Org . "9.0")
  3364. :type 'symbol)
  3365. (defcustom org-preview-latex-process-alist
  3366. '((dvipng
  3367. :programs ("latex" "dvipng")
  3368. :description "dvi > png"
  3369. :message "you need to install the programs: latex and dvipng."
  3370. :image-input-type "dvi"
  3371. :image-output-type "png"
  3372. :image-size-adjust (1.0 . 1.0)
  3373. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3374. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3375. (dvisvgm
  3376. :programs ("latex" "dvisvgm")
  3377. :description "dvi > svg"
  3378. :message "you need to install the programs: latex and dvisvgm."
  3379. :use-xcolor t
  3380. :image-input-type "dvi"
  3381. :image-output-type "svg"
  3382. :image-size-adjust (1.7 . 1.5)
  3383. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3384. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3385. (imagemagick
  3386. :programs ("latex" "convert")
  3387. :description "pdf > png"
  3388. :message "you need to install the programs: latex and imagemagick."
  3389. :use-xcolor t
  3390. :image-input-type "pdf"
  3391. :image-output-type "png"
  3392. :image-size-adjust (1.0 . 1.0)
  3393. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3394. :image-converter
  3395. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3396. "Definitions of external processes for LaTeX previewing.
  3397. Org mode can use some external commands to generate TeX snippet's images for
  3398. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3399. `org-create-formula-image' how to call them.
  3400. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3401. PROPERTIES accepts the following attributes:
  3402. :programs list of strings, required programs.
  3403. :description string, describe the process.
  3404. :message string, message it when required programs cannot be found.
  3405. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3406. :image-output-type string, output file type of image converter (e.g., \"png\").
  3407. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3408. deal with background and foreground color of image.
  3409. Otherwise, dvipng style background and foreground color
  3410. format are generated. You may then refer to them in
  3411. command options with \"%F\" and \"%B\".
  3412. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3413. image size showed in buffer and the cdr element is for
  3414. HTML file. This option is only useful for process
  3415. developers, users should use variable
  3416. `org-format-latex-options' instead.
  3417. :post-clean list of strings, files matched are to be cleaned up once
  3418. the image is generated. When nil, the files with \".dvi\",
  3419. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3420. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3421. be cleaned up.
  3422. :latex-header list of strings, the LaTeX header of the snippet file.
  3423. When nil, the fallback value is used instead, which is
  3424. controlled by `org-format-latex-header',
  3425. `org-latex-default-packages-alist' and
  3426. `org-latex-packages-alist', which see.
  3427. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3428. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3429. replaced with values defined below.
  3430. :image-converter list of image converter commands strings. Each of them is
  3431. given to the shell and supports any of the following
  3432. place-holders defined below.
  3433. Place-holders used by `:image-converter' and `:latex-compiler':
  3434. %f input file name
  3435. %b base name of input file
  3436. %o base directory of input file
  3437. %O absolute output file name
  3438. Place-holders only used by `:image-converter':
  3439. %F foreground of image
  3440. %B background of image
  3441. %D dpi, which is used to adjust image size by some processing commands.
  3442. %S the image size scale ratio, which is used to adjust image size by some
  3443. processing commands."
  3444. :group 'org-latex
  3445. :version "26.1"
  3446. :package-version '(Org . "9.0")
  3447. :type '(alist :tag "LaTeX to image backends"
  3448. :value-type (plist)))
  3449. (defcustom org-preview-latex-image-directory "ltximg/"
  3450. "Path to store latex preview images.
  3451. A relative path here creates many directories relative to the
  3452. processed Org files paths. An absolute path puts all preview
  3453. images at the same place."
  3454. :group 'org-latex
  3455. :version "26.1"
  3456. :package-version '(Org . "9.0")
  3457. :type 'string)
  3458. (defun org-format-latex-mathml-available-p ()
  3459. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3460. (save-match-data
  3461. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3462. org-latex-to-mathml-convert-command)
  3463. (let ((executable (car (split-string
  3464. org-latex-to-mathml-convert-command))))
  3465. (when (executable-find executable)
  3466. (if (string-match
  3467. "%j" org-latex-to-mathml-convert-command)
  3468. (file-readable-p org-latex-to-mathml-jar-file)
  3469. t))))))
  3470. (defcustom org-format-latex-header "\\documentclass{article}
  3471. \\usepackage[usenames]{color}
  3472. \[PACKAGES]
  3473. \[DEFAULT-PACKAGES]
  3474. \\pagestyle{empty} % do not remove
  3475. % The settings below are copied from fullpage.sty
  3476. \\setlength{\\textwidth}{\\paperwidth}
  3477. \\addtolength{\\textwidth}{-3cm}
  3478. \\setlength{\\oddsidemargin}{1.5cm}
  3479. \\addtolength{\\oddsidemargin}{-2.54cm}
  3480. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3481. \\setlength{\\textheight}{\\paperheight}
  3482. \\addtolength{\\textheight}{-\\headheight}
  3483. \\addtolength{\\textheight}{-\\headsep}
  3484. \\addtolength{\\textheight}{-\\footskip}
  3485. \\addtolength{\\textheight}{-3cm}
  3486. \\setlength{\\topmargin}{1.5cm}
  3487. \\addtolength{\\topmargin}{-2.54cm}"
  3488. "The document header used for processing LaTeX fragments.
  3489. It is imperative that this header make sure that no page number
  3490. appears on the page. The package defined in the variables
  3491. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3492. will either replace the placeholder \"[PACKAGES]\" in this
  3493. header, or they will be appended."
  3494. :group 'org-latex
  3495. :type 'string)
  3496. (defun org-set-packages-alist (var val)
  3497. "Set the packages alist and make sure it has 3 elements per entry."
  3498. (set var (mapcar (lambda (x)
  3499. (if (and (consp x) (= (length x) 2))
  3500. (list (car x) (nth 1 x) t)
  3501. x))
  3502. val)))
  3503. (defun org-get-packages-alist (var)
  3504. "Get the packages alist and make sure it has 3 elements per entry."
  3505. (mapcar (lambda (x)
  3506. (if (and (consp x) (= (length x) 2))
  3507. (list (car x) (nth 1 x) t)
  3508. x))
  3509. (default-value var)))
  3510. (defcustom org-latex-default-packages-alist
  3511. '(("AUTO" "inputenc" t ("pdflatex"))
  3512. ("T1" "fontenc" t ("pdflatex"))
  3513. ("" "graphicx" t)
  3514. ("" "grffile" t)
  3515. ("" "longtable" nil)
  3516. ("" "wrapfig" nil)
  3517. ("" "rotating" nil)
  3518. ("normalem" "ulem" t)
  3519. ("" "amsmath" t)
  3520. ("" "textcomp" t)
  3521. ("" "amssymb" t)
  3522. ("" "capt-of" nil)
  3523. ("" "hyperref" nil))
  3524. "Alist of default packages to be inserted in the header.
  3525. Change this only if one of the packages here causes an
  3526. incompatibility with another package you are using.
  3527. The packages in this list are needed by one part or another of
  3528. Org mode to function properly:
  3529. - inputenc, fontenc: for basic font and character selection
  3530. - graphicx: for including images
  3531. - grffile: allow periods and spaces in graphics file names
  3532. - longtable: For multipage tables
  3533. - wrapfig: for figure placement
  3534. - rotating: for sideways figures and tables
  3535. - ulem: for underline and strike-through
  3536. - amsmath: for subscript and superscript and math environments
  3537. - textcomp, amssymb: for various symbols used
  3538. for interpreting the entities in `org-entities'. You can skip
  3539. some of these packages if you don't use any of their symbols.
  3540. - capt-of: for captions outside of floats
  3541. - hyperref: for cross references
  3542. Therefore you should not modify this variable unless you know
  3543. what you are doing. The one reason to change it anyway is that
  3544. you might be loading some other package that conflicts with one
  3545. of the default packages. Each element is either a cell or
  3546. a string.
  3547. A cell is of the format
  3548. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3549. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3550. when compiling LaTeX snippets into images for inclusion into
  3551. non-LaTeX output. COMPILERS is a list of compilers that should
  3552. include the package, see `org-latex-compiler'. If the document
  3553. compiler is not in the list, and the list is non-nil, the package
  3554. will not be inserted in the final document.
  3555. A string will be inserted as-is in the header of the document."
  3556. :group 'org-latex
  3557. :group 'org-export-latex
  3558. :set 'org-set-packages-alist
  3559. :get 'org-get-packages-alist
  3560. :version "26.1"
  3561. :package-version '(Org . "8.3")
  3562. :type '(repeat
  3563. (choice
  3564. (list :tag "options/package pair"
  3565. (string :tag "options")
  3566. (string :tag "package")
  3567. (boolean :tag "Snippet")
  3568. (choice
  3569. (const :tag "For all compilers" nil)
  3570. (repeat :tag "Allowed compiler" string)))
  3571. (string :tag "A line of LaTeX"))))
  3572. (defcustom org-latex-packages-alist nil
  3573. "Alist of packages to be inserted in every LaTeX header.
  3574. These will be inserted after `org-latex-default-packages-alist'.
  3575. Each element is either a cell or a string.
  3576. A cell is of the format:
  3577. (\"options\" \"package\" SNIPPET-FLAG)
  3578. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3579. needed when turning LaTeX snippets into images for inclusion into
  3580. non-LaTeX output.
  3581. A string will be inserted as-is in the header of the document.
  3582. Make sure that you only list packages here which:
  3583. - you want in every file;
  3584. - do not conflict with the setup in `org-format-latex-header';
  3585. - do not conflict with the default packages in
  3586. `org-latex-default-packages-alist'."
  3587. :group 'org-latex
  3588. :group 'org-export-latex
  3589. :set 'org-set-packages-alist
  3590. :get 'org-get-packages-alist
  3591. :type '(repeat
  3592. (choice
  3593. (list :tag "options/package pair"
  3594. (string :tag "options")
  3595. (string :tag "package")
  3596. (boolean :tag "Snippet"))
  3597. (string :tag "A line of LaTeX"))))
  3598. (defgroup org-appearance nil
  3599. "Settings for Org mode appearance."
  3600. :tag "Org Appearance"
  3601. :group 'org)
  3602. (defcustom org-level-color-stars-only nil
  3603. "Non-nil means fontify only the stars in each headline.
  3604. When nil, the entire headline is fontified.
  3605. Changing it requires restart of `font-lock-mode' to become effective
  3606. also in regions already fontified."
  3607. :group 'org-appearance
  3608. :type 'boolean)
  3609. (defcustom org-hide-leading-stars nil
  3610. "Non-nil means hide the first N-1 stars in a headline.
  3611. This works by using the face `org-hide' for these stars. This
  3612. face is white for a light background, and black for a dark
  3613. background. You may have to customize the face `org-hide' to
  3614. make this work.
  3615. Changing it requires restart of `font-lock-mode' to become effective
  3616. also in regions already fontified.
  3617. You may also set this on a per-file basis by adding one of the following
  3618. lines to the buffer:
  3619. #+STARTUP: hidestars
  3620. #+STARTUP: showstars"
  3621. :group 'org-appearance
  3622. :type 'boolean)
  3623. (defcustom org-hidden-keywords nil
  3624. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3625. For example, a value \\='(title) for this list makes the document's title
  3626. appear in the buffer without the initial \"#+TITLE:\" part."
  3627. :group 'org-appearance
  3628. :version "24.1"
  3629. :type '(set (const :tag "#+AUTHOR" author)
  3630. (const :tag "#+DATE" date)
  3631. (const :tag "#+EMAIL" email)
  3632. (const :tag "#+TITLE" title)))
  3633. (defcustom org-custom-properties nil
  3634. "List of properties (as strings) with a special meaning.
  3635. The default use of these custom properties is to let the user
  3636. hide them with `org-toggle-custom-properties-visibility'."
  3637. :group 'org-properties
  3638. :group 'org-appearance
  3639. :version "24.3"
  3640. :type '(repeat (string :tag "Property Name")))
  3641. (defcustom org-fontify-done-headline nil
  3642. "Non-nil means change the face of a headline if it is marked DONE.
  3643. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3644. When this is non-nil, the headline after the keyword is set to the
  3645. `org-headline-done' as an additional indication."
  3646. :group 'org-appearance
  3647. :type 'boolean)
  3648. (defcustom org-fontify-emphasized-text t
  3649. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3650. Changing this variable requires a restart of Emacs to take effect."
  3651. :group 'org-appearance
  3652. :type 'boolean)
  3653. (defcustom org-fontify-whole-heading-line nil
  3654. "Non-nil means fontify the whole line for headings.
  3655. This is useful when setting a background color for the
  3656. org-level-* faces."
  3657. :group 'org-appearance
  3658. :type 'boolean)
  3659. (defcustom org-highlight-latex-and-related nil
  3660. "Non-nil means highlight LaTeX related syntax in the buffer.
  3661. When non nil, the value should be a list containing any of the
  3662. following symbols:
  3663. `latex' Highlight LaTeX snippets and environments.
  3664. `script' Highlight subscript and superscript.
  3665. `entities' Highlight entities."
  3666. :group 'org-appearance
  3667. :version "24.4"
  3668. :package-version '(Org . "8.0")
  3669. :type '(choice
  3670. (const :tag "No highlighting" nil)
  3671. (set :greedy t :tag "Highlight"
  3672. (const :tag "LaTeX snippets and environments" latex)
  3673. (const :tag "Subscript and superscript" script)
  3674. (const :tag "Entities" entities))))
  3675. (defcustom org-hide-emphasis-markers nil
  3676. "Non-nil mean font-lock should hide the emphasis marker characters."
  3677. :group 'org-appearance
  3678. :type 'boolean
  3679. :safe #'booleanp)
  3680. (defcustom org-hide-macro-markers nil
  3681. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3682. :group 'org-appearance
  3683. :type 'boolean)
  3684. (defcustom org-pretty-entities nil
  3685. "Non-nil means show entities as UTF8 characters.
  3686. When nil, the \\name form remains in the buffer."
  3687. :group 'org-appearance
  3688. :version "24.1"
  3689. :type 'boolean)
  3690. (defcustom org-pretty-entities-include-sub-superscripts t
  3691. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3692. :group 'org-appearance
  3693. :version "24.1"
  3694. :type 'boolean)
  3695. (defvar org-emph-re nil
  3696. "Regular expression for matching emphasis.
  3697. After a match, the match groups contain these elements:
  3698. 0 The match of the full regular expression, including the characters
  3699. before and after the proper match
  3700. 1 The character before the proper match, or empty at beginning of line
  3701. 2 The proper match, including the leading and trailing markers
  3702. 3 The leading marker like * or /, indicating the type of highlighting
  3703. 4 The text between the emphasis markers, not including the markers
  3704. 5 The character after the match, empty at the end of a line")
  3705. (defvar org-verbatim-re nil
  3706. "Regular expression for matching verbatim text.")
  3707. (defvar org-emphasis-regexp-components) ; defined just below
  3708. (defvar org-emphasis-alist) ; defined just below
  3709. (defun org-set-emph-re (var val)
  3710. "Set variable and compute the emphasis regular expression."
  3711. (set var val)
  3712. (when (and (boundp 'org-emphasis-alist)
  3713. (boundp 'org-emphasis-regexp-components)
  3714. org-emphasis-alist org-emphasis-regexp-components)
  3715. (pcase-let*
  3716. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3717. (body (if (<= nl 0) body
  3718. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3719. (template
  3720. (format (concat "\\([%s]\\|^\\)" ;before markers
  3721. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3722. "\\([%s]\\|$\\)") ;after markers
  3723. pre border border body border post)))
  3724. (setq org-emph-re (format template "*/_+"))
  3725. (setq org-verbatim-re (format template "=~")))))
  3726. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3727. ;; set this option proved cumbersome. See this message/thread:
  3728. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3729. (defvar org-emphasis-regexp-components
  3730. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3731. "Components used to build the regular expression for emphasis.
  3732. This is a list with five entries. Terminology: In an emphasis string
  3733. like \" *strong word* \", we call the initial space PREMATCH, the final
  3734. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3735. and \"trong wor\" is the body. The different components in this variable
  3736. specify what is allowed/forbidden in each part:
  3737. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3738. post Chars allowed as postmatch. End of line will be allowed too.
  3739. border The chars *forbidden* as border characters.
  3740. body-regexp A regexp like \".\" to match a body character. Don't use
  3741. non-shy groups here, and don't allow newline here.
  3742. newline The maximum number of newlines allowed in an emphasis exp.
  3743. You need to reload Org or to restart Emacs after setting this.")
  3744. (defcustom org-emphasis-alist
  3745. '(("*" bold)
  3746. ("/" italic)
  3747. ("_" underline)
  3748. ("=" org-verbatim verbatim)
  3749. ("~" org-code verbatim)
  3750. ("+" (:strike-through t)))
  3751. "Alist of characters and faces to emphasize text.
  3752. Text starting and ending with a special character will be emphasized,
  3753. for example *bold*, _underlined_ and /italic/. This variable sets the
  3754. marker characters and the face to be used by font-lock for highlighting
  3755. in Org buffers.
  3756. You need to reload Org or to restart Emacs after customizing this."
  3757. :group 'org-appearance
  3758. :set 'org-set-emph-re
  3759. :version "24.4"
  3760. :package-version '(Org . "8.0")
  3761. :type '(repeat
  3762. (list
  3763. (string :tag "Marker character")
  3764. (choice
  3765. (face :tag "Font-lock-face")
  3766. (plist :tag "Face property list"))
  3767. (option (const verbatim)))))
  3768. (defvar org-protecting-blocks '("src" "example" "export")
  3769. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3770. This is needed for font-lock setup.")
  3771. ;;; Functions and variables from their packages
  3772. ;; Declared here to avoid compiler warnings
  3773. (defvar mark-active)
  3774. ;; Various packages
  3775. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3776. (declare-function calendar-forward-day "cal-move" (arg))
  3777. (declare-function calendar-goto-date "cal-move" (date))
  3778. (declare-function calendar-goto-today "cal-move" ())
  3779. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3780. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3781. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3782. (declare-function cdlatex-tab "ext:cdlatex" ())
  3783. (declare-function dired-get-filename
  3784. "dired"
  3785. (&optional localp no-error-if-not-filep))
  3786. (declare-function iswitchb-read-buffer
  3787. "iswitchb"
  3788. (prompt &optional
  3789. default require-match _predicate start matches-set))
  3790. (declare-function org-agenda-change-all-lines
  3791. "org-agenda"
  3792. (newhead hdmarker &optional fixface just-this))
  3793. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3794. "org-agenda"
  3795. (&optional end))
  3796. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3797. (declare-function org-agenda-format-item
  3798. "org-agenda"
  3799. (extra txt &optional level category tags dotime
  3800. remove-re habitp))
  3801. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3802. (declare-function org-agenda-save-markers-for-cut-and-paste
  3803. "org-agenda"
  3804. (beg end))
  3805. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3806. (declare-function org-agenda-skip "org-agenda" ())
  3807. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3808. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3809. (declare-function org-indent-mode "org-indent" (&optional arg))
  3810. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3811. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3812. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3813. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3814. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3815. (declare-function parse-time-string "parse-time" (string))
  3816. (defvar align-mode-rules-list)
  3817. (defvar calc-embedded-close-formula)
  3818. (defvar calc-embedded-open-formula)
  3819. (defvar calc-embedded-open-mode)
  3820. (defvar font-lock-unfontify-region-function)
  3821. (defvar iswitchb-temp-buflist)
  3822. (defvar org-agenda-tags-todo-honor-ignore-options)
  3823. (defvar remember-data-file)
  3824. (defvar texmathp-why)
  3825. ;;;###autoload
  3826. (defun turn-on-orgtbl ()
  3827. "Unconditionally turn on `orgtbl-mode'."
  3828. (require 'org-table)
  3829. (orgtbl-mode 1))
  3830. (defun org-at-table-p (&optional table-type)
  3831. "Non-nil if the cursor is inside an Org table.
  3832. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3833. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3834. (or (not (derived-mode-p 'org-mode))
  3835. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3836. (and e (or table-type
  3837. (eq 'org (org-element-property :type e))))))))
  3838. (defun org-at-table.el-p ()
  3839. "Non-nil when point is at a table.el table."
  3840. (and (org-match-line "[ \t]*[|+]")
  3841. (let ((element (org-element-at-point)))
  3842. (and (eq (org-element-type element) 'table)
  3843. (eq (org-element-property :type element) 'table.el)))))
  3844. (defun org-at-table-hline-p ()
  3845. "Non-nil when point is inside a hline in a table.
  3846. Assume point is already in a table."
  3847. (org-match-line org-table-hline-regexp))
  3848. (defun org-table-map-tables (function &optional quietly)
  3849. "Apply FUNCTION to the start of all tables in the buffer."
  3850. (org-with-wide-buffer
  3851. (goto-char (point-min))
  3852. (while (re-search-forward org-table-any-line-regexp nil t)
  3853. (unless quietly
  3854. (message "Mapping tables: %d%%"
  3855. (floor (* 100.0 (point)) (buffer-size))))
  3856. (beginning-of-line 1)
  3857. (when (and (looking-at org-table-line-regexp)
  3858. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3859. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3860. (save-excursion (funcall function))
  3861. (or (looking-at org-table-line-regexp)
  3862. (forward-char 1)))
  3863. (re-search-forward org-table-any-border-regexp nil 1)))
  3864. (unless quietly (message "Mapping tables: done")))
  3865. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3866. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3867. (declare-function org-resolve-clocks "org-clock"
  3868. (&optional also-non-dangling-p prompt last-valid))
  3869. (defun org-at-TBLFM-p (&optional pos)
  3870. "Non-nil when point (or POS) is in #+TBLFM line."
  3871. (save-excursion
  3872. (goto-char (or pos (point)))
  3873. (beginning-of-line)
  3874. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3875. (eq (org-element-type (org-element-at-point)) 'table))))
  3876. (defvar org-clock-start-time)
  3877. (defvar org-clock-marker (make-marker)
  3878. "Marker recording the last clock-in.")
  3879. (defvar org-clock-hd-marker (make-marker)
  3880. "Marker recording the last clock-in, but the headline position.")
  3881. (defvar org-clock-heading ""
  3882. "The heading of the current clock entry.")
  3883. (defun org-clock-is-active ()
  3884. "Return the buffer where the clock is currently running.
  3885. Return nil if no clock is running."
  3886. (marker-buffer org-clock-marker))
  3887. (defun org-check-running-clock ()
  3888. "Check if the current buffer contains the running clock.
  3889. If yes, offer to stop it and to save the buffer with the changes."
  3890. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3891. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3892. (buffer-name))))
  3893. (org-clock-out)
  3894. (when (y-or-n-p "Save changed buffer?")
  3895. (save-buffer))))
  3896. (defun org-clocktable-try-shift (dir n)
  3897. "Check if this line starts a clock table, if yes, shift the time block."
  3898. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3899. (org-clocktable-shift dir n)))
  3900. ;;;###autoload
  3901. (defun org-clock-persistence-insinuate ()
  3902. "Set up hooks for clock persistence."
  3903. (require 'org-clock)
  3904. (add-hook 'org-mode-hook 'org-clock-load)
  3905. (add-hook 'kill-emacs-hook 'org-clock-save))
  3906. (defgroup org-archive nil
  3907. "Options concerning archiving in Org mode."
  3908. :tag "Org Archive"
  3909. :group 'org-structure)
  3910. (defcustom org-archive-location "%s_archive::"
  3911. "The location where subtrees should be archived.
  3912. The value of this variable is a string, consisting of two parts,
  3913. separated by a double-colon. The first part is a filename and
  3914. the second part is a headline.
  3915. When the filename is omitted, archiving happens in the same file.
  3916. %s in the filename will be replaced by the current file
  3917. name (without the directory part). Archiving to a different file
  3918. is useful to keep archived entries from contributing to the
  3919. Org Agenda.
  3920. The archived entries will be filed as subtrees of the specified
  3921. headline. When the headline is omitted, the subtrees are simply
  3922. filed away at the end of the file, as top-level entries. Also in
  3923. the heading you can use %s to represent the file name, this can be
  3924. useful when using the same archive for a number of different files.
  3925. Here are a few examples:
  3926. \"%s_archive::\"
  3927. If the current file is Projects.org, archive in file
  3928. Projects.org_archive, as top-level trees. This is the default.
  3929. \"::* Archived Tasks\"
  3930. Archive in the current file, under the top-level headline
  3931. \"* Archived Tasks\".
  3932. \"~/org/archive.org::\"
  3933. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3934. \"~/org/archive.org::* From %s\"
  3935. Archive in file ~/org/archive.org (absolute path), under headlines
  3936. \"From FILENAME\" where file name is the current file name.
  3937. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3938. The \"datetree/\" string is special, signifying to archive
  3939. items to the datetree. Items are placed in either the CLOSED
  3940. date of the item, or the current date if there is no CLOSED date.
  3941. The heading will be a subentry to the current date. There doesn't
  3942. need to be a heading, but there always needs to be a slash after
  3943. datetree. For example, to store archived items directly in the
  3944. datetree, use \"~/org/datetree.org::datetree/\".
  3945. \"basement::** Finished Tasks\"
  3946. Archive in file ./basement (relative path), as level 3 trees
  3947. below the level 2 heading \"** Finished Tasks\".
  3948. You may set this option on a per-file basis by adding to the buffer a
  3949. line like
  3950. #+ARCHIVE: basement::** Finished Tasks
  3951. You may also define it locally for a subtree by setting an ARCHIVE property
  3952. in the entry. If such a property is found in an entry, or anywhere up
  3953. the hierarchy, it will be used."
  3954. :group 'org-archive
  3955. :type 'string)
  3956. (defcustom org-agenda-skip-archived-trees t
  3957. "Non-nil means the agenda will skip any items located in archived trees.
  3958. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3959. variable is no longer recommended, you should leave it at the value t.
  3960. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3961. :group 'org-archive
  3962. :group 'org-agenda-skip
  3963. :type 'boolean)
  3964. (defcustom org-columns-skip-archived-trees t
  3965. "Non-nil means ignore archived trees when creating column view."
  3966. :group 'org-archive
  3967. :group 'org-properties
  3968. :type 'boolean)
  3969. (defcustom org-cycle-open-archived-trees nil
  3970. "Non-nil means `org-cycle' will open archived trees.
  3971. An archived tree is a tree marked with the tag ARCHIVE.
  3972. When nil, archived trees will stay folded. You can still open them with
  3973. normal outline commands like `show-all', but not with the cycling commands."
  3974. :group 'org-archive
  3975. :group 'org-cycle
  3976. :type 'boolean)
  3977. (defcustom org-sparse-tree-open-archived-trees nil
  3978. "Non-nil means sparse tree construction shows matches in archived trees.
  3979. When nil, matches in these trees are highlighted, but the trees are kept in
  3980. collapsed state."
  3981. :group 'org-archive
  3982. :group 'org-sparse-trees
  3983. :type 'boolean)
  3984. (defcustom org-sparse-tree-default-date-type nil
  3985. "The default date type when building a sparse tree.
  3986. When this is nil, a date is a scheduled or a deadline timestamp.
  3987. Otherwise, these types are allowed:
  3988. all: all timestamps
  3989. active: only active timestamps (<...>)
  3990. inactive: only inactive timestamps ([...])
  3991. scheduled: only scheduled timestamps
  3992. deadline: only deadline timestamps"
  3993. :type '(choice (const :tag "Scheduled or deadline" nil)
  3994. (const :tag "All timestamps" all)
  3995. (const :tag "Only active timestamps" active)
  3996. (const :tag "Only inactive timestamps" inactive)
  3997. (const :tag "Only scheduled timestamps" scheduled)
  3998. (const :tag "Only deadline timestamps" deadline)
  3999. (const :tag "Only closed timestamps" closed))
  4000. :version "26.1"
  4001. :package-version '(Org . "8.3")
  4002. :group 'org-sparse-trees)
  4003. (defun org-cycle-hide-archived-subtrees (state)
  4004. "Re-hide all archived subtrees after a visibility state change.
  4005. STATE should be one of the symbols listed in the docstring of
  4006. `org-cycle-hook'."
  4007. (when (and (not org-cycle-open-archived-trees)
  4008. (not (memq state '(overview folded))))
  4009. (save-excursion
  4010. (let* ((globalp (memq state '(contents all)))
  4011. (beg (if globalp (point-min) (point)))
  4012. (end (if globalp (point-max) (org-end-of-subtree t))))
  4013. (org-hide-archived-subtrees beg end)
  4014. (goto-char beg)
  4015. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4016. (message "%s" (substitute-command-keys
  4017. "Subtree is archived and stays closed. Use \
  4018. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4019. (defun org-force-cycle-archived ()
  4020. "Cycle subtree even if it is archived."
  4021. (interactive)
  4022. (setq this-command 'org-cycle)
  4023. (let ((org-cycle-open-archived-trees t))
  4024. (call-interactively 'org-cycle)))
  4025. (defun org-hide-archived-subtrees (beg end)
  4026. "Re-hide all archived subtrees after a visibility state change."
  4027. (org-with-wide-buffer
  4028. (let ((case-fold-search nil)
  4029. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4030. (goto-char beg)
  4031. ;; Include headline point is currently on.
  4032. (beginning-of-line)
  4033. (while (and (< (point) end) (re-search-forward re end t))
  4034. (when (member org-archive-tag (org-get-tags nil t))
  4035. (org-flag-subtree t)
  4036. (org-end-of-subtree t))))))
  4037. (defun org-flag-subtree (flag)
  4038. (save-excursion
  4039. (org-back-to-heading t)
  4040. (org-flag-region (line-end-position)
  4041. (progn (org-end-of-subtree t) (point))
  4042. flag
  4043. 'outline)))
  4044. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4045. ;; Declare Column View Code
  4046. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4047. (declare-function org-columns-compute "org-colview" (property))
  4048. ;; Declare ID code
  4049. (declare-function org-id-store-link "org-id")
  4050. (declare-function org-id-locations-load "org-id")
  4051. (declare-function org-id-locations-save "org-id")
  4052. (defvar org-id-track-globally)
  4053. ;;; Variables for pre-computed regular expressions, all buffer local
  4054. (defvar-local org-todo-regexp nil
  4055. "Matches any of the TODO state keywords.
  4056. Since TODO keywords are case-sensitive, `case-fold-search' is
  4057. expected to be bound to nil when matching against this regexp.")
  4058. (defvar-local org-not-done-regexp nil
  4059. "Matches any of the TODO state keywords except the last one.
  4060. Since TODO keywords are case-sensitive, `case-fold-search' is
  4061. expected to be bound to nil when matching against this regexp.")
  4062. (defvar-local org-not-done-heading-regexp nil
  4063. "Matches a TODO headline that is not done.
  4064. Since TODO keywords are case-sensitive, `case-fold-search' is
  4065. expected to be bound to nil when matching against this regexp.")
  4066. (defvar-local org-todo-line-regexp nil
  4067. "Matches a headline and puts TODO state into group 2 if present.
  4068. Since TODO keywords are case-sensitive, `case-fold-search' is
  4069. expected to be bound to nil when matching against this regexp.")
  4070. (defvar-local org-complex-heading-regexp nil
  4071. "Matches a headline and puts everything into groups:
  4072. group 1: Stars
  4073. group 2: The TODO keyword, maybe
  4074. group 3: Priority cookie
  4075. group 4: True headline
  4076. group 5: Tags
  4077. Since TODO keywords are case-sensitive, `case-fold-search' is
  4078. expected to be bound to nil when matching against this regexp.")
  4079. (defvar-local org-complex-heading-regexp-format nil
  4080. "Printf format to make regexp to match an exact headline.
  4081. This regexp will match the headline of any node which has the
  4082. exact headline text that is put into the format, but may have any
  4083. TODO state, priority and tags.")
  4084. (defvar-local org-todo-line-tags-regexp nil
  4085. "Matches a headline and puts TODO state into group 2 if present.
  4086. Also put tags into group 4 if tags are present.")
  4087. (defconst org-plain-time-of-day-regexp
  4088. (concat
  4089. "\\(\\<[012]?[0-9]"
  4090. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4091. "\\(--?"
  4092. "\\(\\<[012]?[0-9]"
  4093. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4094. "\\)?")
  4095. "Regular expression to match a plain time or time range.
  4096. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4097. groups carry important information:
  4098. 0 the full match
  4099. 1 the first time, range or not
  4100. 8 the second time, if it is a range.")
  4101. (defconst org-plain-time-extension-regexp
  4102. (concat
  4103. "\\(\\<[012]?[0-9]"
  4104. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4105. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4106. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4107. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4108. groups carry important information:
  4109. 0 the full match
  4110. 7 hours of duration
  4111. 9 minutes of duration")
  4112. (defconst org-stamp-time-of-day-regexp
  4113. (concat
  4114. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4115. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4116. "\\(--?"
  4117. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4118. "Regular expression to match a timestamp time or time range.
  4119. After a match, the following groups carry important information:
  4120. 0 the full match
  4121. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4122. 2 the first time, range or not
  4123. 4 the second time, if it is a range.")
  4124. (defconst org-startup-options
  4125. '(("fold" org-startup-folded t)
  4126. ("overview" org-startup-folded t)
  4127. ("nofold" org-startup-folded nil)
  4128. ("showall" org-startup-folded nil)
  4129. ("showeverything" org-startup-folded showeverything)
  4130. ("content" org-startup-folded content)
  4131. ("indent" org-startup-indented t)
  4132. ("noindent" org-startup-indented nil)
  4133. ("hidestars" org-hide-leading-stars t)
  4134. ("showstars" org-hide-leading-stars nil)
  4135. ("odd" org-odd-levels-only t)
  4136. ("oddeven" org-odd-levels-only nil)
  4137. ("align" org-startup-align-all-tables t)
  4138. ("noalign" org-startup-align-all-tables nil)
  4139. ("shrink" org-startup-shrink-all-tables t)
  4140. ("inlineimages" org-startup-with-inline-images t)
  4141. ("noinlineimages" org-startup-with-inline-images nil)
  4142. ("latexpreview" org-startup-with-latex-preview t)
  4143. ("nolatexpreview" org-startup-with-latex-preview nil)
  4144. ("customtime" org-display-custom-times t)
  4145. ("logdone" org-log-done time)
  4146. ("lognotedone" org-log-done note)
  4147. ("nologdone" org-log-done nil)
  4148. ("lognoteclock-out" org-log-note-clock-out t)
  4149. ("nolognoteclock-out" org-log-note-clock-out nil)
  4150. ("logrepeat" org-log-repeat state)
  4151. ("lognoterepeat" org-log-repeat note)
  4152. ("logdrawer" org-log-into-drawer t)
  4153. ("nologdrawer" org-log-into-drawer nil)
  4154. ("logstatesreversed" org-log-states-order-reversed t)
  4155. ("nologstatesreversed" org-log-states-order-reversed nil)
  4156. ("nologrepeat" org-log-repeat nil)
  4157. ("logreschedule" org-log-reschedule time)
  4158. ("lognotereschedule" org-log-reschedule note)
  4159. ("nologreschedule" org-log-reschedule nil)
  4160. ("logredeadline" org-log-redeadline time)
  4161. ("lognoteredeadline" org-log-redeadline note)
  4162. ("nologredeadline" org-log-redeadline nil)
  4163. ("logrefile" org-log-refile time)
  4164. ("lognoterefile" org-log-refile note)
  4165. ("nologrefile" org-log-refile nil)
  4166. ("fninline" org-footnote-define-inline t)
  4167. ("nofninline" org-footnote-define-inline nil)
  4168. ("fnlocal" org-footnote-section nil)
  4169. ("fnauto" org-footnote-auto-label t)
  4170. ("fnprompt" org-footnote-auto-label nil)
  4171. ("fnconfirm" org-footnote-auto-label confirm)
  4172. ("fnplain" org-footnote-auto-label plain)
  4173. ("fnadjust" org-footnote-auto-adjust t)
  4174. ("nofnadjust" org-footnote-auto-adjust nil)
  4175. ("constcgs" constants-unit-system cgs)
  4176. ("constSI" constants-unit-system SI)
  4177. ("noptag" org-tag-persistent-alist nil)
  4178. ("hideblocks" org-hide-block-startup t)
  4179. ("nohideblocks" org-hide-block-startup nil)
  4180. ("beamer" org-startup-with-beamer-mode t)
  4181. ("entitiespretty" org-pretty-entities t)
  4182. ("entitiesplain" org-pretty-entities nil))
  4183. "Variable associated with STARTUP options for Org.
  4184. Each element is a list of three items: the startup options (as written
  4185. in the #+STARTUP line), the corresponding variable, and the value to set
  4186. this variable to if the option is found. An optional forth element PUSH
  4187. means to push this value onto the list in the variable.")
  4188. (defcustom org-group-tags t
  4189. "When non-nil (the default), use group tags.
  4190. This can be turned on/off through `org-toggle-tags-groups'."
  4191. :group 'org-tags
  4192. :group 'org-startup
  4193. :type 'boolean)
  4194. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4195. (defun org-toggle-tags-groups ()
  4196. "Toggle support for group tags.
  4197. Support for group tags is controlled by the option
  4198. `org-group-tags', which is non-nil by default."
  4199. (interactive)
  4200. (setq org-group-tags (not org-group-tags))
  4201. (cond ((and (derived-mode-p 'org-agenda-mode)
  4202. org-group-tags)
  4203. (org-agenda-redo))
  4204. ((derived-mode-p 'org-mode)
  4205. (let ((org-inhibit-startup t)) (org-mode))))
  4206. (message "Groups tags support has been turned %s"
  4207. (if org-group-tags "on" "off")))
  4208. (defun org--tag-add-to-alist (alist1 alist2)
  4209. "Merge tags from ALIST1 into ALIST2.
  4210. Duplicates tags outside a group are removed. Keywords and order
  4211. are preserved.
  4212. The function assumes ALIST1 and ALIST2 are proper tag alists.
  4213. See `org-tag-alist' for their structure."
  4214. (cond
  4215. ((null alist2) alist1)
  4216. ((null alist1) alist2)
  4217. (t
  4218. (let ((to-add nil)
  4219. (group-flag nil))
  4220. (dolist (tag-pair alist1)
  4221. (pcase tag-pair
  4222. (`(,(or :startgrouptag :startgroup))
  4223. (setq group-flag t)
  4224. (push tag-pair to-add))
  4225. (`(,(or :endgrouptag :endgroup))
  4226. (setq group-flag nil)
  4227. (push tag-pair to-add))
  4228. (`(,(or :grouptags :newline))
  4229. (push tag-pair to-add))
  4230. (`(,tag . ,_)
  4231. ;; Remove duplicates from ALIST1, unless they are in
  4232. ;; a group. Indeed, it makes sense to have a tag appear in
  4233. ;; multiple groups.
  4234. (when (or group-flag (not (assoc tag alist2)))
  4235. (push tag-pair to-add)))
  4236. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  4237. ;; Preserve order of ALIST1.
  4238. (append (nreverse to-add) alist2)))))
  4239. (defun org-set-regexps-and-options (&optional tags-only)
  4240. "Precompute regular expressions used in the current buffer.
  4241. When optional argument TAGS-ONLY is non-nil, only compute tags
  4242. related expressions."
  4243. (when (derived-mode-p 'org-mode)
  4244. (let ((alist (org--setup-collect-keywords
  4245. (org-make-options-regexp
  4246. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4247. (and (not tags-only)
  4248. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4249. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4250. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4251. ;; Startup options. Get this early since it does change
  4252. ;; behavior for other options (e.g., tags).
  4253. (let ((startup (cdr (assq 'startup alist))))
  4254. (dolist (option startup)
  4255. (let ((entry (assoc-string option org-startup-options t)))
  4256. (when entry
  4257. (let ((var (nth 1 entry))
  4258. (val (nth 2 entry)))
  4259. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4260. (unless (listp (symbol-value var))
  4261. (set (make-local-variable var) nil))
  4262. (add-to-list var val)))))))
  4263. (setq-local org-file-tags
  4264. (mapcar #'org-add-prop-inherited
  4265. (cdr (assq 'filetags alist))))
  4266. (setq org-current-tag-alist
  4267. (org--tag-add-to-alist
  4268. org-tag-persistent-alist
  4269. (let ((tags (cdr (assq 'tags alist))))
  4270. (if tags (org-tag-string-to-alist tags)
  4271. org-tag-alist))))
  4272. (setq org-tag-groups-alist
  4273. (org-tag-alist-to-groups org-current-tag-alist))
  4274. (unless tags-only
  4275. ;; File properties.
  4276. (setq-local org-file-properties (cdr (assq 'property alist)))
  4277. ;; Archive location.
  4278. (let ((archive (cdr (assq 'archive alist))))
  4279. (when archive (setq-local org-archive-location archive)))
  4280. ;; Category.
  4281. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4282. (when cat
  4283. (setq-local org-category (intern cat))
  4284. (setq-local org-file-properties
  4285. (org--update-property-plist
  4286. "CATEGORY" cat org-file-properties))))
  4287. ;; Columns.
  4288. (let ((column (cdr (assq 'columns alist))))
  4289. (when column (setq-local org-columns-default-format column)))
  4290. ;; Constants.
  4291. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4292. ;; Link abbreviations.
  4293. (let ((links (cdr (assq 'link alist))))
  4294. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4295. ;; Priorities.
  4296. (let ((priorities (cdr (assq 'priorities alist))))
  4297. (when priorities
  4298. (setq-local org-highest-priority (nth 0 priorities))
  4299. (setq-local org-lowest-priority (nth 1 priorities))
  4300. (setq-local org-default-priority (nth 2 priorities))))
  4301. ;; Scripts.
  4302. (let ((scripts (assq 'scripts alist)))
  4303. (when scripts
  4304. (setq-local org-use-sub-superscripts (cdr scripts))))
  4305. ;; TODO keywords.
  4306. (setq-local org-todo-kwd-alist nil)
  4307. (setq-local org-todo-key-alist nil)
  4308. (setq-local org-todo-key-trigger nil)
  4309. (setq-local org-todo-keywords-1 nil)
  4310. (setq-local org-done-keywords nil)
  4311. (setq-local org-todo-heads nil)
  4312. (setq-local org-todo-sets nil)
  4313. (setq-local org-todo-log-states nil)
  4314. (let ((todo-sequences
  4315. (or (nreverse (cdr (assq 'todo alist)))
  4316. (let ((d (default-value 'org-todo-keywords)))
  4317. (if (not (stringp (car d))) d
  4318. ;; XXX: Backward compatibility code.
  4319. (list (cons org-todo-interpretation d)))))))
  4320. (dolist (sequence todo-sequences)
  4321. (let* ((sequence (or (run-hook-with-args-until-success
  4322. 'org-todo-setup-filter-hook sequence)
  4323. sequence))
  4324. (sequence-type (car sequence))
  4325. (keywords (cdr sequence))
  4326. (sep (member "|" keywords))
  4327. names alist)
  4328. (dolist (k (remove "|" keywords))
  4329. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4330. k)
  4331. (error "Invalid TODO keyword %s" k))
  4332. (let ((name (match-string 1 k))
  4333. (key (match-string 2 k))
  4334. (log (org-extract-log-state-settings k)))
  4335. (push name names)
  4336. (push (cons name (and key (string-to-char key))) alist)
  4337. (when log (push log org-todo-log-states))))
  4338. (let* ((names (nreverse names))
  4339. (done (if sep (org-remove-keyword-keys (cdr sep))
  4340. (last names)))
  4341. (head (car names))
  4342. (tail (list sequence-type head (car done) (org-last done))))
  4343. (add-to-list 'org-todo-heads head 'append)
  4344. (push names org-todo-sets)
  4345. (setq org-done-keywords (append org-done-keywords done nil))
  4346. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4347. (setq org-todo-key-alist
  4348. (append org-todo-key-alist
  4349. (and alist
  4350. (append '((:startgroup))
  4351. (nreverse alist)
  4352. '((:endgroup))))))
  4353. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4354. (setq org-todo-sets (nreverse org-todo-sets)
  4355. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4356. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4357. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4358. ;; Compute the regular expressions and other local variables.
  4359. ;; Using `org-outline-regexp-bol' would complicate them much,
  4360. ;; because of the fixed white space at the end of that string.
  4361. (unless org-done-keywords
  4362. (setq org-done-keywords
  4363. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4364. (setq org-not-done-keywords
  4365. (org-delete-all org-done-keywords
  4366. (copy-sequence org-todo-keywords-1))
  4367. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4368. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4369. org-not-done-heading-regexp
  4370. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4371. org-todo-line-regexp
  4372. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4373. org-complex-heading-regexp
  4374. (concat "^\\(\\*+\\)"
  4375. "\\(?: +" org-todo-regexp "\\)?"
  4376. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4377. "\\(?: +\\(.*?\\)\\)??"
  4378. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4379. "[ \t]*$")
  4380. org-complex-heading-regexp-format
  4381. (concat "^\\(\\*+\\)"
  4382. "\\(?: +" org-todo-regexp "\\)?"
  4383. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4384. "\\(?: +"
  4385. ;; Stats cookies can be stuck to body.
  4386. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4387. "\\(%s\\)"
  4388. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4389. "\\)"
  4390. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4391. "[ \t]*$")
  4392. org-todo-line-tags-regexp
  4393. (concat "^\\(\\*+\\)"
  4394. "\\(?: +" org-todo-regexp "\\)?"
  4395. "\\(?: +\\(.*?\\)\\)??"
  4396. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4397. "[ \t]*$"))
  4398. (org-compute-latex-and-related-regexp)))))
  4399. (defun org--setup-collect-keywords (regexp &optional files alist)
  4400. "Return setup keywords values as an alist.
  4401. REGEXP matches a subset of setup keywords. FILES is a list of
  4402. file names already visited. It is used to avoid circular setup
  4403. files. ALIST, when non-nil, is the alist computed so far.
  4404. Return value contains the following keys: `archive', `category',
  4405. `columns', `constants', `filetags', `link', `priorities',
  4406. `property', `scripts', `startup', `tags' and `todo'."
  4407. (org-with-wide-buffer
  4408. (goto-char (point-min))
  4409. (let ((case-fold-search t))
  4410. (while (re-search-forward regexp nil t)
  4411. (let ((element (org-element-at-point)))
  4412. (when (eq (org-element-type element) 'keyword)
  4413. (let ((key (org-element-property :key element))
  4414. (value (org-element-property :value element)))
  4415. (cond
  4416. ((equal key "ARCHIVE")
  4417. (when (org-string-nw-p value)
  4418. (push (cons 'archive value) alist)))
  4419. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4420. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4421. ((equal key "CONSTANTS")
  4422. (let* ((constants (assq 'constants alist))
  4423. (store (cdr constants)))
  4424. (dolist (pair (split-string value))
  4425. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4426. pair)
  4427. (let* ((name (match-string 1 pair))
  4428. (value (match-string 2 pair))
  4429. (old (assoc name store)))
  4430. (if old (setcdr old value)
  4431. (push (cons name value) store)))))
  4432. (if constants (setcdr constants store)
  4433. (push (cons 'constants store) alist))))
  4434. ((equal key "FILETAGS")
  4435. (when (org-string-nw-p value)
  4436. (let ((old (assq 'filetags alist))
  4437. (new (apply #'nconc
  4438. (mapcar (lambda (x) (org-split-string x ":"))
  4439. (split-string value)))))
  4440. (if old (setcdr old (append new (cdr old)))
  4441. (push (cons 'filetags new) alist)))))
  4442. ((equal key "LINK")
  4443. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4444. (let ((links (assq 'link alist))
  4445. (pair (cons (match-string-no-properties 1 value)
  4446. (match-string-no-properties 2 value))))
  4447. (if links (push pair (cdr links))
  4448. (push (list 'link pair) alist)))))
  4449. ((equal key "OPTIONS")
  4450. (when (and (org-string-nw-p value)
  4451. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4452. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4453. ((equal key "PRIORITIES")
  4454. (push (cons 'priorities
  4455. (let ((prio (split-string value)))
  4456. (if (< (length prio) 3) '(?A ?C ?B)
  4457. (mapcar #'string-to-char prio))))
  4458. alist))
  4459. ((equal key "PROPERTY")
  4460. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4461. (let* ((property (assq 'property alist))
  4462. (value (org--update-property-plist
  4463. (match-string-no-properties 1 value)
  4464. (match-string-no-properties 2 value)
  4465. (cdr property))))
  4466. (if property (setcdr property value)
  4467. (push (cons 'property value) alist)))))
  4468. ((equal key "STARTUP")
  4469. (let ((startup (assq 'startup alist)))
  4470. (if startup
  4471. (setcdr startup
  4472. (append (cdr startup) (split-string value)))
  4473. (push (cons 'startup (split-string value)) alist))))
  4474. ((equal key "TAGS")
  4475. (let ((tag-cell (assq 'tags alist)))
  4476. (if tag-cell
  4477. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4478. (push (cons 'tags value) alist))))
  4479. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4480. (let ((todo (assq 'todo alist))
  4481. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4482. (split-string value))))
  4483. (if todo (push value (cdr todo))
  4484. (push (list 'todo value) alist))))
  4485. ((equal key "SETUPFILE")
  4486. (unless buffer-read-only ; Do not check in Gnus messages.
  4487. (let ((f (and (org-string-nw-p value)
  4488. (expand-file-name
  4489. (org-unbracket-string "\"" "\"" value)))))
  4490. (when (and f (file-readable-p f) (not (member f files)))
  4491. (with-temp-buffer
  4492. (setq default-directory (file-name-directory f))
  4493. (insert-file-contents f)
  4494. (setq alist
  4495. ;; Fake Org mode to benefit from cache
  4496. ;; without recurring needlessly.
  4497. (let ((major-mode 'org-mode))
  4498. (org--setup-collect-keywords
  4499. regexp (cons f files) alist)))))))))))))))
  4500. alist)
  4501. (defun org-tag-string-to-alist (s)
  4502. "Return tag alist associated to string S.
  4503. S is a value for TAGS keyword or produced with
  4504. `org-tag-alist-to-string'. Return value is an alist suitable for
  4505. `org-tag-alist' or `org-tag-persistent-alist'."
  4506. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4507. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  4508. "\\(?:(\\(.\\))\\)?\\'"))
  4509. alist group-flag)
  4510. (dolist (tokens lines (cdr (nreverse alist)))
  4511. (push '(:newline) alist)
  4512. (while tokens
  4513. (let ((token (pop tokens)))
  4514. (pcase token
  4515. ("{"
  4516. (push '(:startgroup) alist)
  4517. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4518. ("}"
  4519. (push '(:endgroup) alist)
  4520. (setq group-flag nil))
  4521. ("["
  4522. (push '(:startgrouptag) alist)
  4523. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4524. ("]"
  4525. (push '(:endgrouptag) alist)
  4526. (setq group-flag nil))
  4527. (":"
  4528. (push '(:grouptags) alist))
  4529. ((guard (string-match tag-re token))
  4530. (let ((tag (match-string 1 token))
  4531. (key (and (match-beginning 2)
  4532. (string-to-char (match-string 2 token)))))
  4533. ;; Push all tags in groups, no matter if they already
  4534. ;; appear somewhere else in the list.
  4535. (when (or group-flag (not (assoc tag alist)))
  4536. (push (cons tag key) alist))))))))))
  4537. (defun org-tag-alist-to-string (alist &optional skip-key)
  4538. "Return tag string associated to ALIST.
  4539. ALIST is an alist, as defined in `org-tag-alist' or
  4540. `org-tag-persistent-alist', or produced with
  4541. `org-tag-string-to-alist'.
  4542. Return value is a string suitable as a value for \"TAGS\"
  4543. keyword.
  4544. When optional argument SKIP-KEY is non-nil, skip selection keys
  4545. next to tags."
  4546. (mapconcat (lambda (token)
  4547. (pcase token
  4548. (`(:startgroup) "{")
  4549. (`(:endgroup) "}")
  4550. (`(:startgrouptag) "[")
  4551. (`(:endgrouptag) "]")
  4552. (`(:grouptags) ":")
  4553. (`(:newline) "\\n")
  4554. ((and
  4555. (guard (not skip-key))
  4556. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4557. (format "%s(%c)" tag key))
  4558. (`(,(and tag (pred stringp)) . ,_) tag)
  4559. (_ (user-error "Invalid tag token: %S" token))))
  4560. alist
  4561. " "))
  4562. (defun org-tag-alist-to-groups (alist)
  4563. "Return group alist from tag ALIST.
  4564. ALIST is an alist, as defined in `org-tag-alist' or
  4565. `org-tag-persistent-alist', or produced with
  4566. `org-tag-string-to-alist'. Return value is an alist following
  4567. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4568. a string, summarizing TAGS, as a list of strings."
  4569. (let (groups group-status current-group)
  4570. (dolist (token alist (nreverse groups))
  4571. (pcase token
  4572. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4573. (`(,(or :endgroup :endgrouptag))
  4574. (when (eq group-status 'append)
  4575. (push (nreverse current-group) groups))
  4576. (setq group-status nil current-group nil))
  4577. (`(:grouptags) (setq group-status 'append))
  4578. ((and `(,tag . ,_) (guard group-status))
  4579. (if (eq group-status 'append) (push tag current-group)
  4580. (setq current-group (list tag))))
  4581. (_ nil)))))
  4582. (defvar org--file-cache (make-hash-table :test #'equal)
  4583. "Hash table to store contents of files referenced via a URL.
  4584. This is the cache of file URLs read using `org-file-contents'.")
  4585. (defun org-reset-file-cache ()
  4586. "Reset the cache of files downloaded by `org-file-contents'."
  4587. (clrhash org--file-cache))
  4588. (defun org-file-url-p (file)
  4589. "Non-nil if FILE is a URL."
  4590. (require 'ffap)
  4591. (string-match-p ffap-url-regexp file))
  4592. (defun org-file-contents (file &optional noerror nocache)
  4593. "Return the contents of FILE, as a string.
  4594. FILE can be a file name or URL.
  4595. If FILE is a URL, download the contents. If the URL contents are
  4596. already cached in the `org--file-cache' hash table, the download step
  4597. is skipped.
  4598. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4599. from file or URL.
  4600. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4601. is available. This option applies only if FILE is a URL."
  4602. (let* ((is-url (org-file-url-p file))
  4603. (cache (and is-url
  4604. (not nocache)
  4605. (gethash file org--file-cache))))
  4606. (cond
  4607. (cache)
  4608. (is-url
  4609. (with-current-buffer (url-retrieve-synchronously file)
  4610. (goto-char (point-min))
  4611. ;; Move point to after the url-retrieve header.
  4612. (search-forward "\n\n" nil :move)
  4613. ;; Search for the success code only in the url-retrieve header.
  4614. (if (save-excursion
  4615. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4616. ;; Update the cache `org--file-cache' and return contents.
  4617. (puthash file
  4618. (buffer-substring-no-properties (point) (point-max))
  4619. org--file-cache)
  4620. (funcall (if noerror #'message #'user-error)
  4621. "Unable to fetch file from %S"
  4622. file))))
  4623. (t
  4624. (with-temp-buffer
  4625. (condition-case nil
  4626. (progn
  4627. (insert-file-contents file)
  4628. (buffer-string))
  4629. (file-error
  4630. (funcall (if noerror #'message #'user-error)
  4631. "Unable to read file %S"
  4632. file))))))))
  4633. (defun org-extract-log-state-settings (x)
  4634. "Extract the log state setting from a TODO keyword string.
  4635. This will extract info from a string like \"WAIT(w@/!)\"."
  4636. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4637. (let ((kw (match-string 1 x))
  4638. (log1 (and (match-end 3) (match-string 3 x)))
  4639. (log2 (and (match-end 4) (match-string 4 x))))
  4640. (and (or log1 log2)
  4641. (list kw
  4642. (and log1 (if (equal log1 "!") 'time 'note))
  4643. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4644. (defun org-remove-keyword-keys (list)
  4645. "Remove a pair of parenthesis at the end of each string in LIST."
  4646. (mapcar (lambda (x)
  4647. (if (string-match "(.*)$" x)
  4648. (substring x 0 (match-beginning 0))
  4649. x))
  4650. list))
  4651. (defun org-assign-fast-keys (alist)
  4652. "Assign fast keys to a keyword-key alist.
  4653. Respect keys that are already there."
  4654. (let (new e (alt ?0))
  4655. (while (setq e (pop alist))
  4656. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4657. (cdr e)) ;; Key already assigned.
  4658. (push e new)
  4659. (let ((clist (string-to-list (downcase (car e))))
  4660. (used (append new alist)))
  4661. (when (= (car clist) ?@)
  4662. (pop clist))
  4663. (while (and clist (rassoc (car clist) used))
  4664. (pop clist))
  4665. (unless clist
  4666. (while (rassoc alt used)
  4667. (cl-incf alt)))
  4668. (push (cons (car e) (or (car clist) alt)) new))))
  4669. (nreverse new)))
  4670. ;;; Some variables used in various places
  4671. (defvar org-window-configuration nil
  4672. "Used in various places to store a window configuration.")
  4673. (defvar org-selected-window nil
  4674. "Used in various places to store a window configuration.")
  4675. (defvar org-finish-function nil
  4676. "Function to be called when `C-c C-c' is used.
  4677. This is for getting out of special buffers like capture.")
  4678. (defvar org-last-state)
  4679. ;; Defined somewhere in this file, but used before definition.
  4680. (defvar org-entities) ;; defined in org-entities.el
  4681. (defvar org-struct-menu)
  4682. (defvar org-org-menu)
  4683. (defvar org-tbl-menu)
  4684. ;;;; Define the Org mode
  4685. ;; We use a before-change function to check if a table might need
  4686. ;; an update.
  4687. (defvar org-table-may-need-update t
  4688. "Indicates that a table might need an update.
  4689. This variable is set by `org-before-change-function'.
  4690. `org-table-align' sets it back to nil.")
  4691. (defun org-before-change-function (_beg _end)
  4692. "Every change indicates that a table might need an update."
  4693. (setq org-table-may-need-update t))
  4694. (defvar org-mode-map)
  4695. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4696. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4697. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4698. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4699. (defvar org-table-buffer-is-an nil)
  4700. (defvar bidi-paragraph-direction)
  4701. (defvar buffer-face-mode-face)
  4702. (require 'outline)
  4703. ;; Other stuff we need.
  4704. (require 'time-date)
  4705. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4706. (require 'easymenu)
  4707. (autoload 'easy-menu-add "easymenu")
  4708. (require 'overlay)
  4709. ;; (require 'org-macs) moved higher up in the file before it is first used
  4710. (require 'org-entities)
  4711. ;; (require 'org-compat) moved higher up in the file before it is first used
  4712. (require 'org-faces)
  4713. (require 'org-list)
  4714. (require 'org-pcomplete)
  4715. (require 'org-src)
  4716. (require 'org-footnote)
  4717. (require 'org-macro)
  4718. ;; babel
  4719. (require 'ob)
  4720. ;;;###autoload
  4721. (define-derived-mode org-mode outline-mode "Org"
  4722. "Outline-based notes management and organizer, alias
  4723. \"Carsten's outline-mode for keeping track of everything.\"
  4724. Org mode develops organizational tasks around a NOTES file which
  4725. contains information about projects as plain text. Org mode is
  4726. implemented on top of Outline mode, which is ideal to keep the content
  4727. of large files well structured. It supports ToDo items, deadlines and
  4728. time stamps, which magically appear in the diary listing of the Emacs
  4729. calendar. Tables are easily created with a built-in table editor.
  4730. Plain text URL-like links connect to websites, emails (VM), Usenet
  4731. messages (Gnus), BBDB entries, and any files related to the project.
  4732. For printing and sharing of notes, an Org file (or a part of it)
  4733. can be exported as a structured ASCII or HTML file.
  4734. The following commands are available:
  4735. \\{org-mode-map}"
  4736. ;; Get rid of Outline menus, they are not needed
  4737. ;; Need to do this here because define-derived-mode sets up
  4738. ;; the keymap so late. Still, it is a waste to call this each time
  4739. ;; we switch another buffer into Org mode.
  4740. (define-key org-mode-map [menu-bar headings] 'undefined)
  4741. (define-key org-mode-map [menu-bar hide] 'undefined)
  4742. (define-key org-mode-map [menu-bar show] 'undefined)
  4743. (org-load-modules-maybe)
  4744. (org-install-agenda-files-menu)
  4745. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4746. (add-to-invisibility-spec '(org-hide-block . t))
  4747. (add-to-invisibility-spec '(org-hide-drawer . t))
  4748. (setq-local outline-regexp org-outline-regexp)
  4749. (setq-local outline-level 'org-outline-level)
  4750. (setq bidi-paragraph-direction 'left-to-right)
  4751. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4752. (unless org-display-table
  4753. (setq org-display-table (make-display-table)))
  4754. (set-display-table-slot
  4755. org-display-table 4
  4756. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4757. org-ellipsis)))
  4758. (setq buffer-display-table org-display-table))
  4759. (org-set-regexps-and-options)
  4760. (org-set-font-lock-defaults)
  4761. (when (and org-tag-faces (not org-tags-special-faces-re))
  4762. ;; tag faces set outside customize.... force initialization.
  4763. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4764. ;; Calc embedded
  4765. (setq-local calc-embedded-open-mode "# ")
  4766. ;; Modify a few syntax entries
  4767. (modify-syntax-entry ?\" "\"")
  4768. (modify-syntax-entry ?\\ "_")
  4769. (modify-syntax-entry ?~ "_")
  4770. (modify-syntax-entry ?< "(>")
  4771. (modify-syntax-entry ?> ")<")
  4772. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4773. ;; Activate before-change-function
  4774. (setq-local org-table-may-need-update t)
  4775. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4776. ;; Check for running clock before killing a buffer
  4777. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4778. ;; Initialize macros templates.
  4779. (org-macro-initialize-templates)
  4780. ;; Initialize radio targets.
  4781. (org-update-radio-target-regexp)
  4782. ;; Indentation.
  4783. (setq-local indent-line-function 'org-indent-line)
  4784. (setq-local indent-region-function 'org-indent-region)
  4785. ;; Filling and auto-filling.
  4786. (org-setup-filling)
  4787. ;; Comments.
  4788. (org-setup-comments-handling)
  4789. ;; Initialize cache.
  4790. (org-element-cache-reset)
  4791. ;; Beginning/end of defun
  4792. (setq-local beginning-of-defun-function 'org-backward-element)
  4793. (setq-local end-of-defun-function
  4794. (lambda ()
  4795. (if (not (org-at-heading-p))
  4796. (org-forward-element)
  4797. (org-forward-element)
  4798. (forward-char -1))))
  4799. ;; Next error for sparse trees
  4800. (setq-local next-error-function 'org-occur-next-match)
  4801. ;; Make sure dependence stuff works reliably, even for users who set it
  4802. ;; too late :-(
  4803. (if org-enforce-todo-dependencies
  4804. (add-hook 'org-blocker-hook
  4805. 'org-block-todo-from-children-or-siblings-or-parent)
  4806. (remove-hook 'org-blocker-hook
  4807. 'org-block-todo-from-children-or-siblings-or-parent))
  4808. (if org-enforce-todo-checkbox-dependencies
  4809. (add-hook 'org-blocker-hook
  4810. 'org-block-todo-from-checkboxes)
  4811. (remove-hook 'org-blocker-hook
  4812. 'org-block-todo-from-checkboxes))
  4813. ;; Align options lines
  4814. (setq-local
  4815. align-mode-rules-list
  4816. '((org-in-buffer-settings
  4817. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4818. (modes . '(org-mode)))))
  4819. ;; Imenu
  4820. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4821. ;; Make isearch reveal context
  4822. (setq-local outline-isearch-open-invisible-function
  4823. (lambda (&rest _) (org-show-context 'isearch)))
  4824. ;; Setup the pcomplete hooks
  4825. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4826. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4827. (setq-local pcomplete-default-completion-function 'ignore)
  4828. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4829. (setq-local pcomplete-termination-string "")
  4830. (setq-local buffer-face-mode-face 'org-default)
  4831. ;; If empty file that did not turn on Org mode automatically, make
  4832. ;; it to.
  4833. (when (and org-insert-mode-line-in-empty-file
  4834. (called-interactively-p 'any)
  4835. (= (point-min) (point-max)))
  4836. (insert "# -*- mode: org -*-\n\n"))
  4837. (unless org-inhibit-startup
  4838. (org-unmodified
  4839. (when org-startup-with-beamer-mode (org-beamer-mode))
  4840. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4841. (org-table-map-tables
  4842. (cond ((and org-startup-align-all-tables
  4843. org-startup-shrink-all-tables)
  4844. (lambda () (org-table-align) (org-table-shrink)))
  4845. (org-startup-align-all-tables #'org-table-align)
  4846. (t #'org-table-shrink))
  4847. t))
  4848. (when org-startup-with-inline-images (org-display-inline-images))
  4849. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4850. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4851. (when org-startup-truncated (setq truncate-lines t))
  4852. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4853. (org-refresh-effort-properties)))
  4854. ;; Try to set `org-hide' face correctly.
  4855. (let ((foreground (org-find-invisible-foreground)))
  4856. (when foreground
  4857. (set-face-foreground 'org-hide foreground))))
  4858. ;; Update `customize-package-emacs-version-alist'
  4859. (add-to-list 'customize-package-emacs-version-alist
  4860. '(Org ("8.0" . "24.4")
  4861. ("8.1" . "24.4")
  4862. ("8.2" . "24.4")
  4863. ("8.2.7" . "24.4")
  4864. ("8.3" . "26.1")
  4865. ("9.0" . "26.1")
  4866. ("9.1" . "26.1")
  4867. ("9.2" . "27.1")))
  4868. (defvar org-mode-transpose-word-syntax-table
  4869. (let ((st (make-syntax-table text-mode-syntax-table)))
  4870. (dolist (c org-emphasis-alist st)
  4871. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4872. (when (fboundp 'abbrev-table-put)
  4873. (abbrev-table-put org-mode-abbrev-table
  4874. :parents (list text-mode-abbrev-table)))
  4875. (defun org-find-invisible-foreground ()
  4876. (let ((candidates (remove
  4877. "unspecified-bg"
  4878. (nconc
  4879. (list (face-background 'default)
  4880. (face-background 'org-default))
  4881. (mapcar
  4882. (lambda (alist)
  4883. (when (boundp alist)
  4884. (cdr (assq 'background-color (symbol-value alist)))))
  4885. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4886. (list (face-foreground 'org-hide))))))
  4887. (car (remove nil candidates))))
  4888. (defun org-current-time (&optional rounding-minutes past)
  4889. "Current time, possibly rounded to ROUNDING-MINUTES.
  4890. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4891. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4892. the rounding returns a past time."
  4893. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4894. (car org-time-stamp-rounding-minutes)))
  4895. (time (decode-time)) res)
  4896. (if (< r 1)
  4897. (current-time)
  4898. (setq res
  4899. (apply 'encode-time
  4900. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4901. (nthcdr 2 time))))
  4902. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4903. (seconds-to-time (- (float-time res) (* r 60)))
  4904. res))))
  4905. (defun org-today ()
  4906. "Return today date, considering `org-extend-today-until'."
  4907. (time-to-days
  4908. (time-subtract (current-time)
  4909. (list 0 (* 3600 org-extend-today-until) 0))))
  4910. ;;;; Font-Lock stuff, including the activators
  4911. (defvar org-mouse-map (make-sparse-keymap))
  4912. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4913. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4914. (when org-mouse-1-follows-link
  4915. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4916. (when org-tab-follows-link
  4917. (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
  4918. (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
  4919. (require 'font-lock)
  4920. (defconst org-non-link-chars "]\t\n\r<>")
  4921. (defvar org-link-types-re nil
  4922. "Matches a link that has a url-like prefix like \"http:\"")
  4923. (defvar org-link-re-with-space nil
  4924. "Matches a link with spaces, optional angular brackets around it.")
  4925. (defvar org-link-re-with-space2 nil
  4926. "Matches a link with spaces, optional angular brackets around it.")
  4927. (defvar org-link-re-with-space3 nil
  4928. "Matches a link with spaces, only for internal part in bracket links.")
  4929. (defvar org-angle-link-re nil
  4930. "Matches link with angular brackets, spaces are allowed.")
  4931. (defvar org-plain-link-re nil
  4932. "Matches plain link, without spaces.")
  4933. (defvar org-bracket-link-regexp nil
  4934. "Matches a link in double brackets.")
  4935. (defvar org-bracket-link-analytic-regexp nil
  4936. "Regular expression used to analyze links.
  4937. Here is what the match groups contain after a match:
  4938. 1: http:
  4939. 2: http
  4940. 3: path
  4941. 4: [desc]
  4942. 5: desc")
  4943. (defvar org-bracket-link-analytic-regexp++ nil
  4944. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4945. (defvar org-any-link-re nil
  4946. "Regular expression matching any link.")
  4947. (defconst org-match-sexp-depth 3
  4948. "Number of stacked braces for sub/superscript matching.")
  4949. (defun org-create-multibrace-regexp (left right n)
  4950. "Create a regular expression which will match a balanced sexp.
  4951. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4952. as single character strings.
  4953. The regexp returned will match the entire expression including the
  4954. delimiters. It will also define a single group which contains the
  4955. match except for the outermost delimiters. The maximum depth of
  4956. stacked delimiters is N. Escaping delimiters is not possible."
  4957. (let* ((nothing (concat "[^" left right "]*?"))
  4958. (or "\\|")
  4959. (re nothing)
  4960. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4961. (while (> n 1)
  4962. (setq n (1- n)
  4963. re (concat re or next)
  4964. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4965. (concat left "\\(" re "\\)" right)))
  4966. (defconst org-match-substring-regexp
  4967. (concat
  4968. "\\(\\S-\\)\\([_^]\\)\\("
  4969. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4970. "\\|"
  4971. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4972. "\\|"
  4973. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4974. "The regular expression matching a sub- or superscript.
  4975. Match groups:
  4976. 1: The preceding character (non-whitespace)
  4977. 2: The underscore or caret
  4978. 3: Entire sub/superscript
  4979. 4: (if present) the portion inside the braces/parens")
  4980. (defconst org-match-substring-with-braces-regexp
  4981. (concat
  4982. "\\(\\S-\\)\\([_^]\\)"
  4983. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4984. "The regular expression matching a sub- or superscript, forcing braces.
  4985. Match groups: see `org-match-substring-regexp'.")
  4986. (defun org-make-link-regexps ()
  4987. "Update the link regular expressions.
  4988. This should be called after the variable `org-link-parameters' has changed."
  4989. (let ((types-re (regexp-opt (org-link-types) t)))
  4990. (setq org-link-types-re
  4991. (concat "\\`" types-re ":")
  4992. org-link-re-with-space
  4993. (concat "<?" types-re ":"
  4994. "\\([^" org-non-link-chars " ]"
  4995. "[^" org-non-link-chars "]*"
  4996. "[^" org-non-link-chars " ]\\)>?")
  4997. org-link-re-with-space2
  4998. (concat "<?" types-re ":"
  4999. "\\([^" org-non-link-chars " ]"
  5000. "[^\t\n\r]*"
  5001. "[^" org-non-link-chars " ]\\)>?")
  5002. org-link-re-with-space3
  5003. (concat "<?" types-re ":"
  5004. "\\([^" org-non-link-chars " ]"
  5005. "[^\t\n\r]*\\)")
  5006. org-angle-link-re
  5007. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5008. types-re)
  5009. org-plain-link-re
  5010. (concat
  5011. "\\<" types-re ":"
  5012. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  5013. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5014. org-bracket-link-regexp
  5015. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5016. org-bracket-link-analytic-regexp
  5017. (concat
  5018. "\\[\\["
  5019. "\\(" types-re ":\\)?"
  5020. "\\([^]]+\\)"
  5021. "\\]"
  5022. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5023. "\\]")
  5024. org-bracket-link-analytic-regexp++
  5025. (concat
  5026. "\\[\\["
  5027. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5028. "\\([^]]+\\)"
  5029. "\\]"
  5030. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5031. "\\]")
  5032. org-any-link-re
  5033. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5034. org-angle-link-re "\\)\\|\\("
  5035. org-plain-link-re "\\)"))))
  5036. (org-make-link-regexps)
  5037. (defvar org-emph-face nil)
  5038. (defun org-do-emphasis-faces (limit)
  5039. "Run through the buffer and emphasize strings."
  5040. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  5041. (car org-emphasis-regexp-components))))
  5042. (catch :exit
  5043. (while (re-search-forward quick-re limit t)
  5044. (let* ((marker (match-string 2))
  5045. (verbatim? (member marker '("~" "="))))
  5046. (when (save-excursion
  5047. (goto-char (match-beginning 0))
  5048. (and
  5049. ;; Do not match table hlines.
  5050. (not (and (equal marker "+")
  5051. (org-match-line
  5052. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  5053. ;; Do not match headline stars. Do not consider
  5054. ;; stars of a headline as closing marker for bold
  5055. ;; markup either.
  5056. (not (and (equal marker "*")
  5057. (save-excursion
  5058. (forward-char)
  5059. (skip-chars-backward "*")
  5060. (looking-at-p org-outline-regexp-bol))))
  5061. ;; Match full emphasis markup regexp.
  5062. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  5063. ;; Do not span over paragraph boundaries.
  5064. (not (string-match-p org-element-paragraph-separate
  5065. (match-string 2)))
  5066. ;; Do not span over cells in table rows.
  5067. (not (and (save-match-data (org-match-line "[ \t]*|"))
  5068. (string-match-p "|" (match-string 4))))))
  5069. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5070. (font-lock-prepend-text-property
  5071. (match-beginning 2) (match-end 2) 'face face)
  5072. (when verbatim?
  5073. (org-remove-flyspell-overlays-in
  5074. (match-beginning 0) (match-end 0)))
  5075. (add-text-properties (match-beginning 2) (match-end 2)
  5076. '(font-lock-multiline t org-emphasis t))
  5077. (when org-hide-emphasis-markers
  5078. (add-text-properties (match-end 4) (match-beginning 5)
  5079. '(invisible org-link))
  5080. (add-text-properties (match-beginning 3) (match-end 3)
  5081. '(invisible org-link)))
  5082. (throw :exit t))))))))
  5083. (defun org-emphasize (&optional char)
  5084. "Insert or change an emphasis, i.e. a font like bold or italic.
  5085. If there is an active region, change that region to a new emphasis.
  5086. If there is no region, just insert the marker characters and position
  5087. the cursor between them.
  5088. CHAR should be the marker character. If it is a space, it means to
  5089. remove the emphasis of the selected region.
  5090. If CHAR is not given (for example in an interactive call) it will be
  5091. prompted for."
  5092. (interactive)
  5093. (let ((erc org-emphasis-regexp-components)
  5094. (string "") beg end move s)
  5095. (if (org-region-active-p)
  5096. (setq beg (region-beginning)
  5097. end (region-end)
  5098. string (buffer-substring beg end))
  5099. (setq move t))
  5100. (unless char
  5101. (message "Emphasis marker or tag: [%s]"
  5102. (mapconcat #'car org-emphasis-alist ""))
  5103. (setq char (read-char-exclusive)))
  5104. (if (equal char ?\s)
  5105. (setq s ""
  5106. move nil)
  5107. (unless (assoc (char-to-string char) org-emphasis-alist)
  5108. (user-error "No such emphasis marker: \"%c\"" char))
  5109. (setq s (char-to-string char)))
  5110. (while (and (> (length string) 1)
  5111. (equal (substring string 0 1) (substring string -1))
  5112. (assoc (substring string 0 1) org-emphasis-alist))
  5113. (setq string (substring string 1 -1)))
  5114. (setq string (concat s string s))
  5115. (when beg (delete-region beg end))
  5116. (unless (or (bolp)
  5117. (string-match (concat "[" (nth 0 erc) "\n]")
  5118. (char-to-string (char-before (point)))))
  5119. (insert " "))
  5120. (unless (or (eobp)
  5121. (string-match (concat "[" (nth 1 erc) "\n]")
  5122. (char-to-string (char-after (point)))))
  5123. (insert " ") (backward-char 1))
  5124. (insert string)
  5125. (and move (backward-char 1))))
  5126. (defconst org-nonsticky-props
  5127. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5128. (defsubst org-rear-nonsticky-at (pos)
  5129. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5130. (defun org-activate-links (limit)
  5131. "Add link properties to links.
  5132. This includes angle, plain, and bracket links."
  5133. (catch :exit
  5134. (while (re-search-forward org-any-link-re limit t)
  5135. (let* ((start (match-beginning 0))
  5136. (end (match-end 0))
  5137. (style (cond ((eq ?< (char-after start)) 'angle)
  5138. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5139. (t 'plain))))
  5140. (when (and (memq style org-highlight-links)
  5141. ;; Do not confuse plain links with tags.
  5142. (not (and (eq style 'plain)
  5143. (let ((face (get-text-property
  5144. (max (1- start) (point-min)) 'face)))
  5145. (if (consp face) (memq 'org-tag face)
  5146. (eq 'org-tag face))))))
  5147. (let* ((link-object (save-excursion
  5148. (goto-char start)
  5149. (save-match-data (org-element-link-parser))))
  5150. (link (org-element-property :raw-link link-object))
  5151. (type (org-element-property :type link-object))
  5152. (path (org-element-property :path link-object))
  5153. (properties ;for link's visible part
  5154. (list
  5155. 'face (pcase (org-link-get-parameter type :face)
  5156. ((and (pred functionp) face) (funcall face path))
  5157. ((and (pred facep) face) face)
  5158. ((and (pred consp) face) face) ;anonymous
  5159. (_ 'org-link))
  5160. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5161. 'highlight)
  5162. 'keymap (or (org-link-get-parameter type :keymap)
  5163. org-mouse-map)
  5164. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5165. ((and (pred stringp) echo) echo)
  5166. ((and (pred functionp) echo) echo)
  5167. (_ (concat "LINK: " link)))
  5168. 'htmlize-link (pcase (org-link-get-parameter type
  5169. :htmlize-link)
  5170. ((and (pred functionp) f) (funcall f))
  5171. (_ `(:uri ,link)))
  5172. 'font-lock-multiline t)))
  5173. (org-remove-flyspell-overlays-in start end)
  5174. (org-rear-nonsticky-at end)
  5175. (if (not (eq 'bracket style))
  5176. (add-text-properties start end properties)
  5177. ;; Handle invisible parts in bracket links.
  5178. (remove-text-properties start end '(invisible nil))
  5179. (let ((hidden
  5180. (append `(invisible
  5181. ,(or (org-link-get-parameter type :display)
  5182. 'org-link))
  5183. properties))
  5184. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5185. (visible-end (or (match-end 4) (match-end 2))))
  5186. (add-text-properties start visible-start hidden)
  5187. (add-text-properties visible-start visible-end properties)
  5188. (add-text-properties visible-end end hidden)
  5189. (org-rear-nonsticky-at visible-start)
  5190. (org-rear-nonsticky-at visible-end)))
  5191. (let ((f (org-link-get-parameter type :activate-func)))
  5192. (when (functionp f)
  5193. (funcall f start end path (eq style 'bracket))))
  5194. (throw :exit t))))) ;signal success
  5195. nil))
  5196. (defun org-activate-code (limit)
  5197. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5198. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5199. (remove-text-properties (match-beginning 0) (match-end 0)
  5200. '(display t invisible t intangible t))
  5201. t))
  5202. (defcustom org-src-fontify-natively t
  5203. "When non-nil, fontify code in code blocks.
  5204. See also the `org-block' face."
  5205. :type 'boolean
  5206. :version "26.1"
  5207. :package-version '(Org . "8.3")
  5208. :group 'org-appearance
  5209. :group 'org-babel)
  5210. (defcustom org-allow-promoting-top-level-subtree nil
  5211. "When non-nil, allow promoting a top level subtree.
  5212. The leading star of the top level headline will be replaced
  5213. by a #."
  5214. :type 'boolean
  5215. :version "24.1"
  5216. :group 'org-appearance)
  5217. (defun org-fontify-meta-lines-and-blocks (limit)
  5218. (condition-case nil
  5219. (org-fontify-meta-lines-and-blocks-1 limit)
  5220. (error (message "Org mode fontification error in %S at %d"
  5221. (current-buffer)
  5222. (line-number-at-pos)))))
  5223. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5224. "Fontify #+ lines and blocks."
  5225. (let ((case-fold-search t))
  5226. (when (re-search-forward
  5227. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5228. limit t)
  5229. (let ((beg (match-beginning 0))
  5230. (block-start (match-end 0))
  5231. (block-end nil)
  5232. (lang (match-string 7))
  5233. (beg1 (line-beginning-position 2))
  5234. (dc1 (downcase (match-string 2)))
  5235. (dc3 (downcase (match-string 3)))
  5236. end end1 quoting block-type)
  5237. (cond
  5238. ((and (match-end 4) (equal dc3 "+begin"))
  5239. ;; Truly a block
  5240. (setq block-type (downcase (match-string 5))
  5241. quoting (member block-type org-protecting-blocks))
  5242. (when (re-search-forward
  5243. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5244. nil t) ;; on purpose, we look further than LIMIT
  5245. (setq end (min (point-max) (match-end 0))
  5246. end1 (min (point-max) (1- (match-beginning 0))))
  5247. (setq block-end (match-beginning 0))
  5248. (when quoting
  5249. (org-remove-flyspell-overlays-in beg1 end1)
  5250. (remove-text-properties beg end
  5251. '(display t invisible t intangible t)))
  5252. (add-text-properties
  5253. beg end '(font-lock-fontified t font-lock-multiline t))
  5254. (add-text-properties beg beg1 '(face org-meta-line))
  5255. (org-remove-flyspell-overlays-in beg beg1)
  5256. (add-text-properties ; For end_src
  5257. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5258. (org-remove-flyspell-overlays-in end1 end)
  5259. (cond
  5260. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5261. (org-src-font-lock-fontify-block lang block-start block-end)
  5262. (add-text-properties beg1 block-end '(src-block t)))
  5263. (quoting
  5264. (add-text-properties beg1 (min (point-max) (1+ end1))
  5265. (list 'face
  5266. (list :inherit
  5267. (let ((face-name
  5268. (intern (format "org-block-%s" lang))))
  5269. (append (and (facep face-name) (list face-name))
  5270. '(org-block))))))) ; end of source block
  5271. ((not org-fontify-quote-and-verse-blocks))
  5272. ((string= block-type "quote")
  5273. (add-face-text-property
  5274. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5275. ((string= block-type "verse")
  5276. (add-face-text-property
  5277. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5278. (add-text-properties beg beg1 '(face org-block-begin-line))
  5279. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5280. '(face org-block-end-line))
  5281. t))
  5282. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5283. (org-remove-flyspell-overlays-in
  5284. (match-beginning 0)
  5285. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5286. (add-text-properties
  5287. beg (match-end 3)
  5288. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5289. '(font-lock-fontified t invisible t)
  5290. '(font-lock-fontified t face org-document-info-keyword)))
  5291. (add-text-properties
  5292. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5293. (if (string-equal dc1 "+title:")
  5294. '(font-lock-fontified t face org-document-title)
  5295. '(font-lock-fontified t face org-document-info))))
  5296. ((string-prefix-p "+caption" dc1)
  5297. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5298. (remove-text-properties (match-beginning 0) (match-end 0)
  5299. '(display t invisible t intangible t))
  5300. ;; Handle short captions.
  5301. (save-excursion
  5302. (beginning-of-line)
  5303. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5304. (add-text-properties (line-beginning-position) (match-end 1)
  5305. '(font-lock-fontified t face org-meta-line))
  5306. (add-text-properties (match-end 0) (line-end-position)
  5307. '(font-lock-fontified t face org-block))
  5308. t)
  5309. ((member dc3 '(" " ""))
  5310. (org-remove-flyspell-overlays-in beg (match-end 0))
  5311. (add-text-properties
  5312. beg (match-end 0)
  5313. '(font-lock-fontified t face font-lock-comment-face)))
  5314. (t ;; just any other in-buffer setting, but not indented
  5315. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5316. (remove-text-properties (match-beginning 0) (match-end 0)
  5317. '(display t invisible t intangible t))
  5318. (add-text-properties beg (match-end 0)
  5319. '(font-lock-fontified t face org-meta-line))
  5320. t))))))
  5321. (defun org-fontify-drawers (limit)
  5322. "Fontify drawers."
  5323. (when (re-search-forward org-drawer-regexp limit t)
  5324. (add-text-properties
  5325. (match-beginning 0) (match-end 0)
  5326. '(font-lock-fontified t face org-special-keyword))
  5327. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5328. t))
  5329. (defun org-fontify-macros (limit)
  5330. "Fontify macros."
  5331. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  5332. (let ((begin (match-beginning 0))
  5333. (opening-end (match-beginning 1)))
  5334. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  5335. (match-string 1))
  5336. (let ((end (match-end 1))
  5337. (closing-start (match-beginning 1)))
  5338. (add-text-properties
  5339. begin end
  5340. '(font-lock-multiline t font-lock-fontified t face org-macro))
  5341. (org-remove-flyspell-overlays-in begin end)
  5342. (when org-hide-macro-markers
  5343. (add-text-properties begin opening-end '(invisible t))
  5344. (add-text-properties closing-start end '(invisible t)))
  5345. t)))))
  5346. (defun org-activate-footnote-links (limit)
  5347. "Add text properties for footnotes."
  5348. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5349. (when fn
  5350. (let* ((beg (nth 1 fn))
  5351. (end (nth 2 fn))
  5352. (label (car fn))
  5353. (referencep (/= (line-beginning-position) beg)))
  5354. (when (and referencep (nth 3 fn))
  5355. (save-excursion
  5356. (goto-char beg)
  5357. (search-forward (or label "fn:"))
  5358. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5359. (add-text-properties beg end
  5360. (list 'mouse-face 'highlight
  5361. 'keymap org-mouse-map
  5362. 'help-echo
  5363. (if referencep "Footnote reference"
  5364. "Footnote definition")
  5365. 'font-lock-fontified t
  5366. 'font-lock-multiline t
  5367. 'face 'org-footnote))))))
  5368. (defun org-activate-dates (limit)
  5369. "Add text properties for dates."
  5370. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5371. (not (equal (char-before (match-beginning 0)) 91)))
  5372. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5373. (add-text-properties (match-beginning 0) (match-end 0)
  5374. (list 'mouse-face 'highlight
  5375. 'keymap org-mouse-map))
  5376. (org-rear-nonsticky-at (match-end 0))
  5377. (when org-display-custom-times
  5378. ;; If it's a date range, activate custom time for second date.
  5379. (when (match-end 3)
  5380. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5381. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5382. t))
  5383. (defvar-local org-target-link-regexp nil
  5384. "Regular expression matching radio targets in plain text.")
  5385. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5386. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5387. border border border))
  5388. "Regular expression matching a link target.")
  5389. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5390. "Regular expression matching a radio target.")
  5391. (defconst org-any-target-regexp
  5392. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5393. "Regular expression matching any target.")
  5394. (defun org-activate-target-links (limit)
  5395. "Add text properties for target matches."
  5396. (when org-target-link-regexp
  5397. (let ((case-fold-search t))
  5398. (when (re-search-forward org-target-link-regexp limit t)
  5399. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5400. (add-text-properties (match-beginning 1) (match-end 1)
  5401. (list 'mouse-face 'highlight
  5402. 'keymap org-mouse-map
  5403. 'help-echo "Radio target link"
  5404. 'org-linked-text t))
  5405. (org-rear-nonsticky-at (match-end 1))
  5406. t))))
  5407. (defun org-update-radio-target-regexp ()
  5408. "Find all radio targets in this file and update the regular expression.
  5409. Also refresh fontification if needed."
  5410. (interactive)
  5411. (let ((old-regexp org-target-link-regexp)
  5412. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5413. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5414. (targets
  5415. (org-with-wide-buffer
  5416. (goto-char (point-min))
  5417. (let (rtn)
  5418. (while (re-search-forward org-radio-target-regexp nil t)
  5419. ;; Make sure point is really within the object.
  5420. (backward-char)
  5421. (let ((obj (org-element-context)))
  5422. (when (eq (org-element-type obj) 'radio-target)
  5423. (cl-pushnew (org-element-property :value obj) rtn
  5424. :test #'equal))))
  5425. rtn))))
  5426. (setq org-target-link-regexp
  5427. (and targets
  5428. (concat before-re
  5429. (mapconcat
  5430. (lambda (x)
  5431. (replace-regexp-in-string
  5432. " +" "\\s-+" (regexp-quote x) t t))
  5433. targets
  5434. "\\|")
  5435. after-re)))
  5436. (unless (equal old-regexp org-target-link-regexp)
  5437. ;; Clean-up cache.
  5438. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5439. ((not org-target-link-regexp) old-regexp)
  5440. (t
  5441. (concat before-re
  5442. (mapconcat
  5443. (lambda (re)
  5444. (substring re (length before-re)
  5445. (- (length after-re))))
  5446. (list old-regexp org-target-link-regexp)
  5447. "\\|")
  5448. after-re)))))
  5449. (org-with-wide-buffer
  5450. (goto-char (point-min))
  5451. (while (re-search-forward regexp nil t)
  5452. (org-element-cache-refresh (match-beginning 1)))))
  5453. ;; Re fontify buffer.
  5454. (when (memq 'radio org-highlight-links)
  5455. (org-restart-font-lock)))))
  5456. (defvar org-latex-and-related-regexp nil
  5457. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5458. (defun org-compute-latex-and-related-regexp ()
  5459. "Compute regular expression for LaTeX, entities and sub/superscript.
  5460. Result depends on variable `org-highlight-latex-and-related'."
  5461. (setq-local
  5462. org-latex-and-related-regexp
  5463. (let* ((re-sub
  5464. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5465. ((eq org-use-sub-superscripts '{})
  5466. (list org-match-substring-with-braces-regexp))
  5467. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5468. (re-latex
  5469. (when (memq 'latex org-highlight-latex-and-related)
  5470. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5471. (delq nil
  5472. (mapcar (lambda (x)
  5473. (and (member (car x) matchers) (nth 1 x)))
  5474. org-latex-regexps)))))
  5475. (re-entities
  5476. (when (memq 'entities org-highlight-latex-and-related)
  5477. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5478. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5479. (defun org-do-latex-and-related (limit)
  5480. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5481. LIMIT bounds the search for syntax to highlight. Stop at first
  5482. highlighted object, if any. Return t if some highlighting was
  5483. done, nil otherwise."
  5484. (when (org-string-nw-p org-latex-and-related-regexp)
  5485. (catch 'found
  5486. (while (re-search-forward org-latex-and-related-regexp limit t)
  5487. (unless
  5488. (cl-some
  5489. (lambda (f)
  5490. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5491. (save-excursion
  5492. (goto-char (1+ (match-beginning 0)))
  5493. (face-at-point nil t)))
  5494. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5495. '(?_ ?^))
  5496. 1
  5497. 0)))
  5498. (font-lock-prepend-text-property
  5499. (+ offset (match-beginning 0)) (match-end 0)
  5500. 'face 'org-latex-and-related)
  5501. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5502. '(font-lock-multiline t)))
  5503. (throw 'found t)))
  5504. nil)))
  5505. (defun org-restart-font-lock ()
  5506. "Restart `font-lock-mode', to force refontification."
  5507. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5508. (font-lock-mode -1)
  5509. (font-lock-mode 1)))
  5510. (defun org-activate-tags (limit)
  5511. (when (re-search-forward org-tag-line-re limit t)
  5512. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5513. (add-text-properties (match-beginning 1) (match-end 1)
  5514. (list 'mouse-face 'highlight
  5515. 'keymap org-mouse-map))
  5516. (org-rear-nonsticky-at (match-end 1))
  5517. t))
  5518. (defun org-outline-level ()
  5519. "Compute the outline level of the heading at point.
  5520. If this is called at a normal headline, the level is the number
  5521. of stars. Use `org-reduced-level' to remove the effect of
  5522. `org-odd-levels'. Unlike to `org-current-level', this function
  5523. takes into consideration inlinetasks."
  5524. (org-with-wide-buffer
  5525. (end-of-line)
  5526. (if (re-search-backward org-outline-regexp-bol nil t)
  5527. (1- (- (match-end 0) (match-beginning 0)))
  5528. 0)))
  5529. (defvar org-font-lock-keywords nil)
  5530. (defsubst org-re-property (property &optional literal allow-null value)
  5531. "Return a regexp matching a PROPERTY line.
  5532. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5533. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5534. non-nil, match properties even without a value.
  5535. Match group 3 is set to the value when it exists. If there is no
  5536. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5537. With optional argument VALUE, match only property lines with
  5538. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5539. unless LITERAL is non-nil."
  5540. (concat
  5541. "^\\(?4:[ \t]*\\)"
  5542. (format "\\(?1::\\(?2:%s\\):\\)"
  5543. (if literal property (regexp-quote property)))
  5544. (cond (value
  5545. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5546. (if literal value (regexp-quote value))))
  5547. (allow-null
  5548. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5549. (t
  5550. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5551. (defconst org-property-re
  5552. (org-re-property "\\S-+" 'literal t)
  5553. "Regular expression matching a property line.
  5554. There are four matching groups:
  5555. 1: :PROPKEY: including the leading and trailing colon,
  5556. 2: PROPKEY without the leading and trailing colon,
  5557. 3: PROPVAL without leading or trailing spaces,
  5558. 4: the indentation of the current line,
  5559. 5: trailing whitespace.")
  5560. (defvar org-font-lock-hook nil
  5561. "Functions to be called for special font lock stuff.")
  5562. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5563. (defvar org-font-lock-set-keywords-hook nil
  5564. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5565. This is called after `org-font-lock-extra-keywords' is defined, but before
  5566. it is installed to be used by font lock. This can be useful if something
  5567. needs to be inserted at a specific position in the font-lock sequence.")
  5568. (defun org-font-lock-hook (limit)
  5569. "Run `org-font-lock-hook' within LIMIT."
  5570. (run-hook-with-args 'org-font-lock-hook limit))
  5571. (defun org-set-font-lock-defaults ()
  5572. "Set font lock defaults for the current buffer."
  5573. (let* ((em org-fontify-emphasized-text)
  5574. (lk org-highlight-links)
  5575. (org-font-lock-extra-keywords
  5576. (list
  5577. ;; Call the hook
  5578. '(org-font-lock-hook)
  5579. ;; Headlines
  5580. `(,(if org-fontify-whole-heading-line
  5581. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5582. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5583. (1 (org-get-level-face 1))
  5584. (2 (org-get-level-face 2))
  5585. (3 (org-get-level-face 3)))
  5586. ;; Table lines
  5587. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5588. (1 'org-table t))
  5589. ;; Table internals
  5590. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5591. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5592. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5593. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5594. ;; Drawers
  5595. '(org-fontify-drawers)
  5596. ;; Properties
  5597. (list org-property-re
  5598. '(1 'org-special-keyword t)
  5599. '(3 'org-property-value t))
  5600. ;; Link related fontification.
  5601. '(org-activate-links)
  5602. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5603. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5604. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5605. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5606. ;; Targets.
  5607. (list org-any-target-regexp '(0 'org-target t))
  5608. ;; Diary sexps.
  5609. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5610. ;; Macro
  5611. '(org-fontify-macros)
  5612. ;; TODO keyword
  5613. (list (format org-heading-keyword-regexp-format
  5614. org-todo-regexp)
  5615. '(2 (org-get-todo-face 2) t))
  5616. ;; DONE
  5617. (if org-fontify-done-headline
  5618. (list (format org-heading-keyword-regexp-format
  5619. (concat
  5620. "\\(?:"
  5621. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5622. "\\)"))
  5623. '(2 'org-headline-done t))
  5624. nil)
  5625. ;; Priorities
  5626. '(org-font-lock-add-priority-faces)
  5627. ;; Tags
  5628. '(org-font-lock-add-tag-faces)
  5629. ;; Tags groups
  5630. (when (and org-group-tags org-tag-groups-alist)
  5631. (list (concat org-outline-regexp-bol ".+\\(:"
  5632. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5633. ":\\).*$")
  5634. '(1 'org-tag-group prepend)))
  5635. ;; Special keywords
  5636. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5637. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5638. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5639. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5640. ;; Emphasis
  5641. (when em '(org-do-emphasis-faces))
  5642. ;; Checkboxes
  5643. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5644. 1 'org-checkbox prepend)
  5645. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5646. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5647. (0 (org-get-checkbox-statistics-face) t)))
  5648. ;; Description list items
  5649. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5650. 1 'org-list-dt prepend)
  5651. ;; ARCHIVEd headings
  5652. (list (concat
  5653. org-outline-regexp-bol
  5654. "\\(.*:" org-archive-tag ":.*\\)")
  5655. '(1 'org-archived prepend))
  5656. ;; Specials
  5657. '(org-do-latex-and-related)
  5658. '(org-fontify-entities)
  5659. '(org-raise-scripts)
  5660. ;; Code
  5661. '(org-activate-code (1 'org-code t))
  5662. ;; COMMENT
  5663. (list (format
  5664. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5665. org-todo-regexp
  5666. org-comment-string)
  5667. '(9 'org-special-keyword t))
  5668. ;; Blocks and meta lines
  5669. '(org-fontify-meta-lines-and-blocks))))
  5670. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5671. (run-hooks 'org-font-lock-set-keywords-hook)
  5672. ;; Now set the full font-lock-keywords
  5673. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5674. (setq-local font-lock-defaults
  5675. '(org-font-lock-keywords t nil nil backward-paragraph))
  5676. (kill-local-variable 'font-lock-keywords)
  5677. nil))
  5678. (defun org-toggle-pretty-entities ()
  5679. "Toggle the composition display of entities as UTF8 characters."
  5680. (interactive)
  5681. (setq-local org-pretty-entities (not org-pretty-entities))
  5682. (org-restart-font-lock)
  5683. (if org-pretty-entities
  5684. (message "Entities are now displayed as UTF8 characters")
  5685. (save-restriction
  5686. (widen)
  5687. (decompose-region (point-min) (point-max))
  5688. (message "Entities are now displayed as plain text"))))
  5689. (defvar-local org-custom-properties-overlays nil
  5690. "List of overlays used for custom properties.")
  5691. (defun org-toggle-custom-properties-visibility ()
  5692. "Display or hide properties in `org-custom-properties'."
  5693. (interactive)
  5694. (if org-custom-properties-overlays
  5695. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5696. (setq org-custom-properties-overlays nil))
  5697. (when org-custom-properties
  5698. (org-with-wide-buffer
  5699. (goto-char (point-min))
  5700. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5701. (while (re-search-forward regexp nil t)
  5702. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5703. (when (and end (< (point) end))
  5704. ;; Hide first custom property in current drawer.
  5705. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5706. (overlay-put o 'invisible t)
  5707. (overlay-put o 'org-custom-property t)
  5708. (push o org-custom-properties-overlays))
  5709. ;; Hide additional custom properties in the same drawer.
  5710. (while (re-search-forward regexp end t)
  5711. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5712. (overlay-put o 'invisible t)
  5713. (overlay-put o 'org-custom-property t)
  5714. (push o org-custom-properties-overlays)))))
  5715. ;; Each entry is limited to a single property drawer.
  5716. (outline-next-heading)))))))
  5717. (defun org-fontify-entities (limit)
  5718. "Find an entity to fontify."
  5719. (let (ee)
  5720. (when org-pretty-entities
  5721. (catch 'match
  5722. ;; "\_ "-family is left out on purpose. Only the first one,
  5723. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5724. ;; confusing when adding a second white space character.
  5725. (while (re-search-forward
  5726. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5727. limit t)
  5728. (when (and (not (org-at-comment-p))
  5729. (setq ee (org-entity-get (match-string 1)))
  5730. (= (length (nth 6 ee)) 1))
  5731. (let* ((end (if (equal (match-string 2) "{}")
  5732. (match-end 2)
  5733. (match-end 1))))
  5734. (add-text-properties
  5735. (match-beginning 0) end
  5736. (list 'font-lock-fontified t))
  5737. (compose-region (match-beginning 0) end
  5738. (nth 6 ee) nil)
  5739. (backward-char 1)
  5740. (throw 'match t))))
  5741. nil))))
  5742. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5743. "Fontify string S like in Org mode."
  5744. (with-temp-buffer
  5745. (insert s)
  5746. (let ((org-odd-levels-only odd-levels))
  5747. (org-mode)
  5748. (org-font-lock-ensure)
  5749. (buffer-string))))
  5750. (defvar org-m nil)
  5751. (defvar org-l nil)
  5752. (defvar org-f nil)
  5753. (defun org-get-level-face (n)
  5754. "Get the right face for match N in font-lock matching of headlines."
  5755. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5756. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5757. (if org-cycle-level-faces
  5758. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5759. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5760. (cond
  5761. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5762. ((eq n 2) org-f)
  5763. (t (unless org-level-color-stars-only org-f))))
  5764. (defun org-face-from-face-or-color (context inherit face-or-color)
  5765. "Create a face list that inherits INHERIT, but sets the foreground color.
  5766. When FACE-OR-COLOR is not a string, just return it."
  5767. (if (stringp face-or-color)
  5768. (list :inherit inherit
  5769. (cdr (assoc context org-faces-easy-properties))
  5770. face-or-color)
  5771. face-or-color))
  5772. (defun org-get-todo-face (kwd)
  5773. "Get the right face for a TODO keyword KWD.
  5774. If KWD is a number, get the corresponding match group."
  5775. (when (numberp kwd) (setq kwd (match-string kwd)))
  5776. (or (org-face-from-face-or-color
  5777. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5778. (and (member kwd org-done-keywords) 'org-done)
  5779. 'org-todo))
  5780. (defun org-get-priority-face (priority)
  5781. "Get the right face for PRIORITY.
  5782. PRIORITY is a character."
  5783. (or (org-face-from-face-or-color
  5784. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5785. 'org-priority))
  5786. (defun org-get-tag-face (tag)
  5787. "Get the right face for TAG.
  5788. If TAG is a number, get the corresponding match group."
  5789. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5790. (or (org-face-from-face-or-color
  5791. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5792. 'org-tag)))
  5793. (defun org-font-lock-add-priority-faces (limit)
  5794. "Add the special priority faces."
  5795. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5796. (add-text-properties
  5797. (match-beginning 1) (match-end 1)
  5798. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5799. 'font-lock-fontified t))))
  5800. (defun org-font-lock-add-tag-faces (limit)
  5801. "Add the special tag faces."
  5802. (when (and org-tag-faces org-tags-special-faces-re)
  5803. (while (re-search-forward org-tags-special-faces-re limit t)
  5804. (add-text-properties (match-beginning 1) (match-end 1)
  5805. (list 'face (org-get-tag-face 1)
  5806. 'font-lock-fontified t))
  5807. (backward-char 1))))
  5808. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5809. "Remove fontification and activation overlays from links."
  5810. (font-lock-default-unfontify-region beg end)
  5811. (let* ((buffer-undo-list t)
  5812. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5813. (inhibit-modification-hooks t)
  5814. deactivate-mark buffer-file-name buffer-file-truename)
  5815. (decompose-region beg end)
  5816. (remove-text-properties beg end
  5817. '(mouse-face t keymap t org-linked-text t
  5818. invisible t intangible t
  5819. org-emphasis t))
  5820. (org-remove-font-lock-display-properties beg end)))
  5821. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5822. ((raise 0.3) (height 0.7))
  5823. ((raise -0.5))
  5824. ((raise 0.5)))
  5825. "Display properties for showing superscripts and subscripts.")
  5826. (defun org--remove-sub-superscipt-font-lock-properties (outer-beg end)
  5827. "Remove the raise and invisible properties that are used to
  5828. show superscripts and subscripts."
  5829. (let ((beg outer-beg) next prop)
  5830. (while (< beg end)
  5831. (setq next (next-single-property-change beg 'display nil end)
  5832. prop (get-text-property beg 'display))
  5833. (when (member prop org-script-display)
  5834. (put-text-property beg next 'display nil))
  5835. (setq beg next))
  5836. (setq beg outer-beg)
  5837. (while (< beg end)
  5838. (setq next (next-single-property-change beg 'invisible nil end)
  5839. prop (get-text-property beg 'invisible))
  5840. (when (eq prop 'org-script)
  5841. (put-text-property beg next 'invisible nil))
  5842. (setq beg next))))
  5843. (defvar-local org-raise-scripts--current-script-bounds nil)
  5844. (cl-pushnew '(org-script . t) text-property-default-nonsticky)
  5845. (defun org-raise-scripts--post-command-hook ()
  5846. "Modeled after `prettify-symbols--post-command-hook'."
  5847. (when (and org-raise-scripts--current-script-bounds
  5848. (or (< (point) (nth 0 org-raise-scripts--current-script-bounds))
  5849. (> (point) (nth 1 org-raise-scripts--current-script-bounds))))
  5850. (apply #'font-lock-flush org-raise-scripts--current-script-bounds)
  5851. (setq org-raise-scripts--current-script-bounds nil))
  5852. (let ((bounds (get-text-property (point) 'org-script)))
  5853. (when bounds
  5854. (let ((start (nth 0 bounds))
  5855. (end (nth 1 bounds)))
  5856. (setq org-raise-scripts--current-script-bounds bounds)
  5857. (with-silent-modifications
  5858. (org-remove-font-lock-display-properties start end))))))
  5859. (add-hook 'org-mode-hook
  5860. (lambda ()
  5861. (add-hook 'post-command-hook #'org-raise-scripts--post-command-hook nil 'local)))
  5862. (defun org-raise-scripts (limit)
  5863. "Add raise properties to sub/superscripts."
  5864. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5865. (re-search-forward
  5866. (if (eq org-use-sub-superscripts t)
  5867. org-match-substring-regexp
  5868. org-match-substring-with-braces-regexp)
  5869. limit t))
  5870. (unless (and org-raise-scripts--current-script-bounds
  5871. (> (point) (nth 0 org-raise-scripts--current-script-bounds))
  5872. (<= (point) (nth 1 org-raise-scripts--current-script-bounds)))
  5873. (let* ((pos (point)) table-p comment-p
  5874. (mpos (match-beginning 3))
  5875. (emph-p (get-text-property mpos 'org-emphasis))
  5876. (link-p (get-text-property mpos 'mouse-face))
  5877. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5878. (goto-char (point-at-bol))
  5879. (setq table-p (looking-at-p org-table-dataline-regexp)
  5880. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5881. (goto-char pos)
  5882. ;; Handle a_b^c
  5883. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5884. (unless (or comment-p emph-p link-p keyw-p)
  5885. (put-text-property (match-beginning 2) (match-end 0)
  5886. 'org-script (list (match-beginning 2) (match-end 0)))
  5887. (put-text-property (match-beginning 3) (match-end 0)
  5888. 'display
  5889. (if (equal (char-after (match-beginning 2)) ?^)
  5890. (nth (if table-p 3 1) org-script-display)
  5891. (nth (if table-p 2 0) org-script-display)))
  5892. (add-text-properties (match-beginning 2) (match-end 2)
  5893. '(invisible org-script))
  5894. (when (and (eq (char-after (match-beginning 3)) ?{)
  5895. (eq (char-before (match-end 3)) ?}))
  5896. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5897. '(invisible org-script))
  5898. (add-text-properties (1- (match-end 3)) (match-end 3)
  5899. '(invisible org-script))))
  5900. t))))
  5901. (defun org-remove-empty-overlays-at (pos)
  5902. "Remove outline overlays that do not contain non-white stuff."
  5903. (dolist (o (overlays-at pos))
  5904. (and (eq 'outline (overlay-get o 'invisible))
  5905. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5906. (overlay-end o))))
  5907. (delete-overlay o))))
  5908. (defun org-show-empty-lines-in-parent ()
  5909. "Move to the parent and re-show empty lines before visible headlines."
  5910. (save-excursion
  5911. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5912. (org-cycle-show-empty-lines context))))
  5913. (defun org-files-list ()
  5914. "Return `org-agenda-files' list, plus all open Org files.
  5915. This is useful for operations that need to scan all of a user's
  5916. open and agenda-wise Org files."
  5917. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5918. (dolist (buf (buffer-list))
  5919. (with-current-buffer buf
  5920. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5921. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5922. :test #'equal))))
  5923. files))
  5924. (defsubst org-entry-beginning-position ()
  5925. "Return the beginning position of the current entry."
  5926. (save-excursion (org-back-to-heading t) (point)))
  5927. (defsubst org-entry-end-position ()
  5928. "Return the end position of the current entry."
  5929. (save-excursion (outline-next-heading) (point)))
  5930. (defun org-subtree-end-visible-p ()
  5931. "Is the end of the current subtree visible?"
  5932. (pos-visible-in-window-p
  5933. (save-excursion (org-end-of-subtree t) (point))))
  5934. (defun org-first-headline-recenter ()
  5935. "Move cursor to the first headline and recenter the headline."
  5936. (let ((window (get-buffer-window)))
  5937. (when window
  5938. (goto-char (point-min))
  5939. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5940. (set-window-start window (line-beginning-position))))))
  5941. ;;; Visibility (headlines, blocks, drawers)
  5942. ;;;; Headlines visibility
  5943. (defun org-show-entry ()
  5944. "Show the body directly following this heading.
  5945. Show the heading too, if it is currently invisible."
  5946. (interactive)
  5947. (save-excursion
  5948. (ignore-errors
  5949. (org-back-to-heading t)
  5950. (org-flag-region
  5951. (line-end-position 0)
  5952. (save-excursion
  5953. (if (re-search-forward
  5954. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5955. (match-beginning 1)
  5956. (point-max)))
  5957. nil
  5958. 'outline))))
  5959. (defun org-show-children (&optional level)
  5960. "Show all direct subheadings of this heading.
  5961. Prefix arg LEVEL is how many levels below the current level
  5962. should be shown. Default is enough to cause the following
  5963. heading to appear."
  5964. (interactive "p")
  5965. (save-excursion
  5966. (org-back-to-heading t)
  5967. (let* ((current-level (funcall outline-level))
  5968. (max-level (org-get-valid-level
  5969. current-level
  5970. (if level (prefix-numeric-value level) 1)))
  5971. (end (save-excursion (org-end-of-subtree t t)))
  5972. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5973. (past-first-child nil)
  5974. ;; Make sure to skip inlinetasks.
  5975. (re (format regexp-fmt
  5976. current-level
  5977. (cond
  5978. ((not (featurep 'org-inlinetask)) "")
  5979. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5980. 3))
  5981. (t (1- org-inlinetask-min-level))))))
  5982. ;; Display parent heading.
  5983. (org-flag-heading nil)
  5984. (forward-line)
  5985. ;; Display children. First child may be deeper than expected
  5986. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5987. ;; MAX-LEVEL accordingly.
  5988. (while (re-search-forward re end t)
  5989. (unless past-first-child
  5990. (setq re (format regexp-fmt
  5991. current-level
  5992. (max (funcall outline-level) max-level)))
  5993. (setq past-first-child t))
  5994. (org-flag-heading nil)))))
  5995. (defun org-show-subtree ()
  5996. "Show everything after this heading at deeper levels."
  5997. (interactive)
  5998. (org-flag-region
  5999. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  6000. ;;;; Blocks visibility
  6001. (defun org-hide-block-toggle-maybe ()
  6002. "Toggle visibility of block at point.
  6003. Unlike to `org-hide-block-toggle', this function does not throw
  6004. an error. Return a non-nil value when toggling is successful."
  6005. (interactive)
  6006. (ignore-errors (org-hide-block-toggle)))
  6007. (defun org-hide-block-toggle (&optional force)
  6008. "Toggle the visibility of the current block.
  6009. When optional argument FORCE is `off', make block visible. If it
  6010. is non-nil, hide it unconditionally. Throw an error when not at
  6011. a block. Return a non-nil value when toggling is successful."
  6012. (interactive)
  6013. (let ((element (org-element-at-point)))
  6014. (unless (memq (org-element-type element)
  6015. '(center-block comment-block dynamic-block example-block
  6016. export-block quote-block special-block
  6017. src-block verse-block))
  6018. (user-error "Not at a block"))
  6019. (let* ((post (org-element-property :post-affiliated element))
  6020. (start (save-excursion
  6021. (goto-char post)
  6022. (line-end-position)))
  6023. (end (save-excursion
  6024. (goto-char (org-element-property :end element))
  6025. (skip-chars-backward " \t\n")
  6026. (line-end-position))))
  6027. ;; Do nothing when not before or at the block opening line or at
  6028. ;; the block closing line.
  6029. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  6030. (cond ((eq force 'off)
  6031. (org-flag-region start end nil 'org-hide-block))
  6032. (force
  6033. (org-flag-region start end t 'org-hide-block))
  6034. ((eq (get-char-property start 'invisible) 'org-hide-block)
  6035. (org-flag-region start end nil 'org-hide-block))
  6036. (t
  6037. (org-flag-region start end t 'org-hide-block)))
  6038. ;; When the block is hidden away, make sure point is left in
  6039. ;; a visible part of the buffer.
  6040. (when (invisible-p (max (1- (point)) (point-min)))
  6041. (goto-char post))
  6042. ;; Signal success.
  6043. t))))
  6044. (defun org-hide-block-toggle-all ()
  6045. "Toggle the visibility of all blocks in the current buffer."
  6046. (org-block-map 'org-hide-block-toggle))
  6047. (defun org-hide-block-all ()
  6048. "Fold all blocks in the current buffer."
  6049. (interactive)
  6050. (org-show-all '(blocks))
  6051. (org-block-map 'org-hide-block-toggle-maybe))
  6052. ;;;; Drawers visibility
  6053. (defun org-cycle-hide-drawers (state &optional exceptions)
  6054. "Re-hide all drawers after a visibility state change.
  6055. STATE should be one of the symbols listed in the docstring of
  6056. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  6057. a list of strings specifying which drawers should not be hidden."
  6058. (when (and (derived-mode-p 'org-mode)
  6059. (not (memq state '(overview folded contents))))
  6060. (save-excursion
  6061. (let* ((globalp (eq state 'all))
  6062. (beg (if globalp (point-min) (point)))
  6063. (end (if globalp (point-max)
  6064. (if (eq state 'children)
  6065. (save-excursion (outline-next-heading) (point))
  6066. (org-end-of-subtree t)))))
  6067. (goto-char beg)
  6068. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6069. (unless (member-ignore-case (match-string 1) exceptions)
  6070. (let ((drawer (org-element-at-point)))
  6071. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6072. (org-flag-drawer t drawer)
  6073. ;; Make sure to skip drawer entirely or we might flag
  6074. ;; it another time when matching its ending line with
  6075. ;; `org-drawer-regexp'.
  6076. (goto-char (org-element-property :end drawer))))))))))
  6077. (defun org-flag-drawer (flag &optional element)
  6078. "When FLAG is non-nil, hide the drawer we are at.
  6079. Otherwise make it visible. When optional argument ELEMENT is
  6080. a parsed drawer, as returned by `org-element-at-point', hide or
  6081. show that drawer instead."
  6082. (let ((drawer (or element
  6083. (and (save-excursion
  6084. (beginning-of-line)
  6085. (looking-at-p org-drawer-regexp))
  6086. (org-element-at-point)))))
  6087. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6088. (let ((post (org-element-property :post-affiliated drawer)))
  6089. (org-flag-region
  6090. (save-excursion (goto-char post) (line-end-position))
  6091. (save-excursion (goto-char (org-element-property :end drawer))
  6092. (skip-chars-backward " \t\n")
  6093. (line-end-position))
  6094. flag 'org-hide-drawer)
  6095. ;; When the drawer is hidden away, make sure point lies in
  6096. ;; a visible part of the buffer.
  6097. (when (invisible-p (max (1- (point)) (point-min)))
  6098. (goto-char post))))))
  6099. ;;;; Visibility cycling
  6100. (defvar-local org-cycle-global-status nil)
  6101. (put 'org-cycle-global-status 'org-state t)
  6102. (defvar-local org-cycle-subtree-status nil)
  6103. (put 'org-cycle-subtree-status 'org-state t)
  6104. (defun org-show-all (&optional types)
  6105. "Show all contents in the visible part of the buffer.
  6106. By default, the function expands headings, blocks and drawers.
  6107. When optional argument TYPE is a list of symbols among `blocks',
  6108. `drawers' and `headings', to only expand one specific type."
  6109. (dolist (type (or types '(blocks drawers headings)))
  6110. (org-flag-region (point-min) (point-max) nil
  6111. (pcase type
  6112. (`blocks 'org-hide-block)
  6113. (`drawers 'org-hide-drawer)
  6114. (`headings 'outline)
  6115. (_ (error "Invalid type: %S" type))))))
  6116. ;;;###autoload
  6117. (defun org-cycle (&optional arg)
  6118. "TAB-action and visibility cycling for Org mode.
  6119. This is the command invoked in Org mode by the `TAB' key. Its main
  6120. purpose is outline visibility cycling, but it also invokes other actions
  6121. in special contexts.
  6122. When this function is called with a `\\[universal-argument]' prefix, rotate \
  6123. the entire
  6124. buffer through 3 states (global cycling)
  6125. 1. OVERVIEW: Show only top-level headlines.
  6126. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6127. 3. SHOW ALL: Show everything.
  6128. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  6129. switch to the startup visibility,
  6130. determined by the variable `org-startup-folded', and by any VISIBILITY
  6131. properties in the buffer.
  6132. With a `\\[universal-argument] \\[universal-argument] \
  6133. \\[universal-argument]' prefix argument, show the entire buffer, including
  6134. any drawers.
  6135. When inside a table, re-align the table and move to the next field.
  6136. When point is at the beginning of a headline, rotate the subtree started
  6137. by this line through 3 different states (local cycling)
  6138. 1. FOLDED: Only the main headline is shown.
  6139. 2. CHILDREN: The main headline and the direct children are shown.
  6140. From this state, you can move to one of the children
  6141. and zoom in further.
  6142. 3. SUBTREE: Show the entire subtree, including body text.
  6143. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6144. When point is at the beginning of an empty headline and the variable
  6145. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6146. of the headline by demoting and promoting it to likely levels. This
  6147. speeds up creation document structure by pressing `TAB' once or several
  6148. times right after creating a new headline.
  6149. When there is a numeric prefix, go up to a heading with level ARG, do
  6150. a `show-subtree' and return to the previous cursor position. If ARG
  6151. is negative, go up that many levels.
  6152. When point is not at the beginning of a headline, execute the global
  6153. binding for `TAB', which is re-indenting the line. See the option
  6154. `org-cycle-emulate-tab' for details.
  6155. As a special case, if point is at the beginning of the buffer and there is
  6156. no headline in line 1, this function will act as if called with prefix arg
  6157. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6158. prefix arg, but only
  6159. if the variable `org-cycle-global-at-bob' is t."
  6160. (interactive "P")
  6161. (org-load-modules-maybe)
  6162. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6163. (and org-cycle-level-after-item/entry-creation
  6164. (or (org-cycle-level)
  6165. (org-cycle-item-indentation))))
  6166. (let* ((limit-level
  6167. (or org-cycle-max-level
  6168. (and (boundp 'org-inlinetask-min-level)
  6169. org-inlinetask-min-level
  6170. (1- org-inlinetask-min-level))))
  6171. (nstars (and limit-level
  6172. (if org-odd-levels-only
  6173. (and limit-level (1- (* limit-level 2)))
  6174. limit-level)))
  6175. (org-outline-regexp
  6176. (if (not (derived-mode-p 'org-mode))
  6177. outline-regexp
  6178. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6179. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6180. (not (looking-at org-outline-regexp))))
  6181. (org-cycle-hook
  6182. (if bob-special
  6183. (delq 'org-optimize-window-after-visibility-change
  6184. (copy-sequence org-cycle-hook))
  6185. org-cycle-hook))
  6186. (pos (point)))
  6187. (cond
  6188. ((equal arg '(16))
  6189. (setq last-command 'dummy)
  6190. (org-set-startup-visibility)
  6191. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6192. ((equal arg '(64))
  6193. (org-show-all)
  6194. (org-unlogged-message "Entire buffer visible, including drawers"))
  6195. ((equal arg '(4)) (org-cycle-internal-global))
  6196. ;; Try hiding block at point.
  6197. ((org-hide-block-toggle-maybe))
  6198. ;; Try cdlatex TAB completion
  6199. ((org-try-cdlatex-tab))
  6200. ;; Table: enter it or move to the next field.
  6201. ((org-at-table-p 'any)
  6202. (if (org-at-table.el-p)
  6203. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6204. Use `\\[org-edit-special]' to edit table.el tables"))
  6205. (if arg (org-table-edit-field t)
  6206. (org-table-justify-field-maybe)
  6207. (call-interactively 'org-table-next-field))))
  6208. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6209. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6210. (bob-special (org-cycle-internal-global))
  6211. ;; Drawers: delegate to `org-flag-drawer'.
  6212. ((save-excursion
  6213. (beginning-of-line 1)
  6214. (looking-at org-drawer-regexp))
  6215. (org-flag-drawer ; toggle block visibility
  6216. (not (get-char-property (match-end 0) 'invisible))))
  6217. ;; Show-subtree, ARG levels up from here.
  6218. ((integerp arg)
  6219. (save-excursion
  6220. (org-back-to-heading)
  6221. (outline-up-heading (if (< arg 0) (- arg)
  6222. (- (funcall outline-level) arg)))
  6223. (org-show-subtree)))
  6224. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6225. ((and (featurep 'org-inlinetask)
  6226. (org-inlinetask-at-task-p)
  6227. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6228. (org-inlinetask-toggle-visibility))
  6229. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6230. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6231. (save-excursion (move-beginning-of-line 1)
  6232. (looking-at org-outline-regexp)))
  6233. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6234. (org-cycle-internal-local))
  6235. ;; From there: TAB emulation and template completion.
  6236. (buffer-read-only (org-back-to-heading))
  6237. ((run-hook-with-args-until-success
  6238. 'org-tab-after-check-for-cycling-hook))
  6239. ((run-hook-with-args-until-success
  6240. 'org-tab-before-tab-emulation-hook))
  6241. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6242. (or (not (bolp))
  6243. (not (looking-at org-outline-regexp))))
  6244. (call-interactively (global-key-binding "\t")))
  6245. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6246. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6247. (or (and (eq org-cycle-emulate-tab 'white)
  6248. (= (match-end 0) (point-at-eol)))
  6249. (and (eq org-cycle-emulate-tab 'whitestart)
  6250. (>= (match-end 0) pos))))
  6251. t
  6252. (eq org-cycle-emulate-tab t))
  6253. (call-interactively (global-key-binding "\t")))
  6254. (t (save-excursion
  6255. (org-back-to-heading)
  6256. (org-cycle)))))))
  6257. (defun org-cycle-internal-global ()
  6258. "Do the global cycling action."
  6259. ;; Hack to avoid display of messages for .org attachments in Gnus
  6260. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6261. (cond
  6262. ((and (eq last-command this-command)
  6263. (eq org-cycle-global-status 'overview))
  6264. ;; We just created the overview - now do table of contents
  6265. ;; This can be slow in very large buffers, so indicate action
  6266. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6267. (unless ga (org-unlogged-message "CONTENTS..."))
  6268. (org-content)
  6269. (unless ga (org-unlogged-message "CONTENTS...done"))
  6270. (setq org-cycle-global-status 'contents)
  6271. (run-hook-with-args 'org-cycle-hook 'contents))
  6272. ((and (eq last-command this-command)
  6273. (eq org-cycle-global-status 'contents))
  6274. ;; We just showed the table of contents - now show everything
  6275. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6276. (org-show-all '(headings blocks))
  6277. (unless ga (org-unlogged-message "SHOW ALL"))
  6278. (setq org-cycle-global-status 'all)
  6279. (run-hook-with-args 'org-cycle-hook 'all))
  6280. (t
  6281. ;; Default action: go to overview
  6282. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6283. (org-overview)
  6284. (unless ga (org-unlogged-message "OVERVIEW"))
  6285. (setq org-cycle-global-status 'overview)
  6286. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6287. (defvar org-called-with-limited-levels nil
  6288. "Non-nil when `org-with-limited-levels' is currently active.")
  6289. (defun org-cycle-internal-local ()
  6290. "Do the local cycling action."
  6291. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6292. ;; First, determine end of headline (EOH), end of subtree or item
  6293. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6294. (save-excursion
  6295. (if (org-at-item-p)
  6296. (progn
  6297. (beginning-of-line)
  6298. (setq struct (org-list-struct))
  6299. (setq eoh (point-at-eol))
  6300. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6301. (setq has-children (org-list-has-child-p (point) struct)))
  6302. (org-back-to-heading)
  6303. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6304. (setq eos (save-excursion (org-end-of-subtree t t)
  6305. (when (bolp) (backward-char)) (point)))
  6306. (setq has-children
  6307. (or (save-excursion
  6308. (let ((level (funcall outline-level)))
  6309. (outline-next-heading)
  6310. (and (org-at-heading-p t)
  6311. (> (funcall outline-level) level))))
  6312. (save-excursion
  6313. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6314. ;; Determine end invisible part of buffer (EOL)
  6315. (beginning-of-line 2)
  6316. (while (and (not (eobp)) ;This is like `next-line'.
  6317. (get-char-property (1- (point)) 'invisible))
  6318. (goto-char (next-single-char-property-change (point) 'invisible))
  6319. (and (eolp) (beginning-of-line 2)))
  6320. (setq eol (point)))
  6321. ;; Find out what to do next and set `this-command'
  6322. (cond
  6323. ((= eos eoh)
  6324. ;; Nothing is hidden behind this heading
  6325. (unless (org-before-first-heading-p)
  6326. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6327. (org-unlogged-message "EMPTY ENTRY")
  6328. (setq org-cycle-subtree-status nil)
  6329. (save-excursion
  6330. (goto-char eos)
  6331. (outline-next-heading)
  6332. (when (org-invisible-p) (org-flag-heading nil))))
  6333. ((and (or (>= eol eos)
  6334. (not (string-match "\\S-" (buffer-substring eol eos))))
  6335. (or has-children
  6336. (not (setq children-skipped
  6337. org-cycle-skip-children-state-if-no-children))))
  6338. ;; Entire subtree is hidden in one line: children view
  6339. (unless (org-before-first-heading-p)
  6340. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6341. (if (org-at-item-p)
  6342. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6343. (org-show-entry)
  6344. (org-with-limited-levels (org-show-children))
  6345. (org-show-set-visibility 'canonical)
  6346. ;; Fold every list in subtree to top-level items.
  6347. (when (eq org-cycle-include-plain-lists 'integrate)
  6348. (save-excursion
  6349. (org-back-to-heading)
  6350. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6351. (beginning-of-line 1)
  6352. (let* ((struct (org-list-struct))
  6353. (prevs (org-list-prevs-alist struct))
  6354. (end (org-list-get-bottom-point struct)))
  6355. (dolist (e (org-list-get-all-items (point) struct prevs))
  6356. (org-list-set-item-visibility e struct 'folded))
  6357. (goto-char (if (< end eos) end eos)))))))
  6358. (org-unlogged-message "CHILDREN")
  6359. (save-excursion
  6360. (goto-char eos)
  6361. (outline-next-heading)
  6362. (when (org-invisible-p) (org-flag-heading nil)))
  6363. (setq org-cycle-subtree-status 'children)
  6364. (unless (org-before-first-heading-p)
  6365. (run-hook-with-args 'org-cycle-hook 'children)))
  6366. ((or children-skipped
  6367. (and (eq last-command this-command)
  6368. (eq org-cycle-subtree-status 'children)))
  6369. ;; We just showed the children, or no children are there,
  6370. ;; now show everything.
  6371. (unless (org-before-first-heading-p)
  6372. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6373. (org-flag-region eoh eos nil 'outline)
  6374. (org-unlogged-message
  6375. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6376. (setq org-cycle-subtree-status 'subtree)
  6377. (unless (org-before-first-heading-p)
  6378. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6379. (t
  6380. ;; Default action: hide the subtree.
  6381. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6382. (org-flag-region eoh eos t 'outline)
  6383. (org-unlogged-message "FOLDED")
  6384. (setq org-cycle-subtree-status 'folded)
  6385. (unless (org-before-first-heading-p)
  6386. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6387. ;;;###autoload
  6388. (defun org-global-cycle (&optional arg)
  6389. "Cycle the global visibility. For details see `org-cycle'.
  6390. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6391. With a numeric prefix, show all headlines up to that level."
  6392. (interactive "P")
  6393. (let ((org-cycle-include-plain-lists
  6394. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6395. (cond
  6396. ((integerp arg)
  6397. (org-show-all '(headings blocks))
  6398. (outline-hide-sublevels arg)
  6399. (setq org-cycle-global-status 'contents))
  6400. ((equal arg '(4))
  6401. (org-set-startup-visibility)
  6402. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6403. (t
  6404. (org-cycle '(4))))))
  6405. (defun org-set-startup-visibility ()
  6406. "Set the visibility required by startup options and properties."
  6407. (cond
  6408. ((eq org-startup-folded t)
  6409. (org-overview))
  6410. ((eq org-startup-folded 'content)
  6411. (org-content))
  6412. ((or (eq org-startup-folded 'showeverything)
  6413. (eq org-startup-folded nil))
  6414. (org-show-all)))
  6415. (unless (eq org-startup-folded 'showeverything)
  6416. (when org-hide-block-startup (org-hide-block-all))
  6417. (org-set-visibility-according-to-property)
  6418. (org-cycle-hide-archived-subtrees 'all)
  6419. (org-cycle-hide-drawers 'all)
  6420. (org-cycle-show-empty-lines t)))
  6421. (defun org-set-visibility-according-to-property ()
  6422. "Switch subtree visibilities according to :VISIBILITY: property."
  6423. (interactive)
  6424. (org-with-wide-buffer
  6425. (goto-char (point-min))
  6426. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6427. (if (not (org-at-property-p)) (outline-next-heading)
  6428. (let ((state (match-string 3)))
  6429. (save-excursion
  6430. (org-back-to-heading t)
  6431. (outline-hide-subtree)
  6432. (org-reveal)
  6433. (cond
  6434. ((equal state "folded")
  6435. (outline-hide-subtree))
  6436. ((equal state "children")
  6437. (org-show-hidden-entry)
  6438. (org-show-children))
  6439. ((equal state "content")
  6440. (save-excursion
  6441. (save-restriction
  6442. (org-narrow-to-subtree)
  6443. (org-content))))
  6444. ((member state '("all" "showall"))
  6445. (outline-show-subtree)))))))))
  6446. (defun org-overview ()
  6447. "Switch to overview mode, showing only top-level headlines.
  6448. This shows all headlines with a level equal or greater than the level
  6449. of the first headline in the buffer. This is important, because if the
  6450. first headline is not level one, then (hide-sublevels 1) gives confusing
  6451. results."
  6452. (interactive)
  6453. (save-excursion
  6454. (let ((level
  6455. (save-excursion
  6456. (goto-char (point-min))
  6457. (when (re-search-forward org-outline-regexp-bol nil t)
  6458. (goto-char (match-beginning 0))
  6459. (funcall outline-level)))))
  6460. (and level (outline-hide-sublevels level)))))
  6461. (defun org-content (&optional arg)
  6462. "Show all headlines in the buffer, like a table of contents.
  6463. With numerical argument N, show content up to level N."
  6464. (interactive "P")
  6465. (org-overview)
  6466. (save-excursion
  6467. ;; Visit all headings and show their offspring
  6468. (and (integerp arg) (org-overview))
  6469. (goto-char (point-max))
  6470. (catch 'exit
  6471. (while (and (progn (condition-case nil
  6472. (outline-previous-visible-heading 1)
  6473. (error (goto-char (point-min))))
  6474. t)
  6475. (looking-at org-outline-regexp))
  6476. (if (integerp arg)
  6477. (org-show-children (1- arg))
  6478. (outline-show-branches))
  6479. (when (bobp) (throw 'exit nil))))))
  6480. (defun org-optimize-window-after-visibility-change (state)
  6481. "Adjust the window after a change in outline visibility.
  6482. This function is the default value of the hook `org-cycle-hook'."
  6483. (when (get-buffer-window (current-buffer))
  6484. (cond
  6485. ((eq state 'content) nil)
  6486. ((eq state 'all) nil)
  6487. ((eq state 'folded) nil)
  6488. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6489. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6490. (defun org-clean-visibility-after-subtree-move ()
  6491. "Fix visibility issues after moving a subtree."
  6492. ;; First, find a reasonable region to look at:
  6493. ;; Start two siblings above, end three below
  6494. (let* ((beg (save-excursion
  6495. (and (org-get-last-sibling)
  6496. (org-get-last-sibling))
  6497. (point)))
  6498. (end (save-excursion
  6499. (and (org-get-next-sibling)
  6500. (org-get-next-sibling)
  6501. (org-get-next-sibling))
  6502. (if (org-at-heading-p)
  6503. (point-at-eol)
  6504. (point))))
  6505. (level (looking-at "\\*+"))
  6506. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6507. (save-excursion
  6508. (save-restriction
  6509. (narrow-to-region beg end)
  6510. (when re
  6511. ;; Properly fold already folded siblings
  6512. (goto-char (point-min))
  6513. (while (re-search-forward re nil t)
  6514. (when (and (not (org-invisible-p))
  6515. (org-invisible-p (line-end-position)))
  6516. (outline-hide-entry))))
  6517. (org-cycle-hide-drawers 'all)
  6518. (org-cycle-show-empty-lines 'overview)))))
  6519. (defun org-cycle-show-empty-lines (state)
  6520. "Show empty lines above all visible headlines.
  6521. The region to be covered depends on STATE when called through
  6522. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6523. entire buffer covered. Note that an empty line is only shown if there
  6524. are at least `org-cycle-separator-lines' empty lines before the headline."
  6525. (when (/= org-cycle-separator-lines 0)
  6526. (save-excursion
  6527. (let* ((n (abs org-cycle-separator-lines))
  6528. (re (cond
  6529. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6530. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6531. (t (let ((ns (number-to-string (- n 2))))
  6532. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6533. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6534. beg end)
  6535. (cond
  6536. ((memq state '(overview contents t))
  6537. (setq beg (point-min) end (point-max)))
  6538. ((memq state '(children folded))
  6539. (setq beg (point)
  6540. end (progn (org-end-of-subtree t t)
  6541. (line-beginning-position 2)))))
  6542. (when beg
  6543. (goto-char beg)
  6544. (while (re-search-forward re end t)
  6545. (unless (get-char-property (match-end 1) 'invisible)
  6546. (let ((e (match-end 1))
  6547. (b (if (>= org-cycle-separator-lines 0)
  6548. (match-beginning 1)
  6549. (save-excursion
  6550. (goto-char (match-beginning 0))
  6551. (skip-chars-backward " \t\n")
  6552. (line-end-position)))))
  6553. (org-flag-region b e nil 'outline))))))))
  6554. ;; Never hide empty lines at the end of the file.
  6555. (save-excursion
  6556. (goto-char (point-max))
  6557. (outline-previous-heading)
  6558. (outline-end-of-heading)
  6559. (when (and (looking-at "[ \t\n]+")
  6560. (= (match-end 0) (point-max)))
  6561. (org-flag-region (point) (match-end 0) nil 'outline))))
  6562. ;;;; Reveal point location
  6563. (defun org-show-context (&optional key)
  6564. "Make sure point and context are visible.
  6565. Optional argument KEY, when non-nil, is a symbol. See
  6566. `org-show-context-detail' for allowed values and how much is to
  6567. be shown."
  6568. (org-show-set-visibility
  6569. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6570. ((cdr (assq key org-show-context-detail)))
  6571. (t (cdr (assq 'default org-show-context-detail))))))
  6572. (defun org-show-set-visibility (detail)
  6573. "Set visibility around point according to DETAIL.
  6574. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  6575. `tree', `canonical' or t. See `org-show-context-detail' for more
  6576. information."
  6577. ;; Show current heading and possibly its entry, following headline
  6578. ;; or all children.
  6579. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6580. (org-flag-heading nil)
  6581. (org-show-entry)
  6582. ;; If point is hidden within a drawer or a block, make sure to
  6583. ;; expose it.
  6584. (dolist (o (overlays-at (point)))
  6585. (when (memq (overlay-get o 'invisible)
  6586. '(org-hide-block org-hide-drawer outline))
  6587. (delete-overlay o)))
  6588. (unless (org-before-first-heading-p)
  6589. (org-with-limited-levels
  6590. (cl-case detail
  6591. ((tree canonical t) (org-show-children))
  6592. ((nil minimal ancestors))
  6593. (t (save-excursion
  6594. (outline-next-heading)
  6595. (org-flag-heading nil)))))))
  6596. ;; Show all siblings.
  6597. (when (eq detail 'lineage) (org-show-siblings))
  6598. ;; Show ancestors, possibly with their children.
  6599. (when (memq detail '(ancestors lineage tree canonical t))
  6600. (save-excursion
  6601. (while (org-up-heading-safe)
  6602. (org-flag-heading nil)
  6603. (when (memq detail '(canonical t)) (org-show-entry))
  6604. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6605. (defvar org-reveal-start-hook nil
  6606. "Hook run before revealing a location.")
  6607. (defun org-reveal (&optional siblings)
  6608. "Show current entry, hierarchy above it, and the following headline.
  6609. This can be used to show a consistent set of context around
  6610. locations exposed with `org-show-context'.
  6611. With optional argument SIBLINGS, on each level of the hierarchy all
  6612. siblings are shown. This repairs the tree structure to what it would
  6613. look like when opened with hierarchical calls to `org-cycle'.
  6614. With a \\[universal-argument] \\[universal-argument] prefix, \
  6615. go to the parent and show the entire tree."
  6616. (interactive "P")
  6617. (run-hooks 'org-reveal-start-hook)
  6618. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6619. ((equal siblings '(16))
  6620. (save-excursion
  6621. (when (org-up-heading-safe)
  6622. (org-show-subtree)
  6623. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6624. (t (org-show-set-visibility 'lineage))))
  6625. ;;; Indirect buffer display of subtrees
  6626. (defvar org-indirect-dedicated-frame nil
  6627. "This is the frame being used for indirect tree display.")
  6628. (defvar org-last-indirect-buffer nil)
  6629. (defun org-tree-to-indirect-buffer (&optional arg)
  6630. "Create indirect buffer and narrow it to current subtree.
  6631. With a numerical prefix ARG, go up to this level and then take that tree.
  6632. If ARG is negative, go up that many levels.
  6633. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6634. indirect buffer previously made with this command, to avoid proliferation of
  6635. indirect buffers. However, when you call the command with a \
  6636. `\\[universal-argument]' prefix, or
  6637. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6638. so that you can work with several indirect buffers at the same time. If
  6639. `org-indirect-buffer-display' is `dedicated-frame', the \
  6640. `\\[universal-argument]' prefix also
  6641. requests that a new frame be made for the new buffer, so that the dedicated
  6642. frame is not changed."
  6643. (interactive "P")
  6644. (let ((cbuf (current-buffer))
  6645. (cwin (selected-window))
  6646. (pos (point))
  6647. beg end level heading ibuf)
  6648. (save-excursion
  6649. (org-back-to-heading t)
  6650. (when (numberp arg)
  6651. (setq level (org-outline-level))
  6652. (when (< arg 0) (setq arg (+ level arg)))
  6653. (while (> (setq level (org-outline-level)) arg)
  6654. (org-up-heading-safe)))
  6655. (setq beg (point)
  6656. heading (org-get-heading 'no-tags))
  6657. (org-end-of-subtree t t)
  6658. (when (org-at-heading-p) (backward-char 1))
  6659. (setq end (point)))
  6660. (when (and (buffer-live-p org-last-indirect-buffer)
  6661. (not (eq org-indirect-buffer-display 'new-frame))
  6662. (not arg))
  6663. (kill-buffer org-last-indirect-buffer))
  6664. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6665. org-last-indirect-buffer ibuf)
  6666. (cond
  6667. ((or (eq org-indirect-buffer-display 'new-frame)
  6668. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6669. (select-frame (make-frame))
  6670. (delete-other-windows)
  6671. (pop-to-buffer-same-window ibuf)
  6672. (org-set-frame-title heading))
  6673. ((eq org-indirect-buffer-display 'dedicated-frame)
  6674. (raise-frame
  6675. (select-frame (or (and org-indirect-dedicated-frame
  6676. (frame-live-p org-indirect-dedicated-frame)
  6677. org-indirect-dedicated-frame)
  6678. (setq org-indirect-dedicated-frame (make-frame)))))
  6679. (delete-other-windows)
  6680. (pop-to-buffer-same-window ibuf)
  6681. (org-set-frame-title (concat "Indirect: " heading)))
  6682. ((eq org-indirect-buffer-display 'current-window)
  6683. (pop-to-buffer-same-window ibuf))
  6684. ((eq org-indirect-buffer-display 'other-window)
  6685. (pop-to-buffer ibuf))
  6686. (t (error "Invalid value")))
  6687. (narrow-to-region beg end)
  6688. (org-show-all '(headings blocks))
  6689. (goto-char pos)
  6690. (run-hook-with-args 'org-cycle-hook 'all)
  6691. (and (window-live-p cwin) (select-window cwin))))
  6692. (defun org-get-indirect-buffer (&optional buffer heading)
  6693. (setq buffer (or buffer (current-buffer)))
  6694. (let ((n 1) (base (buffer-name buffer)) bname)
  6695. (while (buffer-live-p
  6696. (get-buffer
  6697. (setq bname
  6698. (concat base "-"
  6699. (if heading (concat heading "-" (number-to-string n))
  6700. (number-to-string n))))))
  6701. (setq n (1+ n)))
  6702. (condition-case nil
  6703. (make-indirect-buffer buffer bname 'clone)
  6704. (error (make-indirect-buffer buffer bname)))))
  6705. (defun org-set-frame-title (title)
  6706. "Set the title of the current frame to the string TITLE."
  6707. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6708. ;;;; Structure editing
  6709. ;;; Inserting headlines
  6710. (defun org--line-empty-p (n)
  6711. "Is the Nth next line empty?
  6712. Counts the current line as N = 1 and the previous line as N = 0;
  6713. see `beginning-of-line'."
  6714. (save-excursion
  6715. (and (not (bobp))
  6716. (or (beginning-of-line n) t)
  6717. (save-match-data
  6718. (looking-at "[ \t]*$")))))
  6719. (defun org-previous-line-empty-p ()
  6720. "Is the previous line a blank line?
  6721. When NEXT is non-nil, check the next line instead."
  6722. (org--line-empty-p 0))
  6723. (defun org-next-line-empty-p ()
  6724. "Is the previous line a blank line?
  6725. When NEXT is non-nil, check the next line instead."
  6726. (org--line-empty-p 2))
  6727. (defun org--blank-before-heading-p (&optional parent)
  6728. "Non-nil when an empty line should precede a new heading here.
  6729. When optional argument PARENT is non-nil, consider parent
  6730. headline instead of current one."
  6731. (pcase (assq 'heading org-blank-before-new-entry)
  6732. (`(heading . auto)
  6733. (save-excursion
  6734. (org-with-limited-levels
  6735. (unless (and (org-before-first-heading-p)
  6736. (not (outline-next-heading)))
  6737. (org-back-to-heading t)
  6738. (when parent (org-up-heading-safe))
  6739. (cond ((not (bobp))
  6740. (org-previous-line-empty-p))
  6741. ((outline-next-heading)
  6742. (org-previous-line-empty-p))
  6743. ;; Ignore trailing spaces on last buffer line.
  6744. ((progn (skip-chars-backward " \t") (bolp))
  6745. (org-previous-line-empty-p))
  6746. (t nil))))))
  6747. (`(heading . ,value) value)
  6748. (_ nil)))
  6749. (defun org-insert-heading (&optional arg invisible-ok top)
  6750. "Insert a new heading or an item with the same depth at point.
  6751. If point is at the beginning of a heading, insert a new heading
  6752. or a new headline above the current one. When at the beginning
  6753. of a regular line of text, turn it into a heading.
  6754. If point is in the middle of a line, split it and create a new
  6755. headline with the text in the current line after point (see
  6756. `org-M-RET-may-split-line' on how to modify this behavior). As
  6757. a special case, on a headline, splitting can only happen on the
  6758. title itself. E.g., this excludes breaking stars or tags.
  6759. With a `\\[universal-argument]' prefix, set \
  6760. `org-insert-heading-respect-content' to
  6761. a non-nil value for the duration of the command. This forces the
  6762. insertion of a heading after the current subtree, independently
  6763. on the location of point.
  6764. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6765. insert the heading at the end of the tree
  6766. above the current heading. For example, if point is within a
  6767. 2nd-level heading, then it will insert a 2nd-level heading at
  6768. the end of the 1st-level parent subtree.
  6769. When INVISIBLE-OK is set, stop at invisible headlines when going
  6770. back. This is important for non-interactive uses of the
  6771. command.
  6772. When optional argument TOP is non-nil, insert a level 1 heading,
  6773. unconditionally."
  6774. (interactive "P")
  6775. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6776. (level (org-current-level))
  6777. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6778. (cond
  6779. ((or org-insert-heading-respect-content
  6780. (member arg '((4) (16)))
  6781. (and (not invisible-ok)
  6782. (invisible-p (max (1- (point)) (point-min)))))
  6783. ;; Position point at the location of insertion.
  6784. (if (not level) ;before first headline
  6785. (org-with-limited-levels (outline-next-heading))
  6786. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6787. ;; is nil.
  6788. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6789. (cond ((equal arg '(16))
  6790. (org-up-heading-safe)
  6791. (org-end-of-subtree t t))
  6792. (t
  6793. (org-end-of-subtree t t))))
  6794. (unless (bolp) (insert "\n")) ;ensure final newline
  6795. (unless (and blank? (org-previous-line-empty-p))
  6796. (org-N-empty-lines-before-current (if blank? 1 0)))
  6797. (insert stars " \n")
  6798. (forward-char -1))
  6799. ;; At a headline...
  6800. ((org-at-heading-p)
  6801. (cond ((bolp)
  6802. (when blank? (save-excursion (insert "\n")))
  6803. (save-excursion (insert stars " \n"))
  6804. (unless (and blank? (org-previous-line-empty-p))
  6805. (org-N-empty-lines-before-current (if blank? 1 0)))
  6806. (end-of-line))
  6807. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6808. (org-match-line org-complex-heading-regexp)
  6809. (org-pos-in-match-range (point) 4))
  6810. ;; Grab the text that should moved to the new headline.
  6811. ;; Preserve tags.
  6812. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6813. (if (looking-at "[ \t]*$") (replace-match "")
  6814. (org-align-tags))
  6815. (end-of-line)
  6816. (when blank? (insert "\n"))
  6817. (insert "\n" stars " ")
  6818. (when (org-string-nw-p split) (insert split))
  6819. (when (eobp) (save-excursion (insert "\n")))))
  6820. (t
  6821. (end-of-line)
  6822. (when blank? (insert "\n"))
  6823. (insert "\n" stars " ")
  6824. (when (eobp) (save-excursion (insert "\n"))))))
  6825. ;; On regular text, turn line into a headline or split, if
  6826. ;; appropriate.
  6827. ((bolp)
  6828. (insert stars " ")
  6829. (unless (and blank? (org-previous-line-empty-p))
  6830. (org-N-empty-lines-before-current (if blank? 1 0))))
  6831. (t
  6832. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6833. (end-of-line))
  6834. (insert "\n" stars " ")
  6835. (unless (and blank? (org-previous-line-empty-p))
  6836. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6837. (run-hooks 'org-insert-heading-hook))
  6838. (defun org-N-empty-lines-before-current (n)
  6839. "Make the number of empty lines before current exactly N.
  6840. So this will delete or add empty lines."
  6841. (let ((column (current-column)))
  6842. (beginning-of-line)
  6843. (unless (bobp)
  6844. (let ((start (save-excursion
  6845. (skip-chars-backward " \r\t\n")
  6846. (line-end-position))))
  6847. (delete-region start (line-end-position 0))))
  6848. (insert (make-string n ?\n))
  6849. (move-to-column column)))
  6850. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6851. "Return the heading of the current entry, without the stars.
  6852. When NO-TAGS is non-nil, don't include tags.
  6853. When NO-TODO is non-nil, don't include TODO keywords.
  6854. When NO-PRIORITY is non-nil, don't include priority cookie.
  6855. When NO-COMMENT is non-nil, don't include COMMENT string."
  6856. (save-excursion
  6857. (org-back-to-heading t)
  6858. (let ((case-fold-search nil))
  6859. (looking-at org-complex-heading-regexp)
  6860. (let ((todo (and (not no-todo) (match-string 2)))
  6861. (priority (and (not no-priority) (match-string 3)))
  6862. (headline (pcase (match-string 4)
  6863. (`nil "")
  6864. ((and (guard no-comment) h)
  6865. (replace-regexp-in-string
  6866. (eval-when-compile
  6867. (format "\\`%s[ \t]+" org-comment-string))
  6868. "" h))
  6869. (h h)))
  6870. (tags (and (not no-tags) (match-string 5))))
  6871. (mapconcat #'identity
  6872. (delq nil (list todo priority headline tags))
  6873. " ")))))
  6874. (defun org-heading-components ()
  6875. "Return the components of the current heading.
  6876. This is a list with the following elements:
  6877. - the level as an integer
  6878. - the reduced level, different if `org-odd-levels-only' is set.
  6879. - the TODO keyword, or nil
  6880. - the priority character, like ?A, or nil if no priority is given
  6881. - the headline text itself, or the tags string if no headline text
  6882. - the tags string, or nil."
  6883. (save-excursion
  6884. (org-back-to-heading t)
  6885. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6886. (list (length (match-string 1))
  6887. (org-reduced-level (length (match-string 1)))
  6888. (match-string-no-properties 2)
  6889. (and (match-end 3) (aref (match-string 3) 2))
  6890. (match-string-no-properties 4)
  6891. (match-string-no-properties 5)))))
  6892. (defun org-get-entry ()
  6893. "Get the entry text, after heading, entire subtree."
  6894. (save-excursion
  6895. (org-back-to-heading t)
  6896. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6897. (defun org-edit-headline (&optional heading)
  6898. "Edit the current headline.
  6899. Set it to HEADING when provided."
  6900. (interactive)
  6901. (org-with-wide-buffer
  6902. (org-back-to-heading t)
  6903. (let ((case-fold-search nil))
  6904. (when (looking-at org-complex-heading-regexp)
  6905. (let* ((old (match-string-no-properties 4))
  6906. (new (save-match-data
  6907. (org-trim (or heading (read-string "Edit: " old))))))
  6908. (unless (equal old new)
  6909. (if old (replace-match new t t nil 4)
  6910. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6911. (insert " " new))
  6912. (org-align-tags)
  6913. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6914. (defun org-insert-heading-after-current ()
  6915. "Insert a new heading with same level as current, after current subtree."
  6916. (interactive)
  6917. (org-back-to-heading)
  6918. (org-insert-heading)
  6919. (org-move-subtree-down)
  6920. (end-of-line 1))
  6921. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6922. "Insert heading with `org-insert-heading-respect-content' set to t."
  6923. (interactive)
  6924. (org-insert-heading '(4) invisible-ok))
  6925. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6926. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6927. (interactive)
  6928. (org-insert-todo-heading force-state '(4)))
  6929. (defun org-insert-todo-heading (arg &optional force-heading)
  6930. "Insert a new heading with the same level and TODO state as current heading.
  6931. If the heading has no TODO state, or if the state is DONE, use
  6932. the first state (TODO by default). Also with one prefix arg,
  6933. force first state. With two prefix args, force inserting at the
  6934. end of the parent subtree.
  6935. When called at a plain list item, insert a new item with an
  6936. unchecked check box."
  6937. (interactive "P")
  6938. (when (or force-heading (not (org-insert-item 'checkbox)))
  6939. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6940. force-heading))
  6941. (save-excursion
  6942. (org-forward-heading-same-level -1)
  6943. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6944. (let* ((new-mark-x
  6945. (if (or (equal arg '(4))
  6946. (not (match-beginning 2))
  6947. (member (match-string 2) org-done-keywords))
  6948. (car org-todo-keywords-1)
  6949. (match-string 2)))
  6950. (new-mark
  6951. (or
  6952. (run-hook-with-args-until-success
  6953. 'org-todo-get-default-hook new-mark-x nil)
  6954. new-mark-x)))
  6955. (beginning-of-line 1)
  6956. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6957. (if org-treat-insert-todo-heading-as-state-change
  6958. (org-todo new-mark)
  6959. (insert new-mark " "))))
  6960. (when org-provide-todo-statistics
  6961. (org-update-parent-todo-statistics))))
  6962. (defun org-insert-subheading (arg)
  6963. "Insert a new subheading and demote it.
  6964. Works for outline headings and for plain lists alike."
  6965. (interactive "P")
  6966. (org-insert-heading arg)
  6967. (cond
  6968. ((org-at-heading-p) (org-do-demote))
  6969. ((org-at-item-p) (org-indent-item))))
  6970. (defun org-insert-todo-subheading (arg)
  6971. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6972. Works for outline headings and for plain lists alike."
  6973. (interactive "P")
  6974. (org-insert-todo-heading arg)
  6975. (cond
  6976. ((org-at-heading-p) (org-do-demote))
  6977. ((org-at-item-p) (org-indent-item))))
  6978. ;;; Promotion and Demotion
  6979. (defvar org-after-demote-entry-hook nil
  6980. "Hook run after an entry has been demoted.
  6981. The cursor will be at the beginning of the entry.
  6982. When a subtree is being demoted, the hook will be called for each node.")
  6983. (defvar org-after-promote-entry-hook nil
  6984. "Hook run after an entry has been promoted.
  6985. The cursor will be at the beginning of the entry.
  6986. When a subtree is being promoted, the hook will be called for each node.")
  6987. (defun org-promote-subtree ()
  6988. "Promote the entire subtree.
  6989. See also `org-promote'."
  6990. (interactive)
  6991. (save-excursion
  6992. (org-with-limited-levels (org-map-tree 'org-promote)))
  6993. (org-fix-position-after-promote))
  6994. (defun org-demote-subtree ()
  6995. "Demote the entire subtree.
  6996. See `org-demote' and `org-promote'."
  6997. (interactive)
  6998. (save-excursion
  6999. (org-with-limited-levels (org-map-tree 'org-demote)))
  7000. (org-fix-position-after-promote))
  7001. (defun org-do-promote ()
  7002. "Promote the current heading higher up the tree.
  7003. If the region is active in `transient-mark-mode', promote all
  7004. headings in the region."
  7005. (interactive)
  7006. (save-excursion
  7007. (if (org-region-active-p)
  7008. (org-map-region 'org-promote (region-beginning) (region-end))
  7009. (org-promote)))
  7010. (org-fix-position-after-promote))
  7011. (defun org-do-demote ()
  7012. "Demote the current heading lower down the tree.
  7013. If the region is active in `transient-mark-mode', demote all
  7014. headings in the region."
  7015. (interactive)
  7016. (save-excursion
  7017. (if (org-region-active-p)
  7018. (org-map-region 'org-demote (region-beginning) (region-end))
  7019. (org-demote)))
  7020. (org-fix-position-after-promote))
  7021. (defun org-fix-position-after-promote ()
  7022. "Fix cursor position and indentation after demoting/promoting."
  7023. (let ((pos (point)))
  7024. (when (save-excursion
  7025. (beginning-of-line)
  7026. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  7027. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  7028. (cond ((eobp) (insert " "))
  7029. ((eolp) (insert " "))
  7030. ((equal (char-after) ?\s) (forward-char 1))))))
  7031. (defun org-current-level ()
  7032. "Return the level of the current entry, or nil if before the first headline.
  7033. The level is the number of stars at the beginning of the
  7034. headline. Use `org-reduced-level' to remove the effect of
  7035. `org-odd-levels'. Unlike to `org-outline-level', this function
  7036. ignores inlinetasks."
  7037. (let ((level (org-with-limited-levels (org-outline-level))))
  7038. (and (> level 0) level)))
  7039. (defun org-get-previous-line-level ()
  7040. "Return the outline depth of the last headline before the current line.
  7041. Returns 0 for the first headline in the buffer, and nil if before the
  7042. first headline."
  7043. (and (org-current-level)
  7044. (or (and (/= (line-beginning-position) (point-min))
  7045. (save-excursion (beginning-of-line 0) (org-current-level)))
  7046. 0)))
  7047. (defun org-reduced-level (l)
  7048. "Compute the effective level of a heading.
  7049. This takes into account the setting of `org-odd-levels-only'."
  7050. (cond
  7051. ((zerop l) 0)
  7052. (org-odd-levels-only (1+ (floor (/ l 2))))
  7053. (t l)))
  7054. (defun org-level-increment ()
  7055. "Return the number of stars that will be added or removed at a
  7056. time to headlines when structure editing, based on the value of
  7057. `org-odd-levels-only'."
  7058. (if org-odd-levels-only 2 1))
  7059. (defun org-get-valid-level (level &optional change)
  7060. "Rectify a level change under the influence of `org-odd-levels-only'.
  7061. LEVEL is a current level, CHANGE is by how much the level should
  7062. be modified. Even if CHANGE is nil, LEVEL may be returned
  7063. modified because even level numbers will become the next higher
  7064. odd number. Returns values greater than 0."
  7065. (if org-odd-levels-only
  7066. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7067. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  7068. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7069. (max 1 (+ level (or change 0)))))
  7070. (defun org-promote ()
  7071. "Promote the current heading higher up the tree."
  7072. (org-with-wide-buffer
  7073. (org-back-to-heading t)
  7074. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7075. after-change-functions))
  7076. (level (save-match-data (funcall outline-level)))
  7077. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7078. (diff (abs (- level (length up-head) -1))))
  7079. (cond
  7080. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7081. (replace-match "# " nil t))
  7082. ((= level 1)
  7083. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7084. (t (replace-match up-head nil t)))
  7085. (unless (= level 1)
  7086. (when org-auto-align-tags (org-align-tags))
  7087. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7088. (run-hooks 'org-after-promote-entry-hook))))
  7089. (defun org-demote ()
  7090. "Demote the current heading lower down the tree."
  7091. (org-with-wide-buffer
  7092. (org-back-to-heading t)
  7093. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7094. after-change-functions))
  7095. (level (save-match-data (funcall outline-level)))
  7096. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7097. (diff (abs (- level (length down-head) -1))))
  7098. (replace-match down-head nil t)
  7099. (when org-auto-align-tags (org-align-tags))
  7100. (when org-adapt-indentation (org-fixup-indentation diff))
  7101. (run-hooks 'org-after-demote-entry-hook))))
  7102. (defun org-cycle-level ()
  7103. "Cycle the level of an empty headline through possible states.
  7104. This goes first to child, then to parent, level, then up the hierarchy.
  7105. After top level, it switches back to sibling level."
  7106. (interactive)
  7107. (let ((org-adapt-indentation nil))
  7108. (when (org-point-at-end-of-empty-headline)
  7109. (setq this-command 'org-cycle-level) ; Only needed for caching
  7110. (let ((cur-level (org-current-level))
  7111. (prev-level (org-get-previous-line-level)))
  7112. (cond
  7113. ;; If first headline in file, promote to top-level.
  7114. ((= prev-level 0)
  7115. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7116. do (org-do-promote)))
  7117. ;; If same level as prev, demote one.
  7118. ((= prev-level cur-level)
  7119. (org-do-demote))
  7120. ;; If parent is top-level, promote to top level if not already.
  7121. ((= prev-level 1)
  7122. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7123. do (org-do-promote)))
  7124. ;; If top-level, return to prev-level.
  7125. ((= cur-level 1)
  7126. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7127. do (org-do-demote)))
  7128. ;; If less than prev-level, promote one.
  7129. ((< cur-level prev-level)
  7130. (org-do-promote))
  7131. ;; If deeper than prev-level, promote until higher than
  7132. ;; prev-level.
  7133. ((> cur-level prev-level)
  7134. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7135. do (org-do-promote))))
  7136. t))))
  7137. (defun org-map-tree (fun)
  7138. "Call FUN for every heading underneath the current one."
  7139. (org-back-to-heading t)
  7140. (let ((level (funcall outline-level)))
  7141. (save-excursion
  7142. (funcall fun)
  7143. (while (and (progn
  7144. (outline-next-heading)
  7145. (> (funcall outline-level) level))
  7146. (not (eobp)))
  7147. (funcall fun)))))
  7148. (defun org-map-region (fun beg end)
  7149. "Call FUN for every heading between BEG and END."
  7150. (let ((org-ignore-region t))
  7151. (save-excursion
  7152. (setq end (copy-marker end))
  7153. (goto-char beg)
  7154. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7155. (< (point) end))
  7156. (funcall fun))
  7157. (while (and (progn
  7158. (outline-next-heading)
  7159. (< (point) end))
  7160. (not (eobp)))
  7161. (funcall fun)))))
  7162. (defun org-fixup-indentation (diff)
  7163. "Change the indentation in the current entry by DIFF.
  7164. DIFF is an integer. Indentation is done according to the
  7165. following rules:
  7166. - Planning information and property drawers are always indented
  7167. according to the new level of the headline;
  7168. - Footnote definitions and their contents are ignored;
  7169. - Inlinetasks' boundaries are not shifted;
  7170. - Empty lines are ignored;
  7171. - Other lines' indentation are shifted by DIFF columns, unless
  7172. it would introduce a structural change in the document, in
  7173. which case no shifting is done at all.
  7174. Assume point is at a heading or an inlinetask beginning."
  7175. (org-with-wide-buffer
  7176. (narrow-to-region (line-beginning-position)
  7177. (save-excursion
  7178. (if (org-with-limited-levels (org-at-heading-p))
  7179. (org-with-limited-levels (outline-next-heading))
  7180. (org-inlinetask-goto-end))
  7181. (point)))
  7182. (forward-line)
  7183. ;; Indent properly planning info and property drawer.
  7184. (when (looking-at-p org-planning-line-re)
  7185. (org-indent-line)
  7186. (forward-line))
  7187. (when (looking-at org-property-drawer-re)
  7188. (goto-char (match-end 0))
  7189. (forward-line)
  7190. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7191. (catch 'no-shift
  7192. (when (zerop diff) (throw 'no-shift nil))
  7193. ;; If DIFF is negative, first check if a shift is possible at all
  7194. ;; (e.g., it doesn't break structure). This can only happen if
  7195. ;; some contents are not properly indented.
  7196. (let ((case-fold-search t))
  7197. (when (< diff 0)
  7198. (let ((diff (- diff))
  7199. (forbidden-re (concat org-outline-regexp
  7200. "\\|"
  7201. (substring org-footnote-definition-re 1))))
  7202. (save-excursion
  7203. (while (not (eobp))
  7204. (cond
  7205. ((looking-at-p "[ \t]*$") (forward-line))
  7206. ((and (looking-at-p org-footnote-definition-re)
  7207. (let ((e (org-element-at-point)))
  7208. (and (eq (org-element-type e) 'footnote-definition)
  7209. (goto-char (org-element-property :end e))))))
  7210. ((looking-at-p org-outline-regexp) (forward-line))
  7211. ;; Give up if shifting would move before column 0 or
  7212. ;; if it would introduce a headline or a footnote
  7213. ;; definition.
  7214. (t
  7215. (skip-chars-forward " \t")
  7216. (let ((ind (current-column)))
  7217. (when (or (< ind diff)
  7218. (and (= ind diff) (looking-at-p forbidden-re)))
  7219. (throw 'no-shift nil)))
  7220. ;; Ignore contents of example blocks and source
  7221. ;; blocks if their indentation is meant to be
  7222. ;; preserved. Jump to block's closing line.
  7223. (beginning-of-line)
  7224. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7225. (let ((e (org-element-at-point)))
  7226. (and (memq (org-element-type e)
  7227. '(example-block src-block))
  7228. (or org-src-preserve-indentation
  7229. (org-element-property :preserve-indent e))
  7230. (goto-char (org-element-property :end e))
  7231. (progn (skip-chars-backward " \r\t\n")
  7232. (beginning-of-line)
  7233. t))))
  7234. (forward-line))))))))
  7235. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7236. ;; by DIFF. Also skip contents of source or example blocks
  7237. ;; when indentation is meant to be preserved.
  7238. (while (not (eobp))
  7239. (cond
  7240. ((and (looking-at-p org-footnote-definition-re)
  7241. (let ((e (org-element-at-point)))
  7242. (and (eq (org-element-type e) 'footnote-definition)
  7243. (goto-char (org-element-property :end e))))))
  7244. ((looking-at-p org-outline-regexp) (forward-line))
  7245. ((looking-at-p "[ \t]*$") (forward-line))
  7246. (t
  7247. (indent-line-to (+ (current-indentation) diff))
  7248. (beginning-of-line)
  7249. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7250. (let ((e (org-element-at-point)))
  7251. (and (memq (org-element-type e)
  7252. '(example-block src-block))
  7253. (or org-src-preserve-indentation
  7254. (org-element-property :preserve-indent e))
  7255. (goto-char (org-element-property :end e))
  7256. (progn (skip-chars-backward " \r\t\n")
  7257. (beginning-of-line)
  7258. t))))
  7259. (forward-line)))))))))
  7260. (defun org-convert-to-odd-levels ()
  7261. "Convert an Org file with all levels allowed to one with odd levels.
  7262. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7263. level 5 etc."
  7264. (interactive)
  7265. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7266. (let ((outline-level 'org-outline-level)
  7267. (org-odd-levels-only nil) n)
  7268. (save-excursion
  7269. (goto-char (point-min))
  7270. (while (re-search-forward "^\\*\\*+ " nil t)
  7271. (setq n (- (length (match-string 0)) 2))
  7272. (while (>= (setq n (1- n)) 0)
  7273. (org-demote))
  7274. (end-of-line 1))))))
  7275. (defun org-convert-to-oddeven-levels ()
  7276. "Convert an Org file with only odd levels to one with odd/even levels.
  7277. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7278. file contains a section with an even level, conversion would
  7279. destroy the structure of the file. An error is signaled in this
  7280. case."
  7281. (interactive)
  7282. (goto-char (point-min))
  7283. ;; First check if there are no even levels
  7284. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7285. (org-show-set-visibility 'canonical)
  7286. (error "Not all levels are odd in this file. Conversion not possible"))
  7287. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7288. (let ((outline-regexp org-outline-regexp)
  7289. (outline-level 'org-outline-level)
  7290. (org-odd-levels-only nil) n)
  7291. (save-excursion
  7292. (goto-char (point-min))
  7293. (while (re-search-forward "^\\*\\*+ " nil t)
  7294. (setq n (/ (1- (length (match-string 0))) 2))
  7295. (while (>= (setq n (1- n)) 0)
  7296. (org-promote))
  7297. (end-of-line 1))))))
  7298. (defun org-tr-level (n)
  7299. "Make N odd if required."
  7300. (if org-odd-levels-only (1+ (/ n 2)) n))
  7301. ;;; Vertical tree motion, cutting and pasting of subtrees
  7302. (defun org-move-subtree-up (&optional arg)
  7303. "Move the current subtree up past ARG headlines of the same level."
  7304. (interactive "p")
  7305. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7306. (defun org-move-subtree-down (&optional arg)
  7307. "Move the current subtree down past ARG headlines of the same level."
  7308. (interactive "p")
  7309. (setq arg (prefix-numeric-value arg))
  7310. (org-preserve-local-variables
  7311. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7312. 'org-get-last-sibling))
  7313. (ins-point (make-marker))
  7314. (cnt (abs arg))
  7315. (col (current-column))
  7316. beg end txt folded)
  7317. ;; Select the tree
  7318. (org-back-to-heading)
  7319. (setq beg (point))
  7320. (save-match-data
  7321. (save-excursion (outline-end-of-heading)
  7322. (setq folded (org-invisible-p)))
  7323. (progn (org-end-of-subtree nil t)
  7324. (unless (eobp) (backward-char))))
  7325. (outline-next-heading)
  7326. (setq end (point))
  7327. (goto-char beg)
  7328. ;; Find insertion point, with error handling
  7329. (while (> cnt 0)
  7330. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  7331. (goto-char beg)
  7332. (user-error "Cannot move past superior level or buffer limit"))
  7333. (setq cnt (1- cnt)))
  7334. (when (> arg 0)
  7335. ;; Moving forward - still need to move over subtree
  7336. (org-end-of-subtree t t)
  7337. (save-excursion
  7338. (org-back-over-empty-lines)
  7339. (or (bolp) (newline))))
  7340. (move-marker ins-point (point))
  7341. (setq txt (buffer-substring beg end))
  7342. (org-save-markers-in-region beg end)
  7343. (delete-region beg end)
  7344. (org-remove-empty-overlays-at beg)
  7345. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  7346. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  7347. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7348. (let ((bbb (point)))
  7349. (insert-before-markers txt)
  7350. (org-reinstall-markers-in-region bbb)
  7351. (move-marker ins-point bbb))
  7352. (or (bolp) (insert "\n"))
  7353. (goto-char ins-point)
  7354. (org-skip-whitespace)
  7355. (move-marker ins-point nil)
  7356. (if folded
  7357. (outline-hide-subtree)
  7358. (org-show-entry)
  7359. (org-show-children))
  7360. (org-clean-visibility-after-subtree-move)
  7361. ;; move back to the initial column we were at
  7362. (move-to-column col))))
  7363. (defvar org-subtree-clip ""
  7364. "Clipboard for cut and paste of subtrees.
  7365. This is actually only a copy of the kill, because we use the normal kill
  7366. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7367. (defvar org-subtree-clip-folded nil
  7368. "Was the last copied subtree folded?
  7369. This is used to fold the tree back after pasting.")
  7370. (defun org-cut-subtree (&optional n)
  7371. "Cut the current subtree into the clipboard.
  7372. With prefix arg N, cut this many sequential subtrees.
  7373. This is a short-hand for marking the subtree and then cutting it."
  7374. (interactive "p")
  7375. (org-copy-subtree n 'cut))
  7376. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7377. "Copy the current subtree into the clipboard.
  7378. With prefix arg N, copy this many sequential subtrees.
  7379. This is a short-hand for marking the subtree and then copying it.
  7380. If CUT is non-nil, actually cut the subtree.
  7381. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7382. of some markers in the region, even if CUT is non-nil. This is
  7383. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7384. (interactive "p")
  7385. (org-preserve-local-variables
  7386. (let (beg end folded (beg0 (point)))
  7387. (if (called-interactively-p 'any)
  7388. (org-back-to-heading nil) ; take what looks like a subtree
  7389. (org-back-to-heading t)) ; take what is really there
  7390. (setq beg (point))
  7391. (skip-chars-forward " \t\r\n")
  7392. (save-match-data
  7393. (if nosubtrees
  7394. (outline-next-heading)
  7395. (save-excursion (outline-end-of-heading)
  7396. (setq folded (org-invisible-p)))
  7397. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7398. (org-end-of-subtree t t)))
  7399. ;; Include the end of an inlinetask
  7400. (when (and (featurep 'org-inlinetask)
  7401. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7402. "END[ \t]*$")))
  7403. (end-of-line))
  7404. (setq end (point))
  7405. (goto-char beg0)
  7406. (when (> end beg)
  7407. (setq org-subtree-clip-folded folded)
  7408. (when (or cut force-store-markers)
  7409. (org-save-markers-in-region beg end))
  7410. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7411. (setq org-subtree-clip (current-kill 0))
  7412. (message "%s: Subtree(s) with %d characters"
  7413. (if cut "Cut" "Copied")
  7414. (length org-subtree-clip))))))
  7415. (defun org-paste-subtree (&optional level tree for-yank remove)
  7416. "Paste the clipboard as a subtree, with modification of headline level.
  7417. The entire subtree is promoted or demoted in order to match a new headline
  7418. level.
  7419. If the cursor is at the beginning of a headline, the same level as
  7420. that headline is used to paste the tree.
  7421. If not, the new level is derived from the *visible* headings
  7422. before and after the insertion point, and taken to be the inferior headline
  7423. level of the two. So if the previous visible heading is level 3 and the
  7424. next is level 4 (or vice versa), level 4 will be used for insertion.
  7425. This makes sure that the subtree remains an independent subtree and does
  7426. not swallow low level entries.
  7427. You can also force a different level, either by using a numeric prefix
  7428. argument, or by inserting the heading marker by hand. For example, if the
  7429. cursor is after \"*****\", then the tree will be shifted to level 5.
  7430. If optional TREE is given, use this text instead of the kill ring.
  7431. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7432. move back over whitespace before inserting, and move point to the end of
  7433. the inserted text when done.
  7434. When REMOVE is non-nil, remove the subtree from the clipboard."
  7435. (interactive "P")
  7436. (setq tree (or tree (and kill-ring (current-kill 0))))
  7437. (unless (org-kill-is-subtree-p tree)
  7438. (user-error
  7439. (substitute-command-keys
  7440. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  7441. (org-with-limited-levels
  7442. (let* ((visp (not (org-invisible-p)))
  7443. (txt tree)
  7444. (old-level (if (string-match org-outline-regexp-bol txt)
  7445. (- (match-end 0) (match-beginning 0) 1)
  7446. -1))
  7447. (force-level
  7448. (cond
  7449. (level (prefix-numeric-value level))
  7450. ;; When point is right after the stars in an otherwise
  7451. ;; empty headline, use stars as the forced level.
  7452. ((and (looking-at-p "[ \t]*$")
  7453. (string-match-p "^\\*+ *"
  7454. (buffer-substring (line-beginning-position)
  7455. (point))))
  7456. (org-outline-level))
  7457. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  7458. (previous-level
  7459. (save-excursion
  7460. (org-previous-visible-heading 1)
  7461. (if (org-at-heading-p) (org-outline-level) 1)))
  7462. (next-level
  7463. (save-excursion
  7464. (if (org-at-heading-p) (org-outline-level)
  7465. (org-next-visible-heading 1)
  7466. (if (org-at-heading-p) (org-outline-level) 1))))
  7467. (new-level (or force-level (max previous-level next-level)))
  7468. (shift (if (or (= old-level -1)
  7469. (= new-level -1)
  7470. (= old-level new-level))
  7471. 0
  7472. (- new-level old-level)))
  7473. (delta (if (> shift 0) -1 1))
  7474. (func (if (> shift 0) #'org-demote #'org-promote))
  7475. (org-odd-levels-only nil)
  7476. beg end newend)
  7477. ;; Remove the forced level indicator.
  7478. (when (and force-level (not level))
  7479. (delete-region (line-beginning-position) (point)))
  7480. ;; Paste before the next visible heading or at end of buffer,
  7481. ;; unless point is at the beginning of a headline.
  7482. (unless (and (bolp) (org-at-heading-p))
  7483. (org-next-visible-heading 1)
  7484. (unless (bolp) (insert "\n")))
  7485. (setq beg (point))
  7486. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7487. (insert-before-markers txt)
  7488. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7489. (setq newend (point))
  7490. (org-reinstall-markers-in-region beg)
  7491. (setq end (point))
  7492. (goto-char beg)
  7493. (skip-chars-forward " \t\n\r")
  7494. (setq beg (point))
  7495. (when (and (org-invisible-p) visp)
  7496. (save-excursion (outline-show-heading)))
  7497. ;; Shift if necessary.
  7498. (unless (= shift 0)
  7499. (save-restriction
  7500. (narrow-to-region beg end)
  7501. (while (not (= shift 0))
  7502. (org-map-region func (point-min) (point-max))
  7503. (setq shift (+ delta shift)))
  7504. (goto-char (point-min))
  7505. (setq newend (point-max))))
  7506. (when (or for-yank (called-interactively-p 'interactive))
  7507. (message "Clipboard pasted as level %d subtree" new-level))
  7508. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7509. kill-ring
  7510. (equal org-subtree-clip (current-kill 0))
  7511. org-subtree-clip-folded)
  7512. ;; The tree was folded before it was killed/copied
  7513. (outline-hide-subtree))
  7514. (when for-yank (goto-char newend))
  7515. (when remove (pop kill-ring)))))
  7516. (defun org-kill-is-subtree-p (&optional txt)
  7517. "Check if the current kill is an outline subtree, or a set of trees.
  7518. Returns nil if kill does not start with a headline, or if the first
  7519. headline level is not the largest headline level in the tree.
  7520. So this will actually accept several entries of equal levels as well,
  7521. which is OK for `org-paste-subtree'.
  7522. If optional TXT is given, check this string instead of the current kill."
  7523. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7524. (re (org-get-limited-outline-regexp))
  7525. (^re (concat "^" re))
  7526. (start-level (and kill
  7527. (string-match
  7528. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7529. kill)
  7530. (- (match-end 2) (match-beginning 2) 1)))
  7531. (start (1+ (or (match-beginning 2) -1))))
  7532. (if (not start-level)
  7533. (progn
  7534. nil) ;; does not even start with a heading
  7535. (catch 'exit
  7536. (while (setq start (string-match ^re kill (1+ start)))
  7537. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7538. (throw 'exit nil)))
  7539. t))))
  7540. (defvar org-markers-to-move nil
  7541. "Markers that should be moved with a cut-and-paste operation.
  7542. Those markers are stored together with their positions relative to
  7543. the start of the region.")
  7544. (defun org-save-markers-in-region (beg end)
  7545. "Check markers in region.
  7546. If these markers are between BEG and END, record their position relative
  7547. to BEG, so that after moving the block of text, we can put the markers back
  7548. into place.
  7549. This function gets called just before an entry or tree gets cut from the
  7550. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7551. called immediately, to move the markers with the entries."
  7552. (setq org-markers-to-move nil)
  7553. (when (featurep 'org-clock)
  7554. (org-clock-save-markers-for-cut-and-paste beg end))
  7555. (when (featurep 'org-agenda)
  7556. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7557. (defun org-check-and-save-marker (marker beg end)
  7558. "Check if MARKER is between BEG and END.
  7559. If yes, remember the marker and the distance to BEG."
  7560. (when (and (marker-buffer marker)
  7561. (equal (marker-buffer marker) (current-buffer))
  7562. (>= marker beg) (< marker end))
  7563. (push (cons marker (- marker beg)) org-markers-to-move)))
  7564. (defun org-reinstall-markers-in-region (beg)
  7565. "Move all remembered markers to their position relative to BEG."
  7566. (dolist (x org-markers-to-move)
  7567. (move-marker (car x) (+ beg (cdr x))))
  7568. (setq org-markers-to-move nil))
  7569. (defun org-narrow-to-subtree ()
  7570. "Narrow buffer to the current subtree."
  7571. (interactive)
  7572. (save-excursion
  7573. (save-match-data
  7574. (org-with-limited-levels
  7575. (narrow-to-region
  7576. (progn (org-back-to-heading t) (point))
  7577. (progn (org-end-of-subtree t t)
  7578. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7579. (point)))))))
  7580. (defun org-toggle-narrow-to-subtree ()
  7581. "Narrow to the subtree at point or widen a narrowed buffer."
  7582. (interactive)
  7583. (if (buffer-narrowed-p)
  7584. (widen)
  7585. (org-narrow-to-subtree)))
  7586. (defun org-narrow-to-block ()
  7587. "Narrow buffer to the current block."
  7588. (interactive)
  7589. (let* ((case-fold-search t)
  7590. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7591. "^[ \t]*#\\+end_.*")))
  7592. (if blockp
  7593. (narrow-to-region (car blockp) (cdr blockp))
  7594. (user-error "Not in a block"))))
  7595. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7596. "Clone the task (subtree) at point N times.
  7597. The clones will be inserted as siblings.
  7598. In interactive use, the user will be prompted for the number of
  7599. clones to be produced. If the entry has a timestamp, the user
  7600. will also be prompted for a time shift, which may be a repeater
  7601. as used in time stamps, for example `+3d'. To disable this,
  7602. you can call the function with a universal prefix argument.
  7603. When a valid repeater is given and the entry contains any time
  7604. stamps, the clones will become a sequence in time, with time
  7605. stamps in the subtree shifted for each clone produced. If SHIFT
  7606. is nil or the empty string, time stamps will be left alone. The
  7607. ID property of the original subtree is removed.
  7608. In each clone, all the CLOCK entries will be removed. This
  7609. prevents Org from considering that the clocked times overlap.
  7610. If the original subtree did contain time stamps with a repeater,
  7611. the following will happen:
  7612. - the repeater will be removed in each clone
  7613. - an additional clone will be produced, with the current, unshifted
  7614. date(s) in the entry.
  7615. - the original entry will be placed *after* all the clones, with
  7616. repeater intact.
  7617. - the start days in the repeater in the original entry will be shifted
  7618. to past the last clone.
  7619. In this way you can spell out a number of instances of a repeating task,
  7620. and still retain the repeater to cover future instances of the task.
  7621. As described above, N+1 clones are produced when the original
  7622. subtree has a repeater. Setting N to 0, then, can be used to
  7623. remove the repeater from a subtree and create a shifted clone
  7624. with the original repeater."
  7625. (interactive "nNumber of clones to produce: ")
  7626. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7627. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7628. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7629. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7630. (shift
  7631. (or shift
  7632. (if (and (not (equal current-prefix-arg '(4)))
  7633. (save-excursion
  7634. (goto-char beg)
  7635. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7636. (read-from-minibuffer
  7637. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7638. ""))) ;No time shift
  7639. (doshift
  7640. (and (org-string-nw-p shift)
  7641. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7642. shift)
  7643. (user-error "Invalid shift specification %s" shift)))))
  7644. (goto-char end-of-tree)
  7645. (unless (bolp) (insert "\n"))
  7646. (let* ((end (point))
  7647. (template (buffer-substring beg end))
  7648. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7649. (shift-what (pcase (and doshift (match-string 2 shift))
  7650. (`nil nil)
  7651. ("d" 'day)
  7652. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7653. ("m" 'month)
  7654. ("y" 'year)
  7655. (_ (error "Unsupported time unit"))))
  7656. (nmin 1)
  7657. (nmax n)
  7658. (n-no-remove -1)
  7659. (idprop (org-entry-get nil "ID")))
  7660. (when (and doshift
  7661. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7662. template))
  7663. (delete-region beg end)
  7664. (setq end beg)
  7665. (setq nmin 0)
  7666. (setq nmax (1+ nmax))
  7667. (setq n-no-remove nmax))
  7668. (goto-char end)
  7669. (cl-loop for n from nmin to nmax do
  7670. (insert
  7671. ;; Prepare clone.
  7672. (with-temp-buffer
  7673. (insert template)
  7674. (org-mode)
  7675. (goto-char (point-min))
  7676. (org-show-subtree)
  7677. (and idprop (if org-clone-delete-id
  7678. (org-entry-delete nil "ID")
  7679. (org-id-get-create t)))
  7680. (unless (= n 0)
  7681. (while (re-search-forward org-clock-line-re nil t)
  7682. (delete-region (line-beginning-position)
  7683. (line-beginning-position 2)))
  7684. (goto-char (point-min))
  7685. (while (re-search-forward org-drawer-regexp nil t)
  7686. (org-remove-empty-drawer-at (point))))
  7687. (goto-char (point-min))
  7688. (when doshift
  7689. (while (re-search-forward org-ts-regexp-both nil t)
  7690. (org-timestamp-change (* n shift-n) shift-what))
  7691. (unless (= n n-no-remove)
  7692. (goto-char (point-min))
  7693. (while (re-search-forward org-ts-regexp nil t)
  7694. (save-excursion
  7695. (goto-char (match-beginning 0))
  7696. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7697. (delete-region (match-beginning 1) (match-end 1)))))))
  7698. (buffer-string)))))
  7699. (goto-char beg)))
  7700. ;;; Outline Sorting
  7701. (defun org-sort (&optional with-case)
  7702. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7703. Optional argument WITH-CASE means sort case-sensitively."
  7704. (interactive "P")
  7705. (org-call-with-arg
  7706. (cond ((org-at-table-p) #'org-table-sort-lines)
  7707. ((org-at-item-p) #'org-sort-list)
  7708. (t #'org-sort-entries))
  7709. with-case))
  7710. (defun org-sort-remove-invisible (s)
  7711. "Remove invisible part of links and emphasis markers from string S."
  7712. (remove-text-properties 0 (length s) org-rm-props s)
  7713. (replace-regexp-in-string
  7714. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7715. (replace-regexp-in-string
  7716. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7717. (org-link-display-format s)
  7718. t t) t t))
  7719. (defvar org-priority-regexp) ; defined later in the file
  7720. (defvar org-after-sorting-entries-or-items-hook nil
  7721. "Hook that is run after a bunch of entries or items have been sorted.
  7722. When children are sorted, the cursor is in the parent line when this
  7723. hook gets called. When a region or a plain list is sorted, the cursor
  7724. will be in the first entry of the sorted region/list.")
  7725. (defun org-sort-entries
  7726. (&optional with-case sorting-type getkey-func compare-func property
  7727. interactive?)
  7728. "Sort entries on a certain level of an outline tree.
  7729. If there is an active region, the entries in the region are sorted.
  7730. Else, if the cursor is before the first entry, sort the top-level items.
  7731. Else, the children of the entry at point are sorted.
  7732. Sorting can be alphabetically, numerically, by date/time as given by
  7733. a time stamp, by a property, by priority order, or by a custom function.
  7734. The command prompts for the sorting type unless it has been given to the
  7735. function through the SORTING-TYPE argument, which needs to be a character,
  7736. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7737. the precise meaning of each character:
  7738. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7739. c By creation time, which is assumed to be the first inactive time stamp
  7740. at the beginning of a line.
  7741. d By deadline date/time.
  7742. k By clocking time.
  7743. n Numerically, by converting the beginning of the entry/item to a number.
  7744. o By order of TODO keywords.
  7745. p By priority according to the cookie.
  7746. r By the value of a property.
  7747. s By scheduled date/time.
  7748. t By date/time, either the first active time stamp in the entry, or, if
  7749. none exist, by the first inactive one.
  7750. Capital letters will reverse the sort order.
  7751. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7752. called with point at the beginning of the record. It must return a
  7753. value that is compatible with COMPARE-FUNC, the function used to
  7754. compare entries.
  7755. Comparing entries ignores case by default. However, with an optional argument
  7756. WITH-CASE, the sorting considers case as well.
  7757. Sorting is done against the visible part of the headlines, it ignores hidden
  7758. links.
  7759. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7760. A non-nil value for INTERACTIVE? is used to signal that this
  7761. function is being called interactively."
  7762. (interactive (list current-prefix-arg nil nil nil nil t))
  7763. (let ((case-func (if with-case 'identity 'downcase))
  7764. start beg end stars re re2
  7765. txt what tmp)
  7766. ;; Find beginning and end of region to sort
  7767. (cond
  7768. ((org-region-active-p)
  7769. ;; we will sort the region
  7770. (setq end (region-end)
  7771. what "region")
  7772. (goto-char (region-beginning))
  7773. (unless (org-at-heading-p) (outline-next-heading))
  7774. (setq start (point)))
  7775. ((or (org-at-heading-p)
  7776. (ignore-errors (progn (org-back-to-heading) t)))
  7777. ;; we will sort the children of the current headline
  7778. (org-back-to-heading)
  7779. (setq start (point)
  7780. end (progn (org-end-of-subtree t t)
  7781. (or (bolp) (insert "\n"))
  7782. (when (>= (org-back-over-empty-lines) 1)
  7783. (forward-line 1))
  7784. (point))
  7785. what "children")
  7786. (goto-char start)
  7787. (outline-show-subtree)
  7788. (outline-next-heading))
  7789. (t
  7790. ;; we will sort the top-level entries in this file
  7791. (goto-char (point-min))
  7792. (or (org-at-heading-p) (outline-next-heading))
  7793. (setq start (point))
  7794. (goto-char (point-max))
  7795. (beginning-of-line 1)
  7796. (when (looking-at ".*?\\S-")
  7797. ;; File ends in a non-white line
  7798. (end-of-line 1)
  7799. (insert "\n"))
  7800. (setq end (point-max))
  7801. (setq what "top-level")
  7802. (goto-char start)
  7803. (org-show-all '(headings blocks))))
  7804. (setq beg (point))
  7805. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7806. (looking-at "\\(\\*+\\)")
  7807. (setq stars (match-string 1)
  7808. re (concat "^" (regexp-quote stars) " +")
  7809. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7810. txt (buffer-substring beg end))
  7811. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7812. (when (and (not (equal stars "*")) (string-match re2 txt))
  7813. (user-error "Region to sort contains a level above the first entry"))
  7814. (unless sorting-type
  7815. (message
  7816. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7817. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7818. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7819. what)
  7820. (setq sorting-type (read-char-exclusive)))
  7821. (unless getkey-func
  7822. (and (= (downcase sorting-type) ?f)
  7823. (setq getkey-func
  7824. (or (and interactive?
  7825. (org-read-function
  7826. "Function for extracting keys: "))
  7827. (error "Missing key extractor")))))
  7828. (and (= (downcase sorting-type) ?r)
  7829. (not property)
  7830. (setq property
  7831. (completing-read "Property: "
  7832. (mapcar #'list (org-buffer-property-keys t))
  7833. nil t)))
  7834. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7835. (message "Sorting entries...")
  7836. (save-restriction
  7837. (narrow-to-region start end)
  7838. (let ((restore-clock?
  7839. ;; The clock marker is lost when using `sort-subr'; mark
  7840. ;; the clock with temporary `:org-clock-marker-backup'
  7841. ;; text property.
  7842. (when (and (eq (org-clock-is-active) (current-buffer))
  7843. (<= start (marker-position org-clock-marker))
  7844. (>= end (marker-position org-clock-marker)))
  7845. (with-silent-modifications
  7846. (put-text-property (1- org-clock-marker) org-clock-marker
  7847. :org-clock-marker-backup t))
  7848. t))
  7849. (dcst (downcase sorting-type))
  7850. (case-fold-search nil)
  7851. (now (current-time)))
  7852. (org-preserve-local-variables
  7853. (sort-subr
  7854. (/= dcst sorting-type)
  7855. ;; This function moves to the beginning character of the
  7856. ;; "record" to be sorted.
  7857. (lambda nil
  7858. (if (re-search-forward re nil t)
  7859. (goto-char (match-beginning 0))
  7860. (goto-char (point-max))))
  7861. ;; This function moves to the last character of the "record" being
  7862. ;; sorted.
  7863. (lambda nil
  7864. (save-match-data
  7865. (condition-case nil
  7866. (outline-forward-same-level 1)
  7867. (error
  7868. (goto-char (point-max))))))
  7869. ;; This function returns the value that gets sorted against.
  7870. (lambda ()
  7871. (cond
  7872. ((= dcst ?n)
  7873. (string-to-number
  7874. (org-sort-remove-invisible (org-get-heading t t t t))))
  7875. ((= dcst ?a)
  7876. (funcall case-func
  7877. (org-sort-remove-invisible (org-get-heading t t t t))))
  7878. ((= dcst ?k)
  7879. (or (get-text-property (point) :org-clock-minutes) 0))
  7880. ((= dcst ?t)
  7881. (let ((end (save-excursion (outline-next-heading) (point))))
  7882. (if (or (re-search-forward org-ts-regexp end t)
  7883. (re-search-forward org-ts-regexp-both end t))
  7884. (org-time-string-to-seconds (match-string 0))
  7885. (float-time now))))
  7886. ((= dcst ?c)
  7887. (let ((end (save-excursion (outline-next-heading) (point))))
  7888. (if (re-search-forward
  7889. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7890. end t)
  7891. (org-time-string-to-seconds (match-string 0))
  7892. (float-time now))))
  7893. ((= dcst ?s)
  7894. (let ((end (save-excursion (outline-next-heading) (point))))
  7895. (if (re-search-forward org-scheduled-time-regexp end t)
  7896. (org-time-string-to-seconds (match-string 1))
  7897. (float-time now))))
  7898. ((= dcst ?d)
  7899. (let ((end (save-excursion (outline-next-heading) (point))))
  7900. (if (re-search-forward org-deadline-time-regexp end t)
  7901. (org-time-string-to-seconds (match-string 1))
  7902. (float-time now))))
  7903. ((= dcst ?p)
  7904. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7905. (string-to-char (match-string 2))
  7906. org-default-priority))
  7907. ((= dcst ?r)
  7908. (or (org-entry-get nil property) ""))
  7909. ((= dcst ?o)
  7910. (when (looking-at org-complex-heading-regexp)
  7911. (let* ((m (match-string 2))
  7912. (s (if (member m org-done-keywords) '- '+)))
  7913. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7914. ((= dcst ?f)
  7915. (if getkey-func
  7916. (progn
  7917. (setq tmp (funcall getkey-func))
  7918. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7919. tmp)
  7920. (error "Invalid key function `%s'" getkey-func)))
  7921. (t (error "Invalid sorting type `%c'" sorting-type))))
  7922. nil
  7923. (cond
  7924. ((= dcst ?a) 'org-string-collate-lessp)
  7925. ((= dcst ?f)
  7926. (or compare-func
  7927. (and interactive?
  7928. (org-read-function
  7929. (concat "Function for comparing keys "
  7930. "(empty for default `sort-subr' predicate): ")
  7931. 'allow-empty))))
  7932. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7933. (when restore-clock?
  7934. (move-marker org-clock-marker
  7935. (1+ (next-single-property-change
  7936. start :org-clock-marker-backup)))
  7937. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7938. '(:org-clock-marker-backup t)))))
  7939. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7940. (message "Sorting entries...done")))
  7941. (defun org-contextualize-keys (alist contexts)
  7942. "Return valid elements in ALIST depending on CONTEXTS.
  7943. `org-agenda-custom-commands' or `org-capture-templates' are the
  7944. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7945. or `org-capture-templates-contexts' are the associated contexts
  7946. definitions."
  7947. (let ((contexts
  7948. ;; normalize contexts
  7949. (mapcar
  7950. (lambda(c) (cond ((listp (cadr c))
  7951. (list (car c) (car c) (nth 1 c)))
  7952. ((string= "" (cadr c))
  7953. (list (car c) (car c) (nth 2 c)))
  7954. (t c)))
  7955. contexts))
  7956. (a alist) r s)
  7957. ;; loop over all commands or templates
  7958. (dolist (c a)
  7959. (let (vrules repl)
  7960. (cond
  7961. ((not (assoc (car c) contexts))
  7962. (push c r))
  7963. ((and (assoc (car c) contexts)
  7964. (setq vrules (org-contextualize-validate-key
  7965. (car c) contexts)))
  7966. (mapc (lambda (vr)
  7967. (unless (equal (car vr) (cadr vr))
  7968. (setq repl vr)))
  7969. vrules)
  7970. (if (not repl) (push c r)
  7971. (push (cadr repl) s)
  7972. (push
  7973. (cons (car c)
  7974. (cdr (or (assoc (cadr repl) alist)
  7975. (error "Undefined key `%s' as contextual replacement for `%s'"
  7976. (cadr repl) (car c)))))
  7977. r))))))
  7978. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7979. (delq
  7980. nil
  7981. (delete-dups
  7982. (mapcar (lambda (x)
  7983. (let ((tpl (car x)))
  7984. (unless (delq
  7985. nil
  7986. (mapcar (lambda (y)
  7987. (equal y tpl))
  7988. s))
  7989. x)))
  7990. (reverse r))))))
  7991. (defun org-contextualize-validate-key (key contexts)
  7992. "Check CONTEXTS for agenda or capture KEY."
  7993. (let (res)
  7994. (dolist (r contexts)
  7995. (dolist (rr (car (last r)))
  7996. (when
  7997. (and (equal key (car r))
  7998. (if (functionp rr) (funcall rr)
  7999. (or (and (eq (car rr) 'in-file)
  8000. (buffer-file-name)
  8001. (string-match (cdr rr) (buffer-file-name)))
  8002. (and (eq (car rr) 'in-mode)
  8003. (string-match (cdr rr) (symbol-name major-mode)))
  8004. (and (eq (car rr) 'in-buffer)
  8005. (string-match (cdr rr) (buffer-name)))
  8006. (when (and (eq (car rr) 'not-in-file)
  8007. (buffer-file-name))
  8008. (not (string-match (cdr rr) (buffer-file-name))))
  8009. (when (eq (car rr) 'not-in-mode)
  8010. (not (string-match (cdr rr) (symbol-name major-mode))))
  8011. (when (eq (car rr) 'not-in-buffer)
  8012. (not (string-match (cdr rr) (buffer-name)))))))
  8013. (push r res))))
  8014. (delete-dups (delq nil res))))
  8015. ;; Defined to provide a value for defcustom, since there is no
  8016. ;; string-collate-greaterp in Emacs.
  8017. (defun org-string-collate-greaterp (s1 s2)
  8018. "Return non-nil if S1 is greater than S2 in collation order."
  8019. (not (org-string-collate-lessp s1 s2)))
  8020. ;;;###autoload
  8021. (defun org-run-like-in-org-mode (cmd)
  8022. "Run a command, pretending that the current buffer is in Org mode.
  8023. This will temporarily bind local variables that are typically bound in
  8024. Org mode to the values they have in Org mode, and then interactively
  8025. call CMD."
  8026. (org-load-modules-maybe)
  8027. (let (binds)
  8028. (dolist (var (org-get-local-variables))
  8029. (when (or (not (boundp (car var)))
  8030. (eq (symbol-value (car var))
  8031. (default-value (car var))))
  8032. (push (list (car var) `(quote ,(cadr var))) binds)))
  8033. (eval `(let ,binds
  8034. (call-interactively (quote ,cmd))))))
  8035. (defun org-get-category (&optional pos force-refresh)
  8036. "Get the category applying to position POS."
  8037. (save-match-data
  8038. (when force-refresh (org-refresh-category-properties))
  8039. (let ((pos (or pos (point))))
  8040. (or (get-text-property pos 'org-category)
  8041. (progn (org-refresh-category-properties)
  8042. (get-text-property pos 'org-category))))))
  8043. ;;; Refresh properties
  8044. (defun org-refresh-properties (dprop tprop)
  8045. "Refresh buffer text properties.
  8046. DPROP is the drawer property and TPROP is either the
  8047. corresponding text property to set, or an alist with each element
  8048. being a text property (as a symbol) and a function to apply to
  8049. the value of the drawer property."
  8050. (let* ((case-fold-search t)
  8051. (inhibit-read-only t)
  8052. (inherit? (org-property-inherit-p dprop))
  8053. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8054. (global (and inherit? (org--property-global-value dprop nil))))
  8055. (with-silent-modifications
  8056. (org-with-point-at 1
  8057. ;; Set global values (e.g., values defined through
  8058. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8059. (when global (put-text-property (point-min) (point-max) tprop global))
  8060. ;; Set local values.
  8061. (while (re-search-forward property-re nil t)
  8062. (when (org-at-property-p)
  8063. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8064. (outline-next-heading))))))
  8065. (defun org-refresh-property (tprop p &optional inherit)
  8066. "Refresh the buffer text property TPROP from the drawer property P.
  8067. The refresh happens only for the current headline, or the whole
  8068. sub-tree if optional argument INHERIT is non-nil."
  8069. (unless (org-before-first-heading-p)
  8070. (save-excursion
  8071. (org-back-to-heading t)
  8072. (let ((start (point))
  8073. (end (save-excursion
  8074. (if inherit (org-end-of-subtree t t)
  8075. (or (outline-next-heading) (point-max))))))
  8076. (if (symbolp tprop)
  8077. ;; TPROP is a text property symbol.
  8078. (put-text-property start end tprop p)
  8079. ;; TPROP is an alist with (property . function) elements.
  8080. (pcase-dolist (`(,prop . ,f) tprop)
  8081. (put-text-property start end prop (funcall f p))))))))
  8082. (defun org-refresh-category-properties ()
  8083. "Refresh category text properties in the buffer."
  8084. (let ((case-fold-search t)
  8085. (inhibit-read-only t)
  8086. (default-category
  8087. (cond ((null org-category)
  8088. (if buffer-file-name
  8089. (file-name-sans-extension
  8090. (file-name-nondirectory buffer-file-name))
  8091. "???"))
  8092. ((symbolp org-category) (symbol-name org-category))
  8093. (t org-category))))
  8094. (with-silent-modifications
  8095. (org-with-wide-buffer
  8096. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8097. ;; This is the default category for the buffer. If none is
  8098. ;; found, fall-back to `org-category' or buffer file name.
  8099. (put-text-property
  8100. (point-min) (point-max)
  8101. 'org-category
  8102. (catch 'buffer-category
  8103. (goto-char (point-max))
  8104. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8105. (let ((element (org-element-at-point)))
  8106. (when (eq (org-element-type element) 'keyword)
  8107. (throw 'buffer-category
  8108. (org-element-property :value element)))))
  8109. default-category))
  8110. ;; Set sub-tree specific categories.
  8111. (goto-char (point-min))
  8112. (let ((regexp (org-re-property "CATEGORY")))
  8113. (while (re-search-forward regexp nil t)
  8114. (let ((value (match-string-no-properties 3)))
  8115. (when (org-at-property-p)
  8116. (put-text-property
  8117. (save-excursion (org-back-to-heading t) (point))
  8118. (save-excursion (org-end-of-subtree t t) (point))
  8119. 'org-category
  8120. value)))))))))
  8121. (defun org-refresh-stats-properties ()
  8122. "Refresh stats text properties in the buffer."
  8123. (with-silent-modifications
  8124. (org-with-point-at 1
  8125. (let ((regexp (concat org-outline-regexp-bol
  8126. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8127. (while (re-search-forward regexp nil t)
  8128. (let* ((numerator (string-to-number (match-string 1)))
  8129. (denominator (and (match-end 2)
  8130. (string-to-number (match-string 2))))
  8131. (stats (cond ((not denominator) numerator) ;percent
  8132. ((= denominator 0) 0)
  8133. (t (/ (* numerator 100) denominator)))))
  8134. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8135. 'org-stats stats)))))))
  8136. (defun org-refresh-effort-properties ()
  8137. "Refresh effort properties"
  8138. (org-refresh-properties
  8139. org-effort-property
  8140. '((effort . identity)
  8141. (effort-minutes . org-duration-to-minutes))))
  8142. ;;;; Link Stuff
  8143. ;;; Link abbreviations
  8144. (defun org-link-expand-abbrev (link)
  8145. "Apply replacements as defined in `org-link-abbrev-alist'."
  8146. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8147. (let* ((key (match-string 1 link))
  8148. (as (or (assoc key org-link-abbrev-alist-local)
  8149. (assoc key org-link-abbrev-alist)))
  8150. (tag (and (match-end 2) (match-string 3 link)))
  8151. rpl)
  8152. (if (not as)
  8153. link
  8154. (setq rpl (cdr as))
  8155. (cond
  8156. ((symbolp rpl) (funcall rpl tag))
  8157. ((string-match "%(\\([^)]+\\))" rpl)
  8158. (replace-match
  8159. (save-match-data
  8160. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8161. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8162. ((string-match "%h" rpl)
  8163. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8164. (t (concat rpl tag)))))
  8165. link))
  8166. ;;; Storing and inserting links
  8167. (defvar org-insert-link-history nil
  8168. "Minibuffer history for links inserted with `org-insert-link'.")
  8169. (defvar org-stored-links nil
  8170. "Contains the links stored with `org-store-link'.")
  8171. (defvar org-store-link-plist nil
  8172. "Plist with info about the most recently link created with `org-store-link'.")
  8173. (defun org-store-link-functions ()
  8174. "Return a list of functions that are called to create and store a link.
  8175. The functions defined in the :store property of
  8176. `org-link-parameters'.
  8177. Each function will be called in turn until one returns a non-nil
  8178. value. Each function should check if it is responsible for
  8179. creating this link (for example by looking at the major mode).
  8180. If not, it must exit and return nil. If yes, it should return
  8181. a non-nil value after calling `org-store-link-props' with a list
  8182. of properties and values. Special properties are:
  8183. :type The link prefix, like \"http\". This must be given.
  8184. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8185. This is obligatory as well.
  8186. :description Optional default description for the second pair
  8187. of brackets in an Org mode link. The user can still change
  8188. this when inserting this link into an Org mode buffer.
  8189. In addition to these, any additional properties can be specified
  8190. and then used in capture templates."
  8191. (cl-loop for link in org-link-parameters
  8192. with store-func
  8193. do (setq store-func (org-link-get-parameter (car link) :store))
  8194. if store-func
  8195. collect store-func))
  8196. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8197. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8198. ;;;###autoload
  8199. (defun org-store-link (arg &optional interactive?)
  8200. "Store a link to the current location.
  8201. \\<org-mode-map>
  8202. This link is added to `org-stored-links' and can later be inserted
  8203. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8204. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8205. A single
  8206. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8207. `org-gnus-prefer-web-links' for links to Usenet articles.
  8208. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8209. skipping storing functions that are not
  8210. part of Org core.
  8211. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8212. prefix ARG forces storing a link for each line in the
  8213. active region.
  8214. Assume the function is called interactively if INTERACTIVE? is
  8215. non-nil."
  8216. (interactive "P\np")
  8217. (org-load-modules-maybe)
  8218. (if (and (equal arg '(64)) (org-region-active-p))
  8219. (save-excursion
  8220. (let ((end (region-end)))
  8221. (goto-char (region-beginning))
  8222. (set-mark (point))
  8223. (while (< (point-at-eol) end)
  8224. (move-end-of-line 1) (activate-mark)
  8225. (let (current-prefix-arg)
  8226. (call-interactively 'org-store-link))
  8227. (move-beginning-of-line 2)
  8228. (set-mark (point)))))
  8229. (setq org-store-link-plist nil)
  8230. (let (link cpltxt desc description search txt custom-id agenda-link)
  8231. (cond
  8232. ;; Store a link using an external link type, if any function is
  8233. ;; available. If more than one can generate a link from current
  8234. ;; location, ask which one to use.
  8235. ((and (not (equal arg '(16)))
  8236. (let ((results-alist nil))
  8237. (dolist (f (org-store-link-functions))
  8238. (when (funcall f)
  8239. ;; XXX: return value is not link's plist, so we
  8240. ;; store the new value before it is modified. It
  8241. ;; would be cleaner to ask store link functions to
  8242. ;; return the plist instead.
  8243. (push (cons f (copy-sequence org-store-link-plist))
  8244. results-alist)))
  8245. (pcase results-alist
  8246. (`nil nil)
  8247. (`((,_ . ,_)) t) ;single choice: nothing to do
  8248. (`((,name . ,_) . ,_)
  8249. ;; Reinstate link plist associated to the chosen
  8250. ;; function.
  8251. (apply #'org-store-link-props
  8252. (cdr (assoc-string
  8253. (completing-read
  8254. "Which function for creating the link? "
  8255. (mapcar #'car results-alist)
  8256. nil t (symbol-name name))
  8257. results-alist)))
  8258. t))))
  8259. (setq link (plist-get org-store-link-plist :link))
  8260. (setq desc (or (plist-get org-store-link-plist :description)
  8261. link)))
  8262. ;; Store a link from a source code buffer.
  8263. ((org-src-edit-buffer-p)
  8264. (let ((coderef-format (org-src-coderef-format)))
  8265. (cond ((org-match-line (org-src-coderef-regexp coderef-format))
  8266. (setq link (format "(%s)" (match-string-no-properties 3))))
  8267. (interactive?
  8268. (let ((label (read-string "Code line label: ")))
  8269. (end-of-line)
  8270. (setq link (format coderef-format label))
  8271. (let ((gc (- 79 (length link))))
  8272. (if (< (current-column) gc)
  8273. (org-move-to-column gc t)
  8274. (insert " ")))
  8275. (insert link)
  8276. (setq link (concat "(" label ")"))
  8277. (setq desc nil)))
  8278. (t (setq link nil)))))
  8279. ;; We are in the agenda, link to referenced location
  8280. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8281. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8282. (get-text-property (point) 'org-marker))))
  8283. (when m
  8284. (org-with-point-at m
  8285. (setq agenda-link (org-store-link nil interactive?))))))
  8286. ((eq major-mode 'calendar-mode)
  8287. (let ((cd (calendar-cursor-to-date)))
  8288. (setq link
  8289. (format-time-string
  8290. (car org-time-stamp-formats)
  8291. (apply 'encode-time
  8292. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8293. nil nil nil))))
  8294. (org-store-link-props :type "calendar" :date cd)))
  8295. ((eq major-mode 'help-mode)
  8296. (setq link (concat "help:" (save-excursion
  8297. (goto-char (point-min))
  8298. (looking-at "^[^ ]+")
  8299. (match-string 0))))
  8300. (org-store-link-props :type "help"))
  8301. ((eq major-mode 'w3-mode)
  8302. (setq cpltxt (if (and (buffer-name)
  8303. (not (string-match "Untitled" (buffer-name))))
  8304. (buffer-name)
  8305. (url-view-url t))
  8306. link (url-view-url t))
  8307. (org-store-link-props :type "w3" :url (url-view-url t)))
  8308. ((eq major-mode 'image-mode)
  8309. (setq cpltxt (concat "file:"
  8310. (abbreviate-file-name buffer-file-name))
  8311. link cpltxt)
  8312. (org-store-link-props :type "image" :file buffer-file-name))
  8313. ;; In dired, store a link to the file of the current line
  8314. ((derived-mode-p 'dired-mode)
  8315. (let ((file (dired-get-filename nil t)))
  8316. (setq file (if file
  8317. (abbreviate-file-name
  8318. (expand-file-name (dired-get-filename nil t)))
  8319. ;; otherwise, no file so use current directory.
  8320. default-directory))
  8321. (setq cpltxt (concat "file:" file)
  8322. link cpltxt)))
  8323. ((setq search (run-hook-with-args-until-success
  8324. 'org-create-file-search-functions))
  8325. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8326. "::" search))
  8327. (setq cpltxt (or description link)))
  8328. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8329. (org-with-limited-levels
  8330. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8331. (cond
  8332. ;; Store a link using the target at point
  8333. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8334. (setq cpltxt
  8335. (concat "file:"
  8336. (abbreviate-file-name
  8337. (buffer-file-name (buffer-base-buffer)))
  8338. "::" (match-string 1))
  8339. link cpltxt))
  8340. ((and (featurep 'org-id)
  8341. (or (eq org-id-link-to-org-use-id t)
  8342. (and interactive?
  8343. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8344. (and (eq org-id-link-to-org-use-id
  8345. 'create-if-interactive-and-no-custom-id)
  8346. (not custom-id))))
  8347. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8348. ;; Store a link using the ID at point
  8349. (setq link (condition-case nil
  8350. (prog1 (org-id-store-link)
  8351. (setq desc (or (plist-get org-store-link-plist
  8352. :description)
  8353. "")))
  8354. (error
  8355. ;; Probably before first headline, link only to file
  8356. (concat "file:"
  8357. (abbreviate-file-name
  8358. (buffer-file-name (buffer-base-buffer))))))))
  8359. (t
  8360. ;; Just link to current headline
  8361. (setq cpltxt (concat "file:"
  8362. (abbreviate-file-name
  8363. (buffer-file-name (buffer-base-buffer)))))
  8364. ;; Add a context search string
  8365. (when (org-xor org-context-in-file-links
  8366. (equal arg '(4)))
  8367. (let* ((element (org-element-at-point))
  8368. (name (org-element-property :name element)))
  8369. (setq txt (cond
  8370. ((org-at-heading-p) nil)
  8371. (name)
  8372. ((org-region-active-p)
  8373. (buffer-substring (region-beginning) (region-end)))))
  8374. (when (or (null txt) (string-match "\\S-" txt))
  8375. (setq cpltxt
  8376. (concat cpltxt "::"
  8377. (condition-case nil
  8378. (org-make-org-heading-search-string txt)
  8379. (error "")))
  8380. desc (or name
  8381. (nth 4 (ignore-errors (org-heading-components)))
  8382. "NONE")))))
  8383. (when (string-match "::\\'" cpltxt)
  8384. (setq cpltxt (substring cpltxt 0 -2)))
  8385. (setq link cpltxt)))))
  8386. ((buffer-file-name (buffer-base-buffer))
  8387. ;; Just link to this file here.
  8388. (setq cpltxt (concat "file:"
  8389. (abbreviate-file-name
  8390. (buffer-file-name (buffer-base-buffer)))))
  8391. ;; Add a context string.
  8392. (when (org-xor org-context-in-file-links
  8393. (equal arg '(4)))
  8394. (setq txt (if (org-region-active-p)
  8395. (buffer-substring (region-beginning) (region-end))
  8396. (buffer-substring (point-at-bol) (point-at-eol))))
  8397. ;; Only use search option if there is some text.
  8398. (when (string-match "\\S-" txt)
  8399. (setq cpltxt
  8400. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8401. desc "NONE")))
  8402. (setq link cpltxt))
  8403. (interactive?
  8404. (user-error "No method for storing a link from this buffer"))
  8405. (t (setq link nil)))
  8406. ;; We're done setting link and desc, clean up
  8407. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8408. (setq link (or link cpltxt)
  8409. desc (or desc cpltxt))
  8410. (cond ((not desc))
  8411. ((equal desc "NONE") (setq desc nil))
  8412. (t (setq desc
  8413. (replace-regexp-in-string
  8414. org-bracket-link-analytic-regexp
  8415. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8416. desc))))
  8417. ;; Return the link
  8418. (if (not (and interactive? link))
  8419. (or agenda-link (and link (org-make-link-string link desc)))
  8420. (push (list link desc) org-stored-links)
  8421. (message "Stored: %s" (or desc link))
  8422. (when custom-id
  8423. (setq link (concat "file:" (abbreviate-file-name
  8424. (buffer-file-name)) "::#" custom-id))
  8425. (push (list link desc) org-stored-links))
  8426. (car org-stored-links)))))
  8427. (defun org-store-link-props (&rest plist)
  8428. "Store link properties.
  8429. The properties are pre-processed by extracting names, addresses
  8430. and dates."
  8431. (let ((x (plist-get plist :from)))
  8432. (when x
  8433. (let ((adr (mail-extract-address-components x)))
  8434. (setq plist (plist-put plist :fromname (car adr)))
  8435. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8436. (let ((x (plist-get plist :to)))
  8437. (when x
  8438. (let ((adr (mail-extract-address-components x)))
  8439. (setq plist (plist-put plist :toname (car adr)))
  8440. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8441. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8442. (when x
  8443. (setq plist (plist-put plist :date-timestamp
  8444. (format-time-string
  8445. (org-time-stamp-format t) x)))
  8446. (setq plist (plist-put plist :date-timestamp-inactive
  8447. (format-time-string
  8448. (org-time-stamp-format t t) x)))))
  8449. (let ((from (plist-get plist :from))
  8450. (to (plist-get plist :to)))
  8451. (when (and from to org-from-is-user-regexp)
  8452. (setq plist
  8453. (plist-put plist :fromto
  8454. (if (string-match org-from-is-user-regexp from)
  8455. (concat "to %t")
  8456. (concat "from %f"))))))
  8457. (setq org-store-link-plist plist))
  8458. (defun org-add-link-props (&rest plist)
  8459. "Add these properties to the link property list."
  8460. (let (key value)
  8461. (while plist
  8462. (setq key (pop plist) value (pop plist))
  8463. (setq org-store-link-plist
  8464. (plist-put org-store-link-plist key value)))))
  8465. (defun org-email-link-description (&optional fmt)
  8466. "Return the description part of an email link.
  8467. This takes information from `org-store-link-plist' and formats it
  8468. according to FMT (default from `org-email-link-description-format')."
  8469. (setq fmt (or fmt org-email-link-description-format))
  8470. (let* ((p org-store-link-plist)
  8471. (to (plist-get p :toaddress))
  8472. (from (plist-get p :fromaddress))
  8473. (table
  8474. (list
  8475. (cons "%c" (plist-get p :fromto))
  8476. (cons "%F" (plist-get p :from))
  8477. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8478. (cons "%T" (plist-get p :to))
  8479. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8480. (cons "%s" (plist-get p :subject))
  8481. (cons "%d" (plist-get p :date))
  8482. (cons "%m" (plist-get p :message-id)))))
  8483. (when (string-match "%c" fmt)
  8484. ;; Check if the user wrote this message
  8485. (if (and org-from-is-user-regexp from to
  8486. (save-match-data (string-match org-from-is-user-regexp from)))
  8487. (setq fmt (replace-match "to %t" t t fmt))
  8488. (setq fmt (replace-match "from %f" t t fmt))))
  8489. (org-replace-escapes fmt table)))
  8490. (defun org-make-org-heading-search-string (&optional string)
  8491. "Make search string for the current headline or STRING."
  8492. (let ((s (or string
  8493. (and (derived-mode-p 'org-mode)
  8494. (save-excursion
  8495. (org-back-to-heading t)
  8496. (org-element-property :raw-value (org-element-at-point))))))
  8497. (lines org-context-in-file-links))
  8498. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8499. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8500. (when (and string (integerp lines) (> lines 0))
  8501. (let ((slines (org-split-string s "\n")))
  8502. (when (< lines (length slines))
  8503. (setq s (mapconcat
  8504. 'identity
  8505. (reverse (nthcdr (- (length slines) lines)
  8506. (reverse slines))) "\n")))))
  8507. (mapconcat #'identity (split-string s) " ")))
  8508. (defconst org-link-escape-chars
  8509. ;;%20 %5B %5D %25
  8510. '(?\s ?\[ ?\] ?%)
  8511. "List of characters that should be escaped in a link when stored to Org.
  8512. This is the list that is used for internal purposes.")
  8513. (defun org-make-link-string (link &optional description)
  8514. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8515. (unless (org-string-nw-p link) (error "Empty link"))
  8516. (let ((uri (cond ((string-match org-link-types-re link)
  8517. (concat (match-string 1 link)
  8518. (org-link-escape (substring link (match-end 1)))))
  8519. ((or (file-name-absolute-p link)
  8520. (string-match-p "\\`\\.\\.?/" link))
  8521. (org-link-escape link))
  8522. ;; For readability, do not encode space characters
  8523. ;; in fuzzy links.
  8524. (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
  8525. (description
  8526. (and (org-string-nw-p description)
  8527. ;; Remove brackets from description, as they are fatal.
  8528. (replace-regexp-in-string
  8529. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8530. (org-trim description)))))
  8531. (format "[[%s]%s]"
  8532. uri
  8533. (if description (format "[%s]" description) ""))))
  8534. (defun org-link-escape (text &optional table merge)
  8535. "Return percent escaped representation of TEXT.
  8536. TEXT is a string with the text to escape.
  8537. Optional argument TABLE is a list with characters that should be
  8538. escaped. When nil, `org-link-escape-chars' is used.
  8539. If optional argument MERGE is set, merge TABLE into
  8540. `org-link-escape-chars'."
  8541. (let ((characters-to-encode
  8542. (cond ((null table) org-link-escape-chars)
  8543. (merge (append org-link-escape-chars table))
  8544. (t table))))
  8545. (mapconcat
  8546. (lambda (c)
  8547. (if (or (memq c characters-to-encode)
  8548. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8549. (mapconcat (lambda (e) (format "%%%.2X" e))
  8550. (or (encode-coding-char c 'utf-8)
  8551. (error "Unable to percent escape character: %c" c))
  8552. "")
  8553. (char-to-string c)))
  8554. text "")))
  8555. (defun org-link-unescape (str)
  8556. "Unhex hexified Unicode parts in string STR.
  8557. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8558. reciprocal of `org-link-escape', which see."
  8559. (if (org-string-nw-p str)
  8560. (replace-regexp-in-string
  8561. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8562. str))
  8563. (defun org-link-unescape-compound (hex)
  8564. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8565. Note: this function also decodes single byte encodings like
  8566. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8567. (save-match-data
  8568. (let* ((bytes (cdr (split-string hex "%")))
  8569. (ret "")
  8570. (eat 0)
  8571. (sum 0))
  8572. (while bytes
  8573. (let* ((val (string-to-number (pop bytes) 16))
  8574. (shift-xor
  8575. (if (= 0 eat)
  8576. (cond
  8577. ((>= val 252) (cons 6 252))
  8578. ((>= val 248) (cons 5 248))
  8579. ((>= val 240) (cons 4 240))
  8580. ((>= val 224) (cons 3 224))
  8581. ((>= val 192) (cons 2 192))
  8582. (t (cons 0 0)))
  8583. (cons 6 128))))
  8584. (when (>= val 192) (setq eat (car shift-xor)))
  8585. (setq val (logxor val (cdr shift-xor)))
  8586. (setq sum (+ (lsh sum (car shift-xor)) val))
  8587. (when (> eat 0) (setq eat (- eat 1)))
  8588. (cond
  8589. ((= 0 eat) ;multi byte
  8590. (setq ret (concat ret (char-to-string sum)))
  8591. (setq sum 0))
  8592. ((not bytes) ; single byte(s)
  8593. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8594. ret)))
  8595. (defun org-link-unescape-single-byte-sequence (hex)
  8596. "Unhexify hex-encoded single byte character sequences."
  8597. (mapconcat (lambda (byte)
  8598. (char-to-string (string-to-number byte 16)))
  8599. (cdr (split-string hex "%")) ""))
  8600. (defun org-fixup-message-id-for-http (s)
  8601. "Replace special characters in a message id, so it can be used in an http query."
  8602. (when (string-match "%" s)
  8603. (setq s (mapconcat (lambda (c)
  8604. (if (eq c ?%)
  8605. "%25"
  8606. (char-to-string c)))
  8607. s "")))
  8608. (while (string-match "<" s)
  8609. (setq s (replace-match "%3C" t t s)))
  8610. (while (string-match ">" s)
  8611. (setq s (replace-match "%3E" t t s)))
  8612. (while (string-match "@" s)
  8613. (setq s (replace-match "%40" t t s)))
  8614. s)
  8615. (defun org-link-prettify (link)
  8616. "Return a human-readable representation of LINK.
  8617. The car of LINK must be a raw link.
  8618. The cdr of LINK must be either a link description or nil."
  8619. (let ((desc (or (cadr link) "<no description>")))
  8620. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  8621. "<" (car link) ">")))
  8622. ;;;###autoload
  8623. (defun org-insert-link-global ()
  8624. "Insert a link like Org mode does.
  8625. This command can be called in any mode to insert a link in Org syntax."
  8626. (interactive)
  8627. (org-load-modules-maybe)
  8628. (org-run-like-in-org-mode 'org-insert-link))
  8629. (defun org-insert-all-links (arg &optional pre post)
  8630. "Insert all links in `org-stored-links'.
  8631. When a universal prefix, do not delete the links from `org-stored-links'.
  8632. When `ARG' is a number, insert the last N link(s).
  8633. `PRE' and `POST' are optional arguments to define a string to
  8634. prepend or to append."
  8635. (interactive "P")
  8636. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  8637. (links (copy-sequence org-stored-links))
  8638. (pr (or pre "- "))
  8639. (po (or post "\n"))
  8640. (cnt 1) l)
  8641. (if (null org-stored-links)
  8642. (message "No link to insert")
  8643. (while (and (or (listp arg) (>= arg cnt))
  8644. (setq l (if (listp arg)
  8645. (pop links)
  8646. (pop org-stored-links))))
  8647. (setq cnt (1+ cnt))
  8648. (insert pr)
  8649. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  8650. (insert po)))))
  8651. (defun org-insert-last-stored-link (arg)
  8652. "Insert the last link stored in `org-stored-links'."
  8653. (interactive "p")
  8654. (org-insert-all-links arg "" "\n"))
  8655. (defun org-link-fontify-links-to-this-file ()
  8656. "Fontify links to the current file in `org-stored-links'."
  8657. (let ((f (buffer-file-name)) a b)
  8658. (setq a (mapcar (lambda(l)
  8659. (let ((ll (car l)))
  8660. (when (and (string-match "^file:\\(.+\\)::" ll)
  8661. (equal f (expand-file-name (match-string 1 ll))))
  8662. ll)))
  8663. org-stored-links))
  8664. (when (featurep 'org-id)
  8665. (setq b (mapcar (lambda(l)
  8666. (let ((ll (car l)))
  8667. (when (and (string-match "^id:\\(.+\\)$" ll)
  8668. (equal f (expand-file-name
  8669. (or (org-id-find-id-file
  8670. (match-string 1 ll)) ""))))
  8671. ll)))
  8672. org-stored-links)))
  8673. (mapcar (lambda(l)
  8674. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  8675. (delq nil (append a b)))))
  8676. (defvar org--links-history nil)
  8677. (defun org-insert-link (&optional complete-file link-location default-description)
  8678. "Insert a link. At the prompt, enter the link.
  8679. Completion can be used to insert any of the link protocol prefixes in use.
  8680. The history can be used to select a link previously stored with
  8681. `org-store-link'. When the empty string is entered (i.e. if you just
  8682. press `RET' at the prompt), the link defaults to the most recently
  8683. stored link. As `SPC' triggers completion in the minibuffer, you need to
  8684. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  8685. You will also be prompted for a description, and if one is given, it will
  8686. be displayed in the buffer instead of the link.
  8687. If there is already a link at point, this command will allow you to edit
  8688. link and description parts.
  8689. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  8690. file name can be
  8691. selected using completion. The path to the file will be relative to the
  8692. current directory if the file is in the current directory or a subdirectory.
  8693. Otherwise, the link will be the absolute path as completed in the minibuffer
  8694. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  8695. option `org-link-file-path-type'.
  8696. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  8697. absolute path even if the file is in
  8698. the current directory or below.
  8699. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8700. prefix negates `org-keep-stored-link-after-insertion'.
  8701. If the LINK-LOCATION parameter is non-nil, this value will be used as
  8702. the link location instead of reading one interactively.
  8703. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  8704. be used as the default description. Otherwise, if
  8705. `org-make-link-description-function' is non-nil, this function
  8706. will be called with the link target, and the result will be the
  8707. default link description. When called non-interactivily, don't
  8708. allow to edit the default description."
  8709. (interactive "P")
  8710. (let* ((wcf (current-window-configuration))
  8711. (origbuf (current-buffer))
  8712. (region (when (org-region-active-p)
  8713. (buffer-substring (region-beginning) (region-end))))
  8714. (remove (and region (list (region-beginning) (region-end))))
  8715. (desc region)
  8716. (link link-location)
  8717. (abbrevs org-link-abbrev-alist-local)
  8718. entry all-prefixes auto-desc)
  8719. (cond
  8720. (link-location) ; specified by arg, just use it.
  8721. ((org-in-regexp org-bracket-link-regexp 1)
  8722. ;; We do have a link at point, and we are going to edit it.
  8723. (setq remove (list (match-beginning 0) (match-end 0)))
  8724. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  8725. (setq link (read-string "Link: "
  8726. (org-link-unescape
  8727. (match-string-no-properties 1)))))
  8728. ((or (org-in-regexp org-angle-link-re)
  8729. (org-in-regexp org-plain-link-re))
  8730. ;; Convert to bracket link
  8731. (setq remove (list (match-beginning 0) (match-end 0))
  8732. link (read-string "Link: "
  8733. (org-unbracket-string "<" ">" (match-string 0)))))
  8734. ((member complete-file '((4) (16)))
  8735. ;; Completing read for file names.
  8736. (setq link (org-file-complete-link complete-file)))
  8737. (t
  8738. ;; Read link, with completion for stored links.
  8739. (org-link-fontify-links-to-this-file)
  8740. (org-switch-to-buffer-other-window "*Org Links*")
  8741. (with-current-buffer "*Org Links*"
  8742. (erase-buffer)
  8743. (insert "Insert a link.
  8744. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  8745. (when org-stored-links
  8746. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  8747. (insert (mapconcat 'org-link-prettify
  8748. (reverse org-stored-links) "\n")))
  8749. (goto-char (point-min)))
  8750. (let ((cw (selected-window)))
  8751. (select-window (get-buffer-window "*Org Links*" 'visible))
  8752. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  8753. (unless (pos-visible-in-window-p (point-max))
  8754. (org-fit-window-to-buffer))
  8755. (and (window-live-p cw) (select-window cw)))
  8756. (setq all-prefixes (append (mapcar 'car abbrevs)
  8757. (mapcar 'car org-link-abbrev-alist)
  8758. (org-link-types)))
  8759. (unwind-protect
  8760. ;; Fake a link history, containing the stored links.
  8761. (let ((org--links-history
  8762. (append (mapcar #'car org-stored-links)
  8763. org-insert-link-history)))
  8764. (setq link
  8765. (org-completing-read
  8766. "Link: "
  8767. (append
  8768. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  8769. (mapcar #'car org-stored-links))
  8770. nil nil nil
  8771. 'org--links-history
  8772. (caar org-stored-links)))
  8773. (unless (org-string-nw-p link) (user-error "No link selected"))
  8774. (dolist (l org-stored-links)
  8775. (when (equal link (cadr l))
  8776. (setq link (car l))
  8777. (setq auto-desc t)))
  8778. (when (or (member link all-prefixes)
  8779. (and (equal ":" (substring link -1))
  8780. (member (substring link 0 -1) all-prefixes)
  8781. (setq link (substring link 0 -1))))
  8782. (setq link (with-current-buffer origbuf
  8783. (org-link-try-special-completion link)))))
  8784. (set-window-configuration wcf)
  8785. (kill-buffer "*Org Links*"))
  8786. (setq entry (assoc link org-stored-links))
  8787. (or entry (push link org-insert-link-history))
  8788. (setq desc (or desc (nth 1 entry)))))
  8789. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  8790. (not org-keep-stored-link-after-insertion))
  8791. (setq org-stored-links (delq (assoc link org-stored-links)
  8792. org-stored-links)))
  8793. (when (and (string-match org-plain-link-re link)
  8794. (not (string-match org-ts-regexp link)))
  8795. ;; URL-like link, normalize the use of angular brackets.
  8796. (setq link (org-unbracket-string "<" ">" link)))
  8797. ;; Check if we are linking to the current file with a search
  8798. ;; option If yes, simplify the link by using only the search
  8799. ;; option.
  8800. (when (and buffer-file-name
  8801. (let ((case-fold-search nil))
  8802. (string-match "\\`file:\\(.+?\\)::" link)))
  8803. (let ((path (match-string-no-properties 1 link))
  8804. (search (substring-no-properties link (match-end 0))))
  8805. (save-match-data
  8806. (when (equal (file-truename buffer-file-name) (file-truename path))
  8807. ;; We are linking to this same file, with a search option
  8808. (setq link search)))))
  8809. ;; Check if we can/should use a relative path. If yes, simplify
  8810. ;; the link.
  8811. (let ((case-fold-search nil))
  8812. (when (string-match "\\`\\(file\\|docview\\):" link)
  8813. (let* ((type (match-string-no-properties 0 link))
  8814. (path-start (match-end 0))
  8815. (search (and (string-match "::\\(.*\\)\\'" link)
  8816. (match-string 1 link)))
  8817. (path
  8818. (if search
  8819. (substring-no-properties
  8820. link path-start (match-beginning 0))
  8821. (substring-no-properties link (match-end 0))))
  8822. (origpath path))
  8823. (cond
  8824. ((or (eq org-link-file-path-type 'absolute)
  8825. (equal complete-file '(16)))
  8826. (setq path (abbreviate-file-name (expand-file-name path))))
  8827. ((eq org-link-file-path-type 'noabbrev)
  8828. (setq path (expand-file-name path)))
  8829. ((eq org-link-file-path-type 'relative)
  8830. (setq path (file-relative-name path)))
  8831. (t
  8832. (save-match-data
  8833. (if (string-match (concat "^" (regexp-quote
  8834. (expand-file-name
  8835. (file-name-as-directory
  8836. default-directory))))
  8837. (expand-file-name path))
  8838. ;; We are linking a file with relative path name.
  8839. (setq path (substring (expand-file-name path)
  8840. (match-end 0)))
  8841. (setq path (abbreviate-file-name (expand-file-name path)))))))
  8842. (setq link (concat type path (and search (concat "::" search))))
  8843. (when (equal desc origpath)
  8844. (setq desc path)))))
  8845. (unless auto-desc
  8846. (let ((initial-input
  8847. (cond
  8848. (default-description)
  8849. ((not org-make-link-description-function) desc)
  8850. (t (condition-case nil
  8851. (funcall org-make-link-description-function link desc)
  8852. (error
  8853. (message "Can't get link description from `%s'"
  8854. (symbol-name org-make-link-description-function))
  8855. (sit-for 2)
  8856. nil))))))
  8857. (setq desc (if (called-interactively-p 'any)
  8858. (read-string "Description: " initial-input)
  8859. initial-input))))
  8860. (unless (string-match "\\S-" desc) (setq desc nil))
  8861. (when remove (apply 'delete-region remove))
  8862. (insert (org-make-link-string link desc))
  8863. ;; Redisplay so as the new link has proper invisible characters.
  8864. (sit-for 0)))
  8865. (defun org-link-try-special-completion (type)
  8866. "If there is completion support for link type TYPE, offer it."
  8867. (let ((fun (org-link-get-parameter type :complete)))
  8868. (if (functionp fun)
  8869. (funcall fun)
  8870. (read-string "Link (no completion support): " (concat type ":")))))
  8871. (defun org-file-complete-link (&optional arg)
  8872. "Create a file link using completion."
  8873. (let ((file (read-file-name "File: "))
  8874. (pwd (file-name-as-directory (expand-file-name ".")))
  8875. (pwd1 (file-name-as-directory (abbreviate-file-name
  8876. (expand-file-name ".")))))
  8877. (cond ((equal arg '(16))
  8878. (concat "file:"
  8879. (abbreviate-file-name (expand-file-name file))))
  8880. ((string-match
  8881. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  8882. (concat "file:" (match-string 1 file)))
  8883. ((string-match
  8884. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  8885. (expand-file-name file))
  8886. (concat "file:"
  8887. (match-string 1 (expand-file-name file))))
  8888. (t (concat "file:" file)))))
  8889. ;;; Opening/following a link
  8890. (defvar org-link-search-failed nil)
  8891. (defvar org-open-link-functions nil
  8892. "Hook for functions finding a plain text link.
  8893. These functions must take a single argument, the link content.
  8894. They will be called for links that look like [[link text][description]]
  8895. when LINK TEXT does not have a protocol like \"http:\" and does not look
  8896. like a filename (e.g. \"./blue.png\").
  8897. These functions will be called *before* Org attempts to resolve the
  8898. link by doing text searches in the current buffer - so if you want a
  8899. link \"[[target]]\" to still find \"<<target>>\", your function should
  8900. handle this as a special case.
  8901. When the function does handle the link, it must return a non-nil value.
  8902. If it decides that it is not responsible for this link, it must return
  8903. nil to indicate that that Org can continue with other options like
  8904. exact and fuzzy text search.")
  8905. (defun org-next-link (&optional search-backward)
  8906. "Move forward to the next link.
  8907. If the link is in hidden text, expose it."
  8908. (interactive "P")
  8909. (when (and org-link-search-failed (eq this-command last-command))
  8910. (goto-char (point-min))
  8911. (message "Link search wrapped back to beginning of buffer"))
  8912. (setq org-link-search-failed nil)
  8913. (let* ((pos (point))
  8914. (ct (org-context))
  8915. (a (assq :link ct))
  8916. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  8917. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  8918. ((looking-at org-any-link-re)
  8919. ;; Don't stay stuck at link without an org-link face
  8920. (forward-char (if search-backward -1 1))))
  8921. (if (funcall srch-fun org-any-link-re nil t)
  8922. (progn
  8923. (goto-char (match-beginning 0))
  8924. (when (org-invisible-p) (org-show-context)))
  8925. (goto-char pos)
  8926. (setq org-link-search-failed t)
  8927. (message "No further link found"))))
  8928. (defun org-previous-link ()
  8929. "Move backward to the previous link.
  8930. If the link is in hidden text, expose it."
  8931. (interactive)
  8932. (org-next-link t))
  8933. (defun org-translate-link (s)
  8934. "Translate a link string if a translation function has been defined."
  8935. (with-temp-buffer
  8936. (insert (org-trim s))
  8937. (org-trim (org-element-interpret-data (org-element-context)))))
  8938. (defun org-translate-link-from-planner (type path)
  8939. "Translate a link from Emacs Planner syntax so that Org can follow it.
  8940. This is still an experimental function, your mileage may vary."
  8941. (cond
  8942. ((member type '("http" "https" "news" "ftp"))
  8943. ;; standard Internet links are the same.
  8944. nil)
  8945. ((and (equal type "irc") (string-match "^//" path))
  8946. ;; Planner has two / at the beginning of an irc link, we have 1.
  8947. ;; We should have zero, actually....
  8948. (setq path (substring path 1)))
  8949. ((and (equal type "lisp") (string-match "^/" path))
  8950. ;; Planner has a slash, we do not.
  8951. (setq type "elisp" path (substring path 1)))
  8952. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  8953. ;; A typical message link. Planner has the id after the final slash,
  8954. ;; we separate it with a hash mark
  8955. (setq path (concat (match-string 1 path) "#"
  8956. (org-unbracket-string "<" ">" (match-string 2 path))))))
  8957. (cons type path))
  8958. (defun org-find-file-at-mouse (ev)
  8959. "Open file link or URL at mouse."
  8960. (interactive "e")
  8961. (mouse-set-point ev)
  8962. (org-open-at-point 'in-emacs))
  8963. (defun org-open-at-mouse (ev)
  8964. "Open file link or URL at mouse.
  8965. See the docstring of `org-open-file' for details."
  8966. (interactive "e")
  8967. (mouse-set-point ev)
  8968. (when (eq major-mode 'org-agenda-mode)
  8969. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  8970. (org-open-at-point))
  8971. (defvar org-window-config-before-follow-link nil
  8972. "The window configuration before following a link.
  8973. This is saved in case the need arises to restore it.")
  8974. ;;;###autoload
  8975. (defun org-open-at-point-global ()
  8976. "Follow a link or a time-stamp like Org mode does.
  8977. Also follow links and emails as seen by `thing-at-point'.
  8978. This command can be called in any mode to follow an external
  8979. link or a time-stamp that has Org mode syntax. Its behavior
  8980. is undefined when called on internal links like fuzzy links.
  8981. Raise a user error when there is nothing to follow."
  8982. (interactive)
  8983. (let ((tap-url (thing-at-point 'url))
  8984. (tap-email (thing-at-point 'email)))
  8985. (cond ((org-in-regexp org-any-link-re)
  8986. (org-open-link-from-string (match-string-no-properties 0)))
  8987. ((or (org-in-regexp org-ts-regexp-both nil t)
  8988. (org-in-regexp org-tsr-regexp-both nil t))
  8989. (org-follow-timestamp-link))
  8990. (tap-url (org-open-link-from-string tap-url))
  8991. (tap-email (org-open-link-from-string
  8992. (concat "mailto:" tap-email)))
  8993. (t (user-error "No link found")))))
  8994. ;;;###autoload
  8995. (defun org-open-link-from-string (s &optional arg reference-buffer)
  8996. "Open a link in the string S, as if it was in Org mode."
  8997. (interactive "sLink: \nP")
  8998. (let ((reference-buffer (or reference-buffer (current-buffer))))
  8999. (with-temp-buffer
  9000. (let ((org-inhibit-startup (not reference-buffer)))
  9001. (org-mode)
  9002. (insert s)
  9003. (goto-char (point-min))
  9004. (when reference-buffer
  9005. (setq org-link-abbrev-alist-local
  9006. (with-current-buffer reference-buffer
  9007. org-link-abbrev-alist-local)))
  9008. (org-open-at-point arg reference-buffer)))))
  9009. (defvar org-open-at-point-functions nil
  9010. "Hook that is run when following a link at point.
  9011. Functions in this hook must return t if they identify and follow
  9012. a link at point. If they don't find anything interesting at point,
  9013. they must return nil.")
  9014. (defvar org-link-search-inhibit-query nil)
  9015. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9016. (defun org--open-doi-link (path)
  9017. "Open a \"doi\" type link.
  9018. PATH is a the path to search for, as a string."
  9019. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9020. (defun org--open-elisp-link (path)
  9021. "Open a \"elisp\" type link.
  9022. PATH is the sexp to evaluate, as a string."
  9023. (let ((cmd path))
  9024. (if (or (and (org-string-nw-p
  9025. org-confirm-elisp-link-not-regexp)
  9026. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9027. (not org-confirm-elisp-link-function)
  9028. (funcall org-confirm-elisp-link-function
  9029. (format "Execute \"%s\" as elisp? "
  9030. (org-add-props cmd nil 'face 'org-warning))))
  9031. (message "%s => %s" cmd
  9032. (if (eq (string-to-char cmd) ?\()
  9033. (eval (read cmd))
  9034. (call-interactively (read cmd))))
  9035. (user-error "Abort"))))
  9036. (defun org--open-help-link (path)
  9037. "Open a \"help\" type link.
  9038. PATH is a symbol name, as a string."
  9039. (pcase (intern path)
  9040. ((and (pred fboundp) variable) (describe-function variable))
  9041. ((and (pred boundp) function) (describe-variable function))
  9042. (name (user-error "Unknown function or variable: %s" name))))
  9043. (defun org--open-shell-link (path)
  9044. "Open a \"shell\" type link.
  9045. PATH is the command to execute, as a string."
  9046. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9047. (cmd path))
  9048. (if (or (and (org-string-nw-p
  9049. org-confirm-shell-link-not-regexp)
  9050. (string-match
  9051. org-confirm-shell-link-not-regexp cmd))
  9052. (not org-confirm-shell-link-function)
  9053. (funcall org-confirm-shell-link-function
  9054. (format "Execute \"%s\" in shell? "
  9055. (org-add-props cmd nil
  9056. 'face 'org-warning))))
  9057. (progn
  9058. (message "Executing %s" cmd)
  9059. (shell-command cmd buf)
  9060. (when (featurep 'midnight)
  9061. (setq clean-buffer-list-kill-buffer-names
  9062. (cons (buffer-name buf)
  9063. clean-buffer-list-kill-buffer-names))))
  9064. (user-error "Abort"))))
  9065. (defun org-open-at-point (&optional arg reference-buffer)
  9066. "Open link, timestamp, footnote or tags at point.
  9067. When point is on a link, follow it. Normally, files will be
  9068. opened by an appropriate application. If the optional prefix
  9069. argument ARG is non-nil, Emacs will visit the file. With
  9070. a double prefix argument, try to open outside of Emacs, in the
  9071. application the system uses for this file type.
  9072. When point is on a timestamp, open the agenda at the day
  9073. specified.
  9074. When point is a footnote definition, move to the first reference
  9075. found. If it is on a reference, move to the associated
  9076. definition.
  9077. When point is on a headline, display a list of every link in the
  9078. entry, so it is possible to pick one, or all, of them. If point
  9079. is on a tag, call `org-tags-view' instead.
  9080. When optional argument REFERENCE-BUFFER is non-nil, it should
  9081. specify a buffer from where the link search should happen. This
  9082. is used internally by `org-open-link-from-string'.
  9083. On top of syntactically correct links, this function will also
  9084. try to open links and time-stamps in comments, example
  9085. blocks... i.e., whenever point is on something looking like
  9086. a timestamp or a link."
  9087. (interactive "P")
  9088. ;; On a code block, open block's results.
  9089. (unless (call-interactively 'org-babel-open-src-block-result)
  9090. (org-load-modules-maybe)
  9091. (setq org-window-config-before-follow-link (current-window-configuration))
  9092. (org-remove-occur-highlights nil nil t)
  9093. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9094. (let* ((context
  9095. ;; Only consider supported types, even if they are not
  9096. ;; the closest one.
  9097. (org-element-lineage
  9098. (org-element-context)
  9099. '(clock footnote-definition footnote-reference headline
  9100. inlinetask link timestamp)
  9101. t))
  9102. (type (org-element-type context))
  9103. (value (org-element-property :value context)))
  9104. (cond
  9105. ;; On a headline or an inlinetask, but not on a timestamp,
  9106. ;; a link, a footnote reference.
  9107. ((memq type '(headline inlinetask))
  9108. (org-match-line org-complex-heading-regexp)
  9109. (if (and (match-beginning 5)
  9110. (>= (point) (match-beginning 5))
  9111. (< (point) (match-end 5)))
  9112. ;; On tags.
  9113. (org-tags-view arg (substring (match-string 5) 0 -1))
  9114. ;; Not on tags.
  9115. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9116. (`(nil . ,_)
  9117. (require 'org-attach)
  9118. (org-attach-reveal 'if-exists))
  9119. (`(,links . ,links-end)
  9120. (dolist (link (if (stringp links) (list links) links))
  9121. (search-forward link nil links-end)
  9122. (goto-char (match-beginning 0))
  9123. (org-open-at-point))))))
  9124. ;; On a footnote reference or at definition's label.
  9125. ((or (eq type 'footnote-reference)
  9126. (and (eq type 'footnote-definition)
  9127. (save-excursion
  9128. ;; Do not validate action when point is on the
  9129. ;; spaces right after the footnote label, in
  9130. ;; order to be on par with behavior on links.
  9131. (skip-chars-forward " \t")
  9132. (let ((begin
  9133. (org-element-property :contents-begin context)))
  9134. (if begin (< (point) begin)
  9135. (= (org-element-property :post-affiliated context)
  9136. (line-beginning-position)))))))
  9137. (org-footnote-action))
  9138. ;; No valid context. Ignore catch-all types like `headline'.
  9139. ;; If point is on something looking like a link or
  9140. ;; a time-stamp, try opening it. It may be useful in
  9141. ;; comments, example blocks...
  9142. ((memq type '(footnote-definition headline inlinetask nil))
  9143. (call-interactively #'org-open-at-point-global))
  9144. ;; On a clock line, make sure point is on the timestamp
  9145. ;; before opening it.
  9146. ((and (eq type 'clock)
  9147. value
  9148. (>= (point) (org-element-property :begin value))
  9149. (<= (point) (org-element-property :end value)))
  9150. (org-follow-timestamp-link))
  9151. ;; Do nothing on white spaces after an object.
  9152. ((>= (point)
  9153. (save-excursion
  9154. (goto-char (org-element-property :end context))
  9155. (skip-chars-backward " \t")
  9156. (point)))
  9157. (user-error "No link found"))
  9158. ((eq type 'timestamp) (org-follow-timestamp-link))
  9159. ((eq type 'link)
  9160. (let ((type (org-element-property :type context))
  9161. (path (org-link-unescape (org-element-property :path context))))
  9162. ;; Switch back to REFERENCE-BUFFER needed when called in
  9163. ;; a temporary buffer through `org-open-link-from-string'.
  9164. (with-current-buffer (or reference-buffer (current-buffer))
  9165. (cond
  9166. ((equal type "file")
  9167. (if (string-match "[*?{]" (file-name-nondirectory path))
  9168. (dired path)
  9169. ;; Look into `org-link-parameters' in order to find
  9170. ;; a DEDICATED-FUNCTION to open file. The function
  9171. ;; will be applied on raw link instead of parsed
  9172. ;; link due to the limitation in `org-add-link-type'
  9173. ;; ("open" function called with a single argument).
  9174. ;; If no such function is found, fallback to
  9175. ;; `org-open-file'.
  9176. (let* ((option (org-element-property :search-option context))
  9177. (app (org-element-property :application context))
  9178. (dedicated-function
  9179. (org-link-get-parameter
  9180. (if app (concat type "+" app) type)
  9181. :follow)))
  9182. (if dedicated-function
  9183. (funcall dedicated-function
  9184. (concat path
  9185. (and option (concat "::" option))))
  9186. (apply #'org-open-file
  9187. path
  9188. (cond (arg)
  9189. ((equal app "emacs") 'emacs)
  9190. ((equal app "sys") 'system))
  9191. (cond ((not option) nil)
  9192. ((string-match-p "\\`[0-9]+\\'" option)
  9193. (list (string-to-number option)))
  9194. (t (list nil
  9195. (org-link-unescape option)))))))))
  9196. ((functionp (org-link-get-parameter type :follow))
  9197. (funcall (org-link-get-parameter type :follow) path))
  9198. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9199. (unless (run-hook-with-args-until-success
  9200. 'org-open-link-functions path)
  9201. (if (not arg) (org-mark-ring-push)
  9202. (switch-to-buffer-other-window
  9203. (org-get-buffer-for-internal-link (current-buffer))))
  9204. (let ((destination
  9205. (org-with-wide-buffer
  9206. (if (equal type "radio")
  9207. (org-search-radio-target
  9208. (org-element-property :path context))
  9209. (org-link-search
  9210. (if (member type '("custom-id" "coderef"))
  9211. (org-element-property :raw-link context)
  9212. path)
  9213. ;; Prevent fuzzy links from matching
  9214. ;; themselves.
  9215. (and (equal type "fuzzy")
  9216. (+ 2 (org-element-property :begin context)))))
  9217. (point))))
  9218. (unless (and (<= (point-min) destination)
  9219. (>= (point-max) destination))
  9220. (widen))
  9221. (goto-char destination))))
  9222. (t (browse-url-at-point))))))
  9223. (t (user-error "No link found")))))
  9224. (run-hook-with-args 'org-follow-link-hook)))
  9225. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9226. "Offer links in the current entry and return the selected link.
  9227. If there is only one link, return it.
  9228. If NTH is an integer, return the NTH link found.
  9229. If ZERO is a string, check also this string for a link, and if
  9230. there is one, return it."
  9231. (with-current-buffer buffer
  9232. (org-with-wide-buffer
  9233. (goto-char marker)
  9234. (let ((cnt ?0)
  9235. have-zero end links link c)
  9236. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9237. (push (match-string 0 zero) links)
  9238. (setq cnt (1- cnt) have-zero t))
  9239. (save-excursion
  9240. (org-back-to-heading t)
  9241. (setq end (save-excursion (outline-next-heading) (point)))
  9242. (while (re-search-forward org-any-link-re end t)
  9243. (push (match-string 0) links))
  9244. (setq links (org-uniquify (reverse links))))
  9245. (cond
  9246. ((null links)
  9247. (message "No links"))
  9248. ((equal (length links) 1)
  9249. (setq link (car links)))
  9250. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9251. (setq link (nth (if have-zero nth (1- nth)) links)))
  9252. (t ; we have to select a link
  9253. (save-excursion
  9254. (save-window-excursion
  9255. (delete-other-windows)
  9256. (with-output-to-temp-buffer "*Select Link*"
  9257. (dolist (l links)
  9258. (cond
  9259. ((not (string-match org-bracket-link-regexp l))
  9260. (princ (format "[%c] %s\n" (cl-incf cnt)
  9261. (org-unbracket-string "<" ">" l))))
  9262. ((match-end 3)
  9263. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9264. (match-string 3 l) (match-string 1 l))))
  9265. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9266. (match-string 1 l)))))))
  9267. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9268. (message "Select link to open, RET to open all:")
  9269. (setq c (read-char-exclusive))
  9270. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9271. (when (equal c ?q) (user-error "Abort"))
  9272. (if (equal c ?\C-m)
  9273. (setq link links)
  9274. (setq nth (- c ?0))
  9275. (when have-zero (setq nth (1+ nth)))
  9276. (unless (and (integerp nth) (>= (length links) nth))
  9277. (user-error "Invalid link selection"))
  9278. (setq link (nth (1- nth) links)))))
  9279. (cons link end)))))
  9280. ;; TODO: These functions are deprecated since `org-open-at-point'
  9281. ;; hard-codes behavior for "file+emacs" and "file+sys" types.
  9282. (defun org-open-file-with-system (path)
  9283. "Open file at PATH using the system way of opening it."
  9284. (org-open-file path 'system))
  9285. (defun org-open-file-with-emacs (path)
  9286. "Open file at PATH in Emacs."
  9287. (org-open-file path 'emacs))
  9288. ;;; File search
  9289. (defvar org-create-file-search-functions nil
  9290. "List of functions to construct the right search string for a file link.
  9291. These functions are called in turn with point at the location to
  9292. which the link should point.
  9293. A function in the hook should first test if it would like to
  9294. handle this file type, for example by checking the `major-mode'
  9295. or the file extension. If it decides not to handle this file, it
  9296. should just return nil to give other functions a chance. If it
  9297. does handle the file, it must return the search string to be used
  9298. when following the link. The search string will be part of the
  9299. file link, given after a double colon, and `org-open-at-point'
  9300. will automatically search for it. If special measures must be
  9301. taken to make the search successful, another function should be
  9302. added to the companion hook `org-execute-file-search-functions',
  9303. which see.
  9304. A function in this hook may also use `setq' to set the variable
  9305. `description' to provide a suggestion for the descriptive text to
  9306. be used for this link when it gets inserted into an Org buffer
  9307. with \\[org-insert-link].")
  9308. (defvar org-execute-file-search-functions nil
  9309. "List of functions to execute a file search triggered by a link.
  9310. Functions added to this hook must accept a single argument, the
  9311. search string that was part of the file link, the part after the
  9312. double colon. The function must first check if it would like to
  9313. handle this search, for example by checking the `major-mode' or
  9314. the file extension. If it decides not to handle this search, it
  9315. should just return nil to give other functions a chance. If it
  9316. does handle the search, it must return a non-nil value to keep
  9317. other functions from trying.
  9318. Each function can access the current prefix argument through the
  9319. variable `current-prefix-arg'. Note that a single prefix is used
  9320. to force opening a link in Emacs, so it may be good to only use a
  9321. numeric or double prefix to guide the search function.
  9322. In case this is needed, a function in this hook can also restore
  9323. the window configuration before `org-open-at-point' was called using:
  9324. (set-window-configuration org-window-config-before-follow-link)")
  9325. (defun org-search-radio-target (target)
  9326. "Search a radio target matching TARGET in current buffer.
  9327. White spaces are not significant."
  9328. (let ((re (format "<<<%s>>>"
  9329. (mapconcat #'regexp-quote
  9330. (split-string target)
  9331. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9332. (origin (point)))
  9333. (goto-char (point-min))
  9334. (catch :radio-match
  9335. (while (re-search-forward re nil t)
  9336. (backward-char)
  9337. (let ((object (org-element-context)))
  9338. (when (eq (org-element-type object) 'radio-target)
  9339. (goto-char (org-element-property :begin object))
  9340. (org-show-context 'link-search)
  9341. (throw :radio-match nil))))
  9342. (goto-char origin)
  9343. (user-error "No match for radio target: %s" target))))
  9344. (defun org-link-search (s &optional avoid-pos stealth)
  9345. "Search for a search string S.
  9346. If S starts with \"#\", it triggers a custom ID search.
  9347. If S is enclosed within parenthesis, it initiates a coderef
  9348. search.
  9349. If S is surrounded by forward slashes, it is interpreted as
  9350. a regular expression. In Org mode files, this will create an
  9351. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9352. to list matches. If the current buffer is in `dired-mode', grep
  9353. will be used to search in all files.
  9354. When AVOID-POS is given, ignore matches near that position.
  9355. When optional argument STEALTH is non-nil, do not modify
  9356. visibility around point, thus ignoring `org-show-context-detail'
  9357. variable.
  9358. Search is case-insensitive and ignores white spaces. Return type
  9359. of matched result, which is either `dedicated' or `fuzzy'."
  9360. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9361. (let* ((case-fold-search t)
  9362. (origin (point))
  9363. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9364. (starred (eq (string-to-char normalized) ?*))
  9365. (words (split-string (if starred (substring s 1) s)))
  9366. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9367. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9368. type)
  9369. (cond
  9370. ;; Check if there are any special search functions.
  9371. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9372. ((eq (string-to-char s) ?#)
  9373. ;; Look for a custom ID S if S starts with "#".
  9374. (let* ((id (substring normalized 1))
  9375. (match (org-find-property "CUSTOM_ID" id)))
  9376. (if match (progn (goto-char match) (setf type 'dedicated))
  9377. (error "No match for custom ID: %s" id))))
  9378. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9379. ;; Look for coderef targets if S is enclosed within parenthesis.
  9380. (let ((coderef (match-string-no-properties 1 normalized))
  9381. (re (substring s-single-re 1 -1)))
  9382. (goto-char (point-min))
  9383. (catch :coderef-match
  9384. (while (re-search-forward re nil t)
  9385. (let ((element (org-element-at-point)))
  9386. (when (and (memq (org-element-type element)
  9387. '(example-block src-block))
  9388. ;; Build proper regexp according to current
  9389. ;; block's label format.
  9390. (let ((label-fmt
  9391. (regexp-quote
  9392. (or (org-element-property :label-fmt element)
  9393. org-coderef-label-format))))
  9394. (save-excursion
  9395. (beginning-of-line)
  9396. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9397. (format label-fmt coderef))))))
  9398. (setq type 'dedicated)
  9399. (goto-char (match-beginning 1))
  9400. (throw :coderef-match nil))))
  9401. (goto-char origin)
  9402. (error "No match for coderef: %s" coderef))))
  9403. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9404. ;; Look for a regular expression.
  9405. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9406. (match-string 1 s)))
  9407. ;; From here, we handle fuzzy links.
  9408. ;;
  9409. ;; Look for targets, only if not in a headline search.
  9410. ((and (not starred)
  9411. (let ((target (format "<<%s>>" s-multi-re)))
  9412. (catch :target-match
  9413. (goto-char (point-min))
  9414. (while (re-search-forward target nil t)
  9415. (backward-char)
  9416. (let ((context (org-element-context)))
  9417. (when (eq (org-element-type context) 'target)
  9418. (setq type 'dedicated)
  9419. (goto-char (org-element-property :begin context))
  9420. (throw :target-match t))))
  9421. nil))))
  9422. ;; Look for elements named after S, only if not in a headline
  9423. ;; search.
  9424. ((and (not starred)
  9425. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9426. (catch :name-match
  9427. (goto-char (point-min))
  9428. (while (re-search-forward name nil t)
  9429. (let ((element (org-element-at-point)))
  9430. (when (equal words
  9431. (split-string
  9432. (org-element-property :name element)))
  9433. (setq type 'dedicated)
  9434. (beginning-of-line)
  9435. (throw :name-match t))))
  9436. nil))))
  9437. ;; Regular text search. Prefer headlines in Org mode buffers.
  9438. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9439. ;; statistics cookies and tags.
  9440. ((and (derived-mode-p 'org-mode)
  9441. (let ((title-re
  9442. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9443. org-outline-regexp-bol
  9444. org-comment-string
  9445. (mapconcat #'regexp-quote words ".+")))
  9446. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9447. (comment-re (eval-when-compile
  9448. (format "\\`%s[ \t]+" org-comment-string))))
  9449. (goto-char (point-min))
  9450. (catch :found
  9451. (while (re-search-forward title-re nil t)
  9452. (when (equal words
  9453. (split-string
  9454. (replace-regexp-in-string
  9455. cookie-re ""
  9456. (replace-regexp-in-string
  9457. comment-re "" (org-get-heading t t t)))))
  9458. (throw :found t)))
  9459. nil)))
  9460. (beginning-of-line)
  9461. (setq type 'dedicated))
  9462. ;; Offer to create non-existent headline depending on
  9463. ;; `org-link-search-must-match-exact-headline'.
  9464. ((and (derived-mode-p 'org-mode)
  9465. (not org-link-search-inhibit-query)
  9466. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9467. (yes-or-no-p "No match - create this as a new heading? "))
  9468. (goto-char (point-max))
  9469. (unless (bolp) (newline))
  9470. (org-insert-heading nil t t)
  9471. (insert s "\n")
  9472. (beginning-of-line 0))
  9473. ;; Only headlines are looked after. No need to process
  9474. ;; further: throw an error.
  9475. ((and (derived-mode-p 'org-mode)
  9476. (or starred org-link-search-must-match-exact-headline))
  9477. (goto-char origin)
  9478. (error "No match for fuzzy expression: %s" normalized))
  9479. ;; Regular text search.
  9480. ((catch :fuzzy-match
  9481. (goto-char (point-min))
  9482. (while (re-search-forward s-multi-re nil t)
  9483. ;; Skip match if it contains AVOID-POS or it is included in
  9484. ;; a link with a description but outside the description.
  9485. (unless (or (and avoid-pos
  9486. (<= (match-beginning 0) avoid-pos)
  9487. (> (match-end 0) avoid-pos))
  9488. (and (save-match-data
  9489. (org-in-regexp org-bracket-link-regexp))
  9490. (match-beginning 3)
  9491. (or (> (match-beginning 3) (point))
  9492. (<= (match-end 3) (point)))
  9493. (org-element-lineage
  9494. (save-match-data (org-element-context))
  9495. '(link) t)))
  9496. (goto-char (match-beginning 0))
  9497. (setq type 'fuzzy)
  9498. (throw :fuzzy-match t)))
  9499. nil))
  9500. ;; All failed. Throw an error.
  9501. (t (goto-char origin)
  9502. (error "No match for fuzzy expression: %s" normalized)))
  9503. ;; Disclose surroundings of match, if appropriate.
  9504. (when (and (derived-mode-p 'org-mode) (not stealth))
  9505. (org-show-context 'link-search))
  9506. type))
  9507. (defun org-get-buffer-for-internal-link (buffer)
  9508. "Return a buffer to be used for displaying the link target of internal links."
  9509. (cond
  9510. ((not org-display-internal-link-with-indirect-buffer)
  9511. buffer)
  9512. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9513. (message "Buffer is already a clone, not making another one")
  9514. ;; we also do not modify visibility in this case
  9515. buffer)
  9516. (t ; make a new indirect buffer for displaying the link
  9517. (let* ((bn (buffer-name buffer))
  9518. (ibn (concat bn "(Clone)"))
  9519. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9520. (with-current-buffer ib (org-overview))
  9521. ib))))
  9522. (defun org-do-occur (regexp &optional cleanup)
  9523. "Call the Emacs command `occur'.
  9524. If CLEANUP is non-nil, remove the printout of the regular expression
  9525. in the *Occur* buffer. This is useful if the regex is long and not useful
  9526. to read."
  9527. (occur regexp)
  9528. (when cleanup
  9529. (let ((cwin (selected-window)) win beg end)
  9530. (when (setq win (get-buffer-window "*Occur*"))
  9531. (select-window win))
  9532. (goto-char (point-min))
  9533. (when (re-search-forward "match[a-z]+" nil t)
  9534. (setq beg (match-end 0))
  9535. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9536. (setq end (1- (match-beginning 0)))))
  9537. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9538. (goto-char (point-min))
  9539. (select-window cwin))))
  9540. ;;; The Mark Ring
  9541. (defvar org-mark-ring nil
  9542. "Mark ring for positions before jumps in Org mode.")
  9543. (defvar org-mark-ring-last-goto nil
  9544. "Last position in the mark ring used to go back.")
  9545. ;; Fill and close the ring
  9546. (setq org-mark-ring nil)
  9547. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  9548. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  9549. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9550. org-mark-ring)
  9551. (defun org-mark-ring-push (&optional pos buffer)
  9552. "Put the current position into the mark ring and rotate it.
  9553. Also push position into the Emacs mark ring. If optional
  9554. argument POS and BUFFER are not nil, mark this location instead."
  9555. (interactive)
  9556. (let ((pos (or pos (point)))
  9557. (buffer (or buffer (current-buffer))))
  9558. (with-current-buffer buffer
  9559. (org-with-point-at pos (push-mark nil t)))
  9560. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9561. (move-marker (car org-mark-ring) pos buffer))
  9562. (message
  9563. (substitute-command-keys
  9564. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  9565. (defun org-mark-ring-goto (&optional n)
  9566. "Jump to the previous position in the mark ring.
  9567. With prefix arg N, jump back that many stored positions. When
  9568. called several times in succession, walk through the entire ring.
  9569. Org mode commands jumping to a different position in the current file,
  9570. or to another Org file, automatically push the old position onto the ring."
  9571. (interactive "p")
  9572. (let (p m)
  9573. (if (eq last-command this-command)
  9574. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9575. (setq p org-mark-ring))
  9576. (setq org-mark-ring-last-goto p)
  9577. (setq m (car p))
  9578. (pop-to-buffer-same-window (marker-buffer m))
  9579. (goto-char m)
  9580. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9581. (defun org-add-angle-brackets (s)
  9582. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9583. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9584. s)
  9585. ;;; Following specific links
  9586. (defvar org-agenda-buffer-tmp-name)
  9587. (defvar org-agenda-start-on-weekday)
  9588. (defun org-follow-timestamp-link ()
  9589. "Open an agenda view for the time-stamp date/range at point."
  9590. (cond
  9591. ((org-at-date-range-p t)
  9592. (let ((org-agenda-start-on-weekday)
  9593. (t1 (match-string 1))
  9594. (t2 (match-string 2)) tt1 tt2)
  9595. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9596. tt2 (time-to-days (org-time-string-to-time t2)))
  9597. (let ((org-agenda-buffer-tmp-name
  9598. (format "*Org Agenda(a:%s)"
  9599. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9600. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9601. ((org-at-timestamp-p 'lax)
  9602. (let ((org-agenda-buffer-tmp-name
  9603. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9604. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9605. (substring (match-string 1) 0 10)))
  9606. 1)))
  9607. (t (error "This should not happen"))))
  9608. ;;; Following file links
  9609. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9610. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9611. (declare-function mailcap-mime-info
  9612. "mailcap" (string &optional request no-decode))
  9613. (defvar org-wait nil)
  9614. (defun org-open-file (path &optional in-emacs line search)
  9615. "Open the file at PATH.
  9616. First, this expands any special file name abbreviations. Then the
  9617. configuration variable `org-file-apps' is checked if it contains an
  9618. entry for this file type, and if yes, the corresponding command is launched.
  9619. If no application is found, Emacs simply visits the file.
  9620. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9621. With a double \\[universal-argument] \\[universal-argument] \
  9622. prefix arg, Org tries to avoid opening in Emacs
  9623. and to use an external application to visit the file.
  9624. Optional LINE specifies a line to go to, optional SEARCH a string
  9625. to search for. If LINE or SEARCH is given, the file will be
  9626. opened in Emacs, unless an entry from org-file-apps that makes
  9627. use of groups in a regexp matches.
  9628. If you want to change the way frames are used when following a
  9629. link, please customize `org-link-frame-setup'.
  9630. If the file does not exist, an error is thrown."
  9631. (let* ((file (if (equal path "")
  9632. buffer-file-name
  9633. (substitute-in-file-name (expand-file-name path))))
  9634. (file-apps (append org-file-apps (org-default-apps)))
  9635. (apps (cl-remove-if
  9636. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9637. (apps-dlink (cl-remove-if-not
  9638. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9639. (remp (and (assq 'remote apps) (file-remote-p file)))
  9640. (dirp (unless remp (file-directory-p file)))
  9641. (file (if (and dirp org-open-directory-means-index-dot-org)
  9642. (concat (file-name-as-directory file) "index.org")
  9643. file))
  9644. (a-m-a-p (assq 'auto-mode apps))
  9645. (dfile (downcase file))
  9646. ;; Reconstruct the original link from the PATH, LINE and
  9647. ;; SEARCH args.
  9648. (link (cond (line (concat file "::" (number-to-string line)))
  9649. (search (concat file "::" search))
  9650. (t file)))
  9651. (dlink (downcase link))
  9652. (ext
  9653. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  9654. (match-string 1 dfile)))
  9655. (save-position-maybe
  9656. (let ((old-buffer (current-buffer))
  9657. (old-pos (point))
  9658. (old-mode major-mode))
  9659. (lambda ()
  9660. (and (derived-mode-p 'org-mode)
  9661. (eq old-mode 'org-mode)
  9662. (or (not (eq old-buffer (current-buffer)))
  9663. (not (eq old-pos (point))))
  9664. (org-mark-ring-push old-pos old-buffer)))))
  9665. cmd link-match-data)
  9666. (cond
  9667. ((member in-emacs '((16) system))
  9668. (setq cmd (cdr (assq 'system apps))))
  9669. (in-emacs (setq cmd 'emacs))
  9670. (t
  9671. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  9672. (and dirp (cdr (assq 'directory apps)))
  9673. ;; First, try matching against apps-dlink if we
  9674. ;; get a match here, store the match data for
  9675. ;; later.
  9676. (let ((match (assoc-default dlink apps-dlink
  9677. 'string-match)))
  9678. (if match
  9679. (progn (setq link-match-data (match-data))
  9680. match)
  9681. (progn (setq in-emacs (or in-emacs line search))
  9682. nil))) ; if we have no match in apps-dlink,
  9683. ; always open the file in emacs if line or search
  9684. ; is given (for backwards compatibility)
  9685. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  9686. 'string-match)
  9687. (cdr (assoc ext apps))
  9688. (cdr (assq t apps))))))
  9689. (when (eq cmd 'system)
  9690. (setq cmd (cdr (assq 'system apps))))
  9691. (when (eq cmd 'default)
  9692. (setq cmd (cdr (assoc t apps))))
  9693. (when (eq cmd 'mailcap)
  9694. (require 'mailcap)
  9695. (mailcap-parse-mailcaps)
  9696. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  9697. (command (mailcap-mime-info mime-type)))
  9698. (if (stringp command)
  9699. (setq cmd command)
  9700. (setq cmd 'emacs))))
  9701. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  9702. (not (file-exists-p file))
  9703. (not org-open-non-existing-files))
  9704. (user-error "No such file: %s" file))
  9705. (cond
  9706. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  9707. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  9708. (while (string-match "['\"]%s['\"]" cmd)
  9709. (setq cmd (replace-match "%s" t t cmd)))
  9710. (setq cmd (replace-regexp-in-string
  9711. "%s"
  9712. (shell-quote-argument (convert-standard-filename file))
  9713. cmd
  9714. nil t))
  9715. ;; Replace "%1", "%2" etc. in command with group matches from regex
  9716. (save-match-data
  9717. (let ((match-index 1)
  9718. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  9719. (set-match-data link-match-data)
  9720. (while (<= match-index number-of-groups)
  9721. (let ((regex (concat "%" (number-to-string match-index)))
  9722. (replace-with (match-string match-index dlink)))
  9723. (while (string-match regex cmd)
  9724. (setq cmd (replace-match replace-with t t cmd))))
  9725. (setq match-index (+ match-index 1)))))
  9726. (save-window-excursion
  9727. (message "Running %s...done" cmd)
  9728. (start-process-shell-command cmd nil cmd)
  9729. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  9730. ((or (stringp cmd)
  9731. (eq cmd 'emacs))
  9732. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  9733. (widen)
  9734. (cond (line (org-goto-line line)
  9735. (when (derived-mode-p 'org-mode) (org-reveal)))
  9736. (search (condition-case err
  9737. (org-link-search search)
  9738. ;; Save position before error-ing out so user
  9739. ;; can easily move back to the original buffer.
  9740. (error (funcall save-position-maybe)
  9741. (error (nth 1 err)))))))
  9742. ((functionp cmd)
  9743. (save-match-data
  9744. (set-match-data link-match-data)
  9745. (condition-case nil
  9746. (funcall cmd file link)
  9747. ;; FIXME: Remove this check when most default installations
  9748. ;; of Emacs have at least Org 9.0.
  9749. ((debug wrong-number-of-arguments wrong-type-argument
  9750. invalid-function)
  9751. (user-error "Please see Org News for version 9.0 about \
  9752. `org-file-apps'--Lisp error: %S" cmd)))))
  9753. ((consp cmd)
  9754. ;; FIXME: Remove this check when most default installations of
  9755. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  9756. ;; fall back to `org-link-frame-setup' for an old usage of
  9757. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  9758. (user-error "Please see Org News for version 9.0 about \
  9759. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  9760. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  9761. (funcall save-position-maybe)))
  9762. (defun org-file-apps-entry-match-against-dlink-p (entry)
  9763. "This function returns non-nil if `entry' uses a regular
  9764. expression which should be matched against the whole link by
  9765. org-open-file.
  9766. It assumes that is the case when the entry uses a regular
  9767. expression which has at least one grouping construct and the
  9768. action is either a lisp form or a command string containing
  9769. `%1', i.e. using at least one subexpression match as a
  9770. parameter."
  9771. (let ((selector (car entry))
  9772. (action (cdr entry)))
  9773. (if (stringp selector)
  9774. (and (> (regexp-opt-depth selector) 0)
  9775. (or (and (stringp action)
  9776. (string-match "%[0-9]" action))
  9777. (consp action)))
  9778. nil)))
  9779. (defun org-default-apps ()
  9780. "Return the default applications for this operating system."
  9781. (cond
  9782. ((eq system-type 'darwin)
  9783. org-file-apps-defaults-macosx)
  9784. ((eq system-type 'windows-nt)
  9785. org-file-apps-defaults-windowsnt)
  9786. (t org-file-apps-defaults-gnu)))
  9787. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  9788. "Convert extensions to regular expressions in the cars of LIST.
  9789. Also, weed out any non-string entries, because the return value is used
  9790. only for regexp matching.
  9791. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  9792. point to the symbol `emacs', indicating that the file should
  9793. be opened in Emacs."
  9794. (append
  9795. (delq nil
  9796. (mapcar (lambda (x)
  9797. (unless (not (stringp (car x)))
  9798. (if (string-match "\\W" (car x))
  9799. x
  9800. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  9801. list))
  9802. (when add-auto-mode
  9803. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  9804. ;;;; Refiling
  9805. (defun org-get-org-file ()
  9806. "Read a filename, with default directory `org-directory'."
  9807. (let ((default (or org-default-notes-file remember-data-file)))
  9808. (read-file-name (format "File name [%s]: " default)
  9809. (file-name-as-directory org-directory)
  9810. default)))
  9811. (defun org-notes-order-reversed-p ()
  9812. "Check if the current file should receive notes in reversed order."
  9813. (cond
  9814. ((not org-reverse-note-order) nil)
  9815. ((eq t org-reverse-note-order) t)
  9816. ((not (listp org-reverse-note-order)) nil)
  9817. (t (catch 'exit
  9818. (dolist (entry org-reverse-note-order)
  9819. (when (string-match (car entry) buffer-file-name)
  9820. (throw 'exit (cdr entry))))))))
  9821. (defvar org-refile-target-table nil
  9822. "The list of refile targets, created by `org-refile'.")
  9823. (defvar org-agenda-new-buffers nil
  9824. "Buffers created to visit agenda files.")
  9825. (defvar org-refile-cache nil
  9826. "Cache for refile targets.")
  9827. (defvar org-refile-markers nil
  9828. "All the markers used for caching refile locations.")
  9829. (defun org-refile-marker (pos)
  9830. "Get a new refile marker, but only if caching is in use."
  9831. (if (not org-refile-use-cache)
  9832. pos
  9833. (let ((m (make-marker)))
  9834. (move-marker m pos)
  9835. (push m org-refile-markers)
  9836. m)))
  9837. (defun org-refile-cache-clear ()
  9838. "Clear the refile cache and disable all the markers."
  9839. (dolist (m org-refile-markers) (move-marker m nil))
  9840. (setq org-refile-markers nil)
  9841. (setq org-refile-cache nil)
  9842. (message "Refile cache has been cleared"))
  9843. (defun org-refile-cache-check-set (set)
  9844. "Check if all the markers in the cache still have live buffers."
  9845. (let (marker)
  9846. (catch 'exit
  9847. (while (and set (setq marker (nth 3 (pop set))))
  9848. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  9849. (when (and marker (null (marker-buffer marker)))
  9850. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  9851. (sit-for 3)
  9852. (throw 'exit nil)))
  9853. t)))
  9854. (defun org-refile-cache-put (set &rest identifiers)
  9855. "Push the refile targets SET into the cache, under IDENTIFIERS."
  9856. (let* ((key (sha1 (prin1-to-string identifiers)))
  9857. (entry (assoc key org-refile-cache)))
  9858. (if entry
  9859. (setcdr entry set)
  9860. (push (cons key set) org-refile-cache))))
  9861. (defun org-refile-cache-get (&rest identifiers)
  9862. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  9863. (cond
  9864. ((not org-refile-cache) nil)
  9865. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  9866. (t
  9867. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  9868. org-refile-cache))))
  9869. (and set (org-refile-cache-check-set set) set)))))
  9870. (defvar org-outline-path-cache nil
  9871. "Alist between buffer positions and outline paths.
  9872. It value is an alist (POSITION . PATH) where POSITION is the
  9873. buffer position at the beginning of an entry and PATH is a list
  9874. of strings describing the outline path for that entry, in reverse
  9875. order.")
  9876. (defun org-refile-get-targets (&optional default-buffer)
  9877. "Produce a table with refile targets."
  9878. (let ((case-fold-search nil)
  9879. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  9880. (entries (or org-refile-targets '((nil . (:level . 1)))))
  9881. targets tgs files desc descre)
  9882. (message "Getting targets...")
  9883. (with-current-buffer (or default-buffer (current-buffer))
  9884. (dolist (entry entries)
  9885. (setq files (car entry) desc (cdr entry))
  9886. (cond
  9887. ((null files) (setq files (list (current-buffer))))
  9888. ((eq files 'org-agenda-files)
  9889. (setq files (org-agenda-files 'unrestricted)))
  9890. ((and (symbolp files) (fboundp files))
  9891. (setq files (funcall files)))
  9892. ((and (symbolp files) (boundp files))
  9893. (setq files (symbol-value files))))
  9894. (when (stringp files) (setq files (list files)))
  9895. (cond
  9896. ((eq (car desc) :tag)
  9897. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  9898. ((eq (car desc) :todo)
  9899. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  9900. ((eq (car desc) :regexp)
  9901. (setq descre (cdr desc)))
  9902. ((eq (car desc) :level)
  9903. (setq descre (concat "^\\*\\{" (number-to-string
  9904. (if org-odd-levels-only
  9905. (1- (* 2 (cdr desc)))
  9906. (cdr desc)))
  9907. "\\}[ \t]")))
  9908. ((eq (car desc) :maxlevel)
  9909. (setq descre (concat "^\\*\\{1," (number-to-string
  9910. (if org-odd-levels-only
  9911. (1- (* 2 (cdr desc)))
  9912. (cdr desc)))
  9913. "\\}[ \t]")))
  9914. (t (error "Bad refiling target description %s" desc)))
  9915. (dolist (f files)
  9916. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  9917. (or
  9918. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  9919. (progn
  9920. (when (bufferp f)
  9921. (setq f (buffer-file-name (buffer-base-buffer f))))
  9922. (setq f (and f (expand-file-name f)))
  9923. (when (eq org-refile-use-outline-path 'file)
  9924. (push (list (file-name-nondirectory f) f nil nil) tgs))
  9925. (when (eq org-refile-use-outline-path 'buffer-name)
  9926. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  9927. (when (eq org-refile-use-outline-path 'full-file-path)
  9928. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  9929. (org-with-wide-buffer
  9930. (goto-char (point-min))
  9931. (setq org-outline-path-cache nil)
  9932. (while (re-search-forward descre nil t)
  9933. (beginning-of-line)
  9934. (let ((case-fold-search nil))
  9935. (looking-at org-complex-heading-regexp))
  9936. (let ((begin (point))
  9937. (heading (match-string-no-properties 4)))
  9938. (unless (or (and
  9939. org-refile-target-verify-function
  9940. (not
  9941. (funcall org-refile-target-verify-function)))
  9942. (not heading))
  9943. (let ((re (format org-complex-heading-regexp-format
  9944. (regexp-quote heading)))
  9945. (target
  9946. (if (not org-refile-use-outline-path) heading
  9947. (mapconcat
  9948. #'identity
  9949. (append
  9950. (pcase org-refile-use-outline-path
  9951. (`file (list (file-name-nondirectory
  9952. (buffer-file-name
  9953. (buffer-base-buffer)))))
  9954. (`full-file-path
  9955. (list (buffer-file-name
  9956. (buffer-base-buffer))))
  9957. (`buffer-name
  9958. (list (buffer-name
  9959. (buffer-base-buffer))))
  9960. (_ nil))
  9961. (mapcar (lambda (s) (replace-regexp-in-string
  9962. "/" "\\/" s nil t))
  9963. (org-get-outline-path t t)))
  9964. "/"))))
  9965. (push (list target f re (org-refile-marker (point)))
  9966. tgs)))
  9967. (when (= (point) begin)
  9968. ;; Verification function has not moved point.
  9969. (end-of-line)))))))
  9970. (when org-refile-use-cache
  9971. (org-refile-cache-put tgs (buffer-file-name) descre))
  9972. (setq targets (append tgs targets))))))
  9973. (message "Getting targets...done")
  9974. (delete-dups (nreverse targets))))
  9975. (defun org--get-outline-path-1 (&optional use-cache)
  9976. "Return outline path to current headline.
  9977. Outline path is a list of strings, in reverse order. When
  9978. optional argument USE-CACHE is non-nil, make use of a cache. See
  9979. `org-get-outline-path' for details.
  9980. Assume buffer is widened and point is on a headline."
  9981. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  9982. (let ((p (point))
  9983. (heading (let ((case-fold-search nil))
  9984. (looking-at org-complex-heading-regexp)
  9985. (if (not (match-end 4)) ""
  9986. ;; Remove statistics cookies.
  9987. (org-trim
  9988. (org-link-display-format
  9989. (replace-regexp-in-string
  9990. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  9991. (match-string-no-properties 4))))))))
  9992. (if (org-up-heading-safe)
  9993. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  9994. (when use-cache
  9995. (push (cons p path) org-outline-path-cache))
  9996. path)
  9997. ;; This is a new root node. Since we assume we are moving
  9998. ;; forward, we can drop previous cache so as to limit number
  9999. ;; of associations there.
  10000. (let ((path (list heading)))
  10001. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10002. path)))))
  10003. (defun org-get-outline-path (&optional with-self use-cache)
  10004. "Return the outline path to the current entry.
  10005. An outline path is a list of ancestors for current headline, as
  10006. a list of strings. Statistics cookies are removed and links are
  10007. replaced with their description, if any, or their path otherwise.
  10008. When optional argument WITH-SELF is non-nil, the path also
  10009. includes the current headline.
  10010. When optional argument USE-CACHE is non-nil, cache outline paths
  10011. between calls to this function so as to avoid backtracking. This
  10012. argument is useful when planning to find more than one outline
  10013. path in the same document. In that case, there are two
  10014. conditions to satisfy:
  10015. - `org-outline-path-cache' is set to nil before starting the
  10016. process;
  10017. - outline paths are computed by increasing buffer positions."
  10018. (org-with-wide-buffer
  10019. (and (or (and with-self (org-back-to-heading t))
  10020. (org-up-heading-safe))
  10021. (reverse (org--get-outline-path-1 use-cache)))))
  10022. (defun org-format-outline-path (path &optional width prefix separator)
  10023. "Format the outline path PATH for display.
  10024. WIDTH is the maximum number of characters that is available.
  10025. PREFIX is a prefix to be included in the returned string,
  10026. such as the file name.
  10027. SEPARATOR is inserted between the different parts of the path,
  10028. the default is \"/\"."
  10029. (setq width (or width 79))
  10030. (setq path (delq nil path))
  10031. (unless (> width 0)
  10032. (user-error "Argument `width' must be positive"))
  10033. (setq separator (or separator "/"))
  10034. (let* ((org-odd-levels-only nil)
  10035. (fpath (concat
  10036. prefix (and prefix path separator)
  10037. (mapconcat
  10038. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10039. (cl-loop for head in path
  10040. for n from 0
  10041. collect (org-add-props
  10042. head nil 'face
  10043. (nth (% n org-n-level-faces) org-level-faces)))
  10044. separator))))
  10045. (when (> (length fpath) width)
  10046. (if (< width 7)
  10047. ;; It's unlikely that `width' will be this small, but don't
  10048. ;; waste characters by adding ".." if it is.
  10049. (setq fpath (substring fpath 0 width))
  10050. (setf (substring fpath (- width 2)) "..")))
  10051. fpath))
  10052. (defun org-display-outline-path (&optional file current separator just-return-string)
  10053. "Display the current outline path in the echo area.
  10054. If FILE is non-nil, prepend the output with the file name.
  10055. If CURRENT is non-nil, append the current heading to the output.
  10056. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10057. the different parts of the path and defaults to \"/\".
  10058. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10059. (interactive "P")
  10060. (let* (case-fold-search
  10061. (bfn (buffer-file-name (buffer-base-buffer)))
  10062. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10063. res)
  10064. (when current (setq path (append path
  10065. (save-excursion
  10066. (org-back-to-heading t)
  10067. (when (looking-at org-complex-heading-regexp)
  10068. (list (match-string 4)))))))
  10069. (setq res
  10070. (org-format-outline-path
  10071. path
  10072. (1- (frame-width))
  10073. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10074. separator))
  10075. (if just-return-string
  10076. (org-no-properties res)
  10077. (org-unlogged-message "%s" res))))
  10078. (defvar org-refile-history nil
  10079. "History for refiling operations.")
  10080. (defvar org-after-refile-insert-hook nil
  10081. "Hook run after `org-refile' has inserted its stuff at the new location.
  10082. Note that this is still *before* the stuff will be removed from
  10083. the *old* location.")
  10084. (defvar org-capture-last-stored-marker)
  10085. (defvar org-refile-keep nil
  10086. "Non-nil means `org-refile' will copy instead of refile.")
  10087. (defun org-copy ()
  10088. "Like `org-refile', but copy."
  10089. (interactive)
  10090. (let ((org-refile-keep t))
  10091. (org-refile nil nil nil "Copy")))
  10092. (defun org-refile (&optional arg default-buffer rfloc msg)
  10093. "Move the entry or entries at point to another heading.
  10094. The list of target headings is compiled using the information in
  10095. `org-refile-targets', which see.
  10096. At the target location, the entry is filed as a subitem of the
  10097. target heading. Depending on `org-reverse-note-order', the new
  10098. subitem will either be the first or the last subitem.
  10099. If there is an active region, all entries in that region will be
  10100. refiled. However, the region must fulfill the requirement that
  10101. the first heading sets the top-level of the moved text.
  10102. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10103. location
  10104. and not actually move anything.
  10105. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10106. location where the last
  10107. refiling operation has put the subtree.
  10108. With a numeric prefix argument of `2', refile to the running clock.
  10109. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10110. being set to t and copy to the target location, don't move it.
  10111. Beware that keeping refiled entries may result in duplicated ID
  10112. properties.
  10113. RFLOC can be a refile location obtained in a different way.
  10114. MSG is a string to replace \"Refile\" in the default prompt with
  10115. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10116. See also `org-refile-use-outline-path'.
  10117. If you are using target caching (see `org-refile-use-cache'), you
  10118. have to clear the target cache in order to find new targets.
  10119. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10120. prefix argument (`C-u C-u C-u C-c C-w')."
  10121. (interactive "P")
  10122. (if (member arg '(0 (64)))
  10123. (org-refile-cache-clear)
  10124. (let* ((actionmsg (cond (msg msg)
  10125. ((equal arg 3) "Refile (and keep)")
  10126. (t "Refile")))
  10127. (regionp (org-region-active-p))
  10128. (region-start (and regionp (region-beginning)))
  10129. (region-end (and regionp (region-end)))
  10130. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10131. pos it nbuf file level reversed)
  10132. (setq last-command nil)
  10133. (when regionp
  10134. (goto-char region-start)
  10135. (or (bolp) (goto-char (point-at-bol)))
  10136. (setq region-start (point))
  10137. (unless (or (org-kill-is-subtree-p
  10138. (buffer-substring region-start region-end))
  10139. (prog1 org-refile-active-region-within-subtree
  10140. (let ((s (point-at-eol)))
  10141. (org-toggle-heading)
  10142. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10143. (user-error "The region is not a (sequence of) subtree(s)")))
  10144. (if (equal arg '(16))
  10145. (org-refile-goto-last-stored)
  10146. (when (or
  10147. (and (equal arg 2)
  10148. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10149. (prog1
  10150. (setq it (list (or org-clock-heading "running clock")
  10151. (buffer-file-name
  10152. (marker-buffer org-clock-hd-marker))
  10153. ""
  10154. (marker-position org-clock-hd-marker)))
  10155. (setq arg nil)))
  10156. (setq it
  10157. (or rfloc
  10158. (let (heading-text)
  10159. (save-excursion
  10160. (unless (and arg (listp arg))
  10161. (org-back-to-heading t)
  10162. (setq heading-text
  10163. (replace-regexp-in-string
  10164. org-bracket-link-regexp
  10165. "\\3"
  10166. (or (nth 4 (org-heading-components))
  10167. ""))))
  10168. (org-refile-get-location
  10169. (cond ((and arg (listp arg)) "Goto")
  10170. (regionp (concat actionmsg " region to"))
  10171. (t (concat actionmsg " subtree \""
  10172. heading-text "\" to")))
  10173. default-buffer
  10174. (and (not (equal '(4) arg))
  10175. org-refile-allow-creating-parent-nodes)))))))
  10176. (setq file (nth 1 it)
  10177. pos (nth 3 it))
  10178. (when (and (not arg)
  10179. pos
  10180. (equal (buffer-file-name) file)
  10181. (if regionp
  10182. (and (>= pos region-start)
  10183. (<= pos region-end))
  10184. (and (>= pos (point))
  10185. (< pos (save-excursion
  10186. (org-end-of-subtree t t))))))
  10187. (error "Cannot refile to position inside the tree or region"))
  10188. (setq nbuf (or (find-buffer-visiting file)
  10189. (find-file-noselect file)))
  10190. (if (and arg (not (equal arg 3)))
  10191. (progn
  10192. (pop-to-buffer-same-window nbuf)
  10193. (goto-char (cond (pos)
  10194. ((org-notes-order-reversed-p) (point-min))
  10195. (t (point-max))))
  10196. (org-show-context 'org-goto))
  10197. (if regionp
  10198. (progn
  10199. (org-kill-new (buffer-substring region-start region-end))
  10200. (org-save-markers-in-region region-start region-end))
  10201. (org-copy-subtree 1 nil t))
  10202. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10203. (find-file-noselect file)))
  10204. (setq reversed (org-notes-order-reversed-p))
  10205. (org-with-wide-buffer
  10206. (if pos
  10207. (progn
  10208. (goto-char pos)
  10209. (setq level (org-get-valid-level (funcall outline-level) 1))
  10210. (goto-char
  10211. (if reversed
  10212. (or (outline-next-heading) (point-max))
  10213. (or (save-excursion (org-get-next-sibling))
  10214. (org-end-of-subtree t t)
  10215. (point-max)))))
  10216. (setq level 1)
  10217. (if (not reversed)
  10218. (goto-char (point-max))
  10219. (goto-char (point-min))
  10220. (or (outline-next-heading) (goto-char (point-max)))))
  10221. (unless (bolp) (newline))
  10222. (org-paste-subtree level nil nil t)
  10223. (when org-log-refile
  10224. (org-add-log-setup 'refile nil nil org-log-refile)
  10225. (unless (eq org-log-refile 'note)
  10226. (save-excursion (org-add-log-note))))
  10227. (and org-auto-align-tags
  10228. (let ((org-loop-over-headlines-in-active-region nil))
  10229. (org-align-tags)))
  10230. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10231. :last-refile)))
  10232. (when bookmark-name
  10233. (with-demoted-errors
  10234. (bookmark-set bookmark-name))))
  10235. ;; If we are refiling for capture, make sure that the
  10236. ;; last-capture pointers point here
  10237. (when (bound-and-true-p org-capture-is-refiling)
  10238. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10239. :last-capture-marker)))
  10240. (when bookmark-name
  10241. (with-demoted-errors
  10242. (bookmark-set bookmark-name))))
  10243. (move-marker org-capture-last-stored-marker (point)))
  10244. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10245. (run-hooks 'org-after-refile-insert-hook)))
  10246. (unless org-refile-keep
  10247. (if regionp
  10248. (delete-region (point) (+ (point) (- region-end region-start)))
  10249. (org-preserve-local-variables
  10250. (delete-region
  10251. (and (org-back-to-heading t) (point))
  10252. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  10253. (when (featurep 'org-inlinetask)
  10254. (org-inlinetask-remove-END-maybe))
  10255. (setq org-markers-to-move nil)
  10256. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10257. (defun org-refile-goto-last-stored ()
  10258. "Go to the location where the last refile was stored."
  10259. (interactive)
  10260. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10261. (message "This is the location of the last refile"))
  10262. (defun org-refile--get-location (refloc tbl)
  10263. "When user refile to REFLOC, find the associated target in TBL.
  10264. Also check `org-refile-target-table'."
  10265. (car (delq
  10266. nil
  10267. (mapcar
  10268. (lambda (r) (or (assoc r tbl)
  10269. (assoc r org-refile-target-table)))
  10270. (list (replace-regexp-in-string "/$" "" refloc)
  10271. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10272. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10273. "Prompt the user for a refile location, using PROMPT.
  10274. PROMPT should not be suffixed with a colon and a space, because
  10275. this function appends the default value from
  10276. `org-refile-history' automatically, if that is not empty."
  10277. (let ((org-refile-targets org-refile-targets)
  10278. (org-refile-use-outline-path org-refile-use-outline-path))
  10279. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10280. (unless org-refile-target-table
  10281. (user-error "No refile targets"))
  10282. (let* ((cbuf (current-buffer))
  10283. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10284. (cfunc (if (and org-refile-use-outline-path
  10285. org-outline-path-complete-in-steps)
  10286. #'org-olpath-completing-read
  10287. #'completing-read))
  10288. (extra (if org-refile-use-outline-path "/" ""))
  10289. (cbnex (concat (buffer-name) extra))
  10290. (filename (and cfn (expand-file-name cfn)))
  10291. (tbl (mapcar
  10292. (lambda (x)
  10293. (if (and (not (member org-refile-use-outline-path
  10294. '(file full-file-path)))
  10295. (not (equal filename (nth 1 x))))
  10296. (cons (concat (car x) extra " ("
  10297. (file-name-nondirectory (nth 1 x)) ")")
  10298. (cdr x))
  10299. (cons (concat (car x) extra) (cdr x))))
  10300. org-refile-target-table))
  10301. (completion-ignore-case t)
  10302. cdef
  10303. (prompt (concat prompt
  10304. (or (and (car org-refile-history)
  10305. (concat " (default " (car org-refile-history) ")"))
  10306. (and (assoc cbnex tbl) (setq cdef cbnex)
  10307. (concat " (default " cbnex ")"))) ": "))
  10308. pa answ parent-target child parent old-hist)
  10309. (setq old-hist org-refile-history)
  10310. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10311. nil 'org-refile-history (or cdef (car org-refile-history))))
  10312. (if (setq pa (org-refile--get-location answ tbl))
  10313. (progn
  10314. (org-refile-check-position pa)
  10315. (when (or (not org-refile-history)
  10316. (not (eq old-hist org-refile-history))
  10317. (not (equal (car pa) (car org-refile-history))))
  10318. (setq org-refile-history
  10319. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10320. org-refile-history
  10321. (cdr org-refile-history))))
  10322. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10323. (pop org-refile-history)))
  10324. pa)
  10325. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10326. (progn
  10327. (setq parent (match-string 1 answ)
  10328. child (match-string 2 answ))
  10329. (setq parent-target (org-refile--get-location parent tbl))
  10330. (when (and parent-target
  10331. (or (eq new-nodes t)
  10332. (and (eq new-nodes 'confirm)
  10333. (y-or-n-p (format "Create new node \"%s\"? "
  10334. child)))))
  10335. (org-refile-new-child parent-target child)))
  10336. (user-error "Invalid target location")))))
  10337. (declare-function org-string-nw-p "org-macs" (s))
  10338. (defun org-refile-check-position (refile-pointer)
  10339. "Check if the refile pointer matches the headline to which it points."
  10340. (let* ((file (nth 1 refile-pointer))
  10341. (re (nth 2 refile-pointer))
  10342. (pos (nth 3 refile-pointer))
  10343. buffer)
  10344. (if (and (not (markerp pos)) (not file))
  10345. (user-error "Please indicate a target file in the refile path")
  10346. (when (org-string-nw-p re)
  10347. (setq buffer (if (markerp pos)
  10348. (marker-buffer pos)
  10349. (or (find-buffer-visiting file)
  10350. (find-file-noselect file))))
  10351. (with-current-buffer buffer
  10352. (org-with-wide-buffer
  10353. (goto-char pos)
  10354. (beginning-of-line 1)
  10355. (unless (looking-at-p re)
  10356. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10357. (defun org-refile-new-child (parent-target child)
  10358. "Use refile target PARENT-TARGET to add new CHILD below it."
  10359. (unless parent-target
  10360. (error "Cannot find parent for new node"))
  10361. (let ((file (nth 1 parent-target))
  10362. (pos (nth 3 parent-target))
  10363. level)
  10364. (with-current-buffer (or (find-buffer-visiting file)
  10365. (find-file-noselect file))
  10366. (org-with-wide-buffer
  10367. (if pos
  10368. (goto-char pos)
  10369. (goto-char (point-max))
  10370. (unless (bolp) (newline)))
  10371. (when (looking-at org-outline-regexp)
  10372. (setq level (funcall outline-level))
  10373. (org-end-of-subtree t t))
  10374. (org-back-over-empty-lines)
  10375. (insert "\n" (make-string
  10376. (if pos (org-get-valid-level level 1) 1) ?*)
  10377. " " child "\n")
  10378. (beginning-of-line 0)
  10379. (list (concat (car parent-target) "/" child) file "" (point))))))
  10380. (defun org-olpath-completing-read (prompt collection &rest args)
  10381. "Read an outline path like a file name."
  10382. (let ((thetable collection))
  10383. (apply #'completing-read
  10384. prompt
  10385. (lambda (string predicate &optional flag)
  10386. (cond
  10387. ((eq flag nil) (try-completion string thetable))
  10388. ((eq flag t)
  10389. (let ((l (length string)))
  10390. (mapcar (lambda (x)
  10391. (let ((r (substring x l))
  10392. (f (if (string-match " ([^)]*)$" x)
  10393. (match-string 0 x)
  10394. "")))
  10395. (if (string-match "/" r)
  10396. (concat string (substring r 0 (match-end 0)) f)
  10397. x)))
  10398. (all-completions string thetable predicate))))
  10399. ;; Exact match?
  10400. ((eq flag 'lambda) (assoc string thetable))))
  10401. args)))
  10402. ;;;; Dynamic blocks
  10403. (defun org-find-dblock (name)
  10404. "Find the first dynamic block with name NAME in the buffer.
  10405. If not found, stay at current position and return nil."
  10406. (let ((case-fold-search t) pos)
  10407. (save-excursion
  10408. (goto-char (point-min))
  10409. (setq pos (and (re-search-forward
  10410. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10411. (match-beginning 0))))
  10412. (when pos (goto-char pos))
  10413. pos))
  10414. (defun org-create-dblock (plist)
  10415. "Create a dynamic block section, with parameters taken from PLIST.
  10416. PLIST must contain a :name entry which is used as the name of the block."
  10417. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10418. (end-of-line 1)
  10419. (newline))
  10420. (let ((col (current-column))
  10421. (name (plist-get plist :name)))
  10422. (insert "#+BEGIN: " name)
  10423. (while plist
  10424. (if (eq (car plist) :name)
  10425. (setq plist (cddr plist))
  10426. (insert " " (prin1-to-string (pop plist)))))
  10427. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10428. (beginning-of-line -2)))
  10429. (defun org-prepare-dblock ()
  10430. "Prepare dynamic block for refresh.
  10431. This empties the block, puts the cursor at the insert position and returns
  10432. the property list including an extra property :name with the block name."
  10433. (unless (looking-at org-dblock-start-re)
  10434. (user-error "Not at a dynamic block"))
  10435. (let* ((begdel (1+ (match-end 0)))
  10436. (name (org-no-properties (match-string 1)))
  10437. (params (append (list :name name)
  10438. (read (concat "(" (match-string 3) ")")))))
  10439. (save-excursion
  10440. (beginning-of-line 1)
  10441. (skip-chars-forward " \t")
  10442. (setq params (plist-put params :indentation-column (current-column))))
  10443. (unless (re-search-forward org-dblock-end-re nil t)
  10444. (error "Dynamic block not terminated"))
  10445. (setq params
  10446. (append params
  10447. (list :content (buffer-substring
  10448. begdel (match-beginning 0)))))
  10449. (delete-region begdel (match-beginning 0))
  10450. (goto-char begdel)
  10451. (open-line 1)
  10452. params))
  10453. (defun org-map-dblocks (&optional command)
  10454. "Apply COMMAND to all dynamic blocks in the current buffer.
  10455. If COMMAND is not given, use `org-update-dblock'."
  10456. (let ((cmd (or command 'org-update-dblock)))
  10457. (save-excursion
  10458. (goto-char (point-min))
  10459. (while (re-search-forward org-dblock-start-re nil t)
  10460. (goto-char (match-beginning 0))
  10461. (save-excursion
  10462. (condition-case nil
  10463. (funcall cmd)
  10464. (error (message "Error during update of dynamic block"))))
  10465. (unless (re-search-forward org-dblock-end-re nil t)
  10466. (error "Dynamic block not terminated"))))))
  10467. (defun org-dblock-update (&optional arg)
  10468. "User command for updating dynamic blocks.
  10469. Update the dynamic block at point. With prefix ARG, update all dynamic
  10470. blocks in the buffer."
  10471. (interactive "P")
  10472. (if arg
  10473. (org-update-all-dblocks)
  10474. (or (looking-at org-dblock-start-re)
  10475. (org-beginning-of-dblock))
  10476. (org-update-dblock)))
  10477. (defun org-update-dblock ()
  10478. "Update the dynamic block at point.
  10479. This means to empty the block, parse for parameters and then call
  10480. the correct writing function."
  10481. (interactive)
  10482. (save-excursion
  10483. (let* ((win (selected-window))
  10484. (pos (point))
  10485. (line (org-current-line))
  10486. (params (org-prepare-dblock))
  10487. (name (plist-get params :name))
  10488. (indent (plist-get params :indentation-column))
  10489. (cmd (intern (concat "org-dblock-write:" name))))
  10490. (message "Updating dynamic block `%s' at line %d..." name line)
  10491. (funcall cmd params)
  10492. (message "Updating dynamic block `%s' at line %d...done" name line)
  10493. (goto-char pos)
  10494. (when (and indent (> indent 0))
  10495. (setq indent (make-string indent ?\ ))
  10496. (save-excursion
  10497. (select-window win)
  10498. (org-beginning-of-dblock)
  10499. (forward-line 1)
  10500. (while (not (looking-at org-dblock-end-re))
  10501. (insert indent)
  10502. (beginning-of-line 2))
  10503. (when (looking-at org-dblock-end-re)
  10504. (and (looking-at "[ \t]+")
  10505. (replace-match ""))
  10506. (insert indent)))))))
  10507. (defun org-beginning-of-dblock ()
  10508. "Find the beginning of the dynamic block at point.
  10509. Error if there is no such block at point."
  10510. (let ((pos (point))
  10511. beg)
  10512. (end-of-line 1)
  10513. (if (and (re-search-backward org-dblock-start-re nil t)
  10514. (setq beg (match-beginning 0))
  10515. (re-search-forward org-dblock-end-re nil t)
  10516. (> (match-end 0) pos))
  10517. (goto-char beg)
  10518. (goto-char pos)
  10519. (error "Not in a dynamic block"))))
  10520. (defun org-update-all-dblocks ()
  10521. "Update all dynamic blocks in the buffer.
  10522. This function can be used in a hook."
  10523. (interactive)
  10524. (when (derived-mode-p 'org-mode)
  10525. (org-map-dblocks 'org-update-dblock)))
  10526. ;;;; Completion
  10527. (declare-function org-export-backend-options "ox" (cl-x) t)
  10528. (defun org-get-export-keywords ()
  10529. "Return a list of all currently understood export keywords.
  10530. Export keywords include options, block names, attributes and
  10531. keywords relative to each registered export back-end."
  10532. (let (keywords)
  10533. (dolist (backend
  10534. (bound-and-true-p org-export-registered-backends)
  10535. (delq nil keywords))
  10536. ;; Back-end name (for keywords, like #+LATEX:)
  10537. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10538. (dolist (option-entry (org-export-backend-options backend))
  10539. ;; Back-end options.
  10540. (push (nth 1 option-entry) keywords)))))
  10541. (defconst org-options-keywords
  10542. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10543. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10544. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10545. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10546. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10547. (defcustom org-structure-template-alist
  10548. '(("a" . "export ascii")
  10549. ("c" . "center")
  10550. ("C" . "comment")
  10551. ("e" . "example")
  10552. ("E" . "export")
  10553. ("h" . "export html")
  10554. ("l" . "export latex")
  10555. ("q" . "quote")
  10556. ("s" . "src")
  10557. ("v" . "verse"))
  10558. "An alist of keys and block types.
  10559. `org-insert-structure-template' will display a menu with this
  10560. list of templates to choose from. The block type is inserted,
  10561. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  10562. The menu keys are defined by the car of each entry in this alist.
  10563. If two entries have the keys \"a\" and \"aa\" respectively, the
  10564. former will be inserted by typing \"a TAB/RET/SPC\" and the
  10565. latter will be inserted by typing \"aa\". If an entry with the
  10566. key \"aab\" is later added, it can be inserted by typing \"ab\".
  10567. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  10568. block can be inserted by pressing TAB after the string \"<KEY\"."
  10569. :group 'org-edit-structure
  10570. :type '(repeat
  10571. (cons (string :tag "Key")
  10572. (string :tag "Template")))
  10573. :package-version '(Org . "9.2"))
  10574. (defun org--insert-structure-template-mks ()
  10575. "Present `org-structure-template-alist' with `org-mks'.
  10576. Menus are added if keys require more than one keystroke. Tabs
  10577. are added to single key entries when more than one stroke is
  10578. needed. Keys longer than two characters are reduced to two
  10579. characters."
  10580. (let* (case-fold-search
  10581. (templates (append org-structure-template-alist
  10582. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  10583. (keys (mapcar #'car templates))
  10584. (start-letters
  10585. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  10586. ;; Sort each element of `org-structure-template-alist' into
  10587. ;; sublists according to the first letter.
  10588. (superlist
  10589. (mapcar (lambda (letter)
  10590. (list letter
  10591. (cl-remove-if-not
  10592. (apply-partially #'string-match-p (concat "^" letter))
  10593. templates :key #'car)))
  10594. start-letters)))
  10595. (org-mks
  10596. (apply #'append
  10597. ;; Make an `org-mks' table. If only one element is
  10598. ;; present in a sublist, make it part of the top-menu,
  10599. ;; otherwise make a submenu according to the starting
  10600. ;; letter and populate it.
  10601. (mapcar (lambda (sublist)
  10602. (if (eq 1 (length (cadr sublist)))
  10603. (mapcar (lambda (elm)
  10604. (list (substring (car elm) 0 1)
  10605. (cdr elm) ""))
  10606. (cadr sublist))
  10607. ;; Create submenu.
  10608. (let* ((topkey (car sublist))
  10609. (elms (cadr sublist))
  10610. (keys (mapcar #'car elms))
  10611. (long (> (length elms) 3)))
  10612. (append
  10613. (list
  10614. ;; Make a description of the submenu.
  10615. (list topkey
  10616. (concat
  10617. (mapconcat #'cdr
  10618. (cl-subseq elms 0 (if long 3 (length elms)))
  10619. ", ")
  10620. (when long ", ..."))))
  10621. ;; List of entries in submenu.
  10622. (cl-mapcar #'list
  10623. (org--insert-structure-template-unique-keys keys)
  10624. (mapcar #'cdr elms)
  10625. (make-list (length elms) ""))))))
  10626. superlist))
  10627. "Select a key\n============"
  10628. "Key: ")))
  10629. (defun org--insert-structure-template-unique-keys (keys)
  10630. "Make a list of unique, two characters long elements from KEYS.
  10631. Elements of length one have a tab appended. Elements of length
  10632. two are kept as is. Longer elements are truncated to length two.
  10633. If an element cannot be made unique, an error is raised."
  10634. (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  10635. menu-keys)
  10636. (dolist (key orderd-keys)
  10637. (let ((potential-key
  10638. (cl-case (length key)
  10639. (1 (concat key "\t"))
  10640. (2 key)
  10641. (otherwise
  10642. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  10643. (mapcar (apply-partially #'concat (substring key 0 1))
  10644. (split-string (substring key 1) "" t)))))))
  10645. (if (or (not potential-key) (assoc potential-key menu-keys))
  10646. (user-error "Could not make unique key for %s." key)
  10647. (push (cons potential-key key) menu-keys))))
  10648. (mapcar #'car
  10649. (cl-sort menu-keys #'<
  10650. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  10651. (defun org-insert-structure-template (type)
  10652. "Insert a block structure of the type #+begin_foo/#+end_foo.
  10653. Select a block from `org-structure-template-alist' then type
  10654. either RET, TAB or SPC to write the block type. With an active
  10655. region, wrap the region in the block. Otherwise, insert an empty
  10656. block."
  10657. (interactive
  10658. (list (pcase (org--insert-structure-template-mks)
  10659. (`("\t" . ,_) (read-string "Structure type: "))
  10660. (`(,_ ,choice . ,_) choice))))
  10661. (let* ((region? (use-region-p))
  10662. (col (current-indentation))
  10663. (indent (make-string col ?\s))
  10664. (special? (string-match-p "\\(src\\|export\\)\\'" type))
  10665. (region-string (and region?
  10666. (buffer-substring (region-beginning)
  10667. (region-end))))
  10668. (region-end-blank (and region?
  10669. (save-excursion
  10670. (goto-char (region-end))
  10671. (when (looking-at "[ \t]*$")
  10672. (replace-match "")
  10673. t))))
  10674. s)
  10675. (when region? (delete-region (region-beginning) (region-end)))
  10676. (unless (save-excursion (skip-chars-backward "[ \t]") (bolp))
  10677. (insert "\n"))
  10678. (beginning-of-line)
  10679. (save-excursion
  10680. (insert
  10681. (with-temp-buffer
  10682. (when region?
  10683. (insert region-string "\n")
  10684. (when (string-match-p
  10685. (concat "\\`" (regexp-opt '("example" "export" "src")))
  10686. type)
  10687. (org-escape-code-in-region (point-min) (point-max))))
  10688. (goto-char (point-min))
  10689. ;; Delete trailing white-lines.
  10690. (when region?
  10691. (while (looking-at-p "^[ \t]*$")
  10692. (delete-region (line-beginning-position)
  10693. (line-beginning-position 2))))
  10694. (save-excursion
  10695. (while (not (eobp))
  10696. (unless (looking-at-p indent)
  10697. (insert indent))
  10698. (forward-line)))
  10699. (insert
  10700. indent
  10701. (format "#+begin_%s%s\n" type (if special? " " "")))
  10702. (unless region? (indent-to col))
  10703. (setq s (point))
  10704. (goto-char (point-max))
  10705. (skip-chars-backward "[ \t\n]" s)
  10706. (delete-region (line-end-position) (point-max))
  10707. (insert "\n" indent
  10708. (format "#+end_%s" (car (split-string type)))
  10709. (if region-end-blank "" "\n"))
  10710. (buffer-substring (point-min) (point))))
  10711. (when (and (eobp) (not (bolp))) (insert "\n")))
  10712. (cond (special?
  10713. (end-of-line))
  10714. (t
  10715. (forward-line)
  10716. (skip-chars-forward "[ \t]*")))))
  10717. ;;;; TODO, DEADLINE, Comments
  10718. (defun org-toggle-comment ()
  10719. "Change the COMMENT state of an entry."
  10720. (interactive)
  10721. (save-excursion
  10722. (org-back-to-heading)
  10723. (let ((case-fold-search nil))
  10724. (looking-at org-complex-heading-regexp))
  10725. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  10726. (skip-chars-forward " \t")
  10727. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  10728. (if (org-in-commented-heading-p t)
  10729. (delete-region (point)
  10730. (progn (search-forward " " (line-end-position) 'move)
  10731. (skip-chars-forward " \t")
  10732. (point)))
  10733. (insert org-comment-string)
  10734. (unless (eolp) (insert " ")))))
  10735. (defvar org-last-todo-state-is-todo nil
  10736. "This is non-nil when the last TODO state change led to a TODO state.
  10737. If the last change removed the TODO tag or switched to DONE, then
  10738. this is nil.")
  10739. (defvar org-todo-setup-filter-hook nil
  10740. "Hook for functions that pre-filter todo specs.
  10741. Each function takes a todo spec and returns either nil or the spec
  10742. transformed into canonical form." )
  10743. (defvar org-todo-get-default-hook nil
  10744. "Hook for functions that get a default item for todo.
  10745. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  10746. nil or a string to be used for the todo mark." )
  10747. (defvar org-agenda-headline-snapshot-before-repeat)
  10748. (defun org-current-effective-time ()
  10749. "Return current time adjusted for `org-extend-today-until' variable."
  10750. (let* ((ct (org-current-time))
  10751. (dct (decode-time ct))
  10752. (ct1
  10753. (cond
  10754. (org-use-last-clock-out-time-as-effective-time
  10755. (or (org-clock-get-last-clock-out-time) ct))
  10756. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  10757. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  10758. (t ct))))
  10759. ct1))
  10760. (defun org-todo-yesterday (&optional arg)
  10761. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  10762. (interactive "P")
  10763. (if (eq major-mode 'org-agenda-mode)
  10764. (apply 'org-agenda-todo-yesterday arg)
  10765. (let* ((org-use-effective-time t)
  10766. (hour (nth 2 (decode-time (org-current-time))))
  10767. (org-extend-today-until (1+ hour)))
  10768. (org-todo arg))))
  10769. (defvar org-block-entry-blocking ""
  10770. "First entry preventing the TODO state change.")
  10771. (defun org-cancel-repeater ()
  10772. "Cancel a repeater by setting its numeric value to zero."
  10773. (interactive)
  10774. (save-excursion
  10775. (org-back-to-heading t)
  10776. (let ((bound1 (point))
  10777. (bound0 (save-excursion (outline-next-heading) (point))))
  10778. (when (and (re-search-forward
  10779. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  10780. org-deadline-time-regexp "\\)\\|\\("
  10781. org-ts-regexp "\\)")
  10782. bound0 t)
  10783. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  10784. bound1 t))
  10785. (replace-match "0" t nil nil 1)))))
  10786. (defvar org-state)
  10787. (defvar org-blocked-by-checkboxes)
  10788. (defun org-todo (&optional arg)
  10789. "Change the TODO state of an item.
  10790. The state of an item is given by a keyword at the start of the heading,
  10791. like
  10792. *** TODO Write paper
  10793. *** DONE Call mom
  10794. The different keywords are specified in the variable `org-todo-keywords'.
  10795. By default the available states are \"TODO\" and \"DONE\". So, for this
  10796. example: when the item starts with TODO, it is changed to DONE.
  10797. When it starts with DONE, the DONE is removed. And when neither TODO nor
  10798. DONE are present, add TODO at the beginning of the heading.
  10799. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  10800. state.
  10801. With numeric prefix ARG, switch to that state.
  10802. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  10803. next set of TODO \
  10804. keywords (nextset).
  10805. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  10806. prefix, circumvent any state blocking.
  10807. With a numeric prefix arg of 0, inhibit note taking for the change.
  10808. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  10809. When called through ELisp, arg is also interpreted in the following way:
  10810. `none' -> empty state
  10811. \"\" -> switch to empty state
  10812. `done' -> switch to DONE
  10813. `nextset' -> switch to the next set of keywords
  10814. `previousset' -> switch to the previous set of keywords
  10815. \"WAITING\" -> switch to the specified keyword, but only if it
  10816. really is a member of `org-todo-keywords'."
  10817. (interactive "P")
  10818. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10819. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10820. 'region-start-level 'region))
  10821. org-loop-over-headlines-in-active-region)
  10822. (org-map-entries
  10823. `(org-todo ,arg)
  10824. org-loop-over-headlines-in-active-region
  10825. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  10826. (when (equal arg '(16)) (setq arg 'nextset))
  10827. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  10828. (let ((org-blocker-hook org-blocker-hook)
  10829. commentp
  10830. case-fold-search)
  10831. (when (equal arg '(64))
  10832. (setq arg nil org-blocker-hook nil))
  10833. (when (and org-blocker-hook
  10834. (or org-inhibit-blocking
  10835. (org-entry-get nil "NOBLOCKING")))
  10836. (setq org-blocker-hook nil))
  10837. (save-excursion
  10838. (catch 'exit
  10839. (org-back-to-heading t)
  10840. (when (org-in-commented-heading-p t)
  10841. (org-toggle-comment)
  10842. (setq commentp t))
  10843. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  10844. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  10845. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  10846. (let* ((match-data (match-data))
  10847. (startpos (copy-marker (line-beginning-position)))
  10848. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  10849. (org-log-done org-log-done)
  10850. (org-log-repeat org-log-repeat)
  10851. (org-todo-log-states org-todo-log-states)
  10852. (org-inhibit-logging
  10853. (if (equal arg 0)
  10854. (progn (setq arg nil) 'note) org-inhibit-logging))
  10855. (this (match-string 1))
  10856. (hl-pos (match-beginning 0))
  10857. (head (org-get-todo-sequence-head this))
  10858. (ass (assoc head org-todo-kwd-alist))
  10859. (interpret (nth 1 ass))
  10860. (done-word (nth 3 ass))
  10861. (final-done-word (nth 4 ass))
  10862. (org-last-state (or this ""))
  10863. (completion-ignore-case t)
  10864. (member (member this org-todo-keywords-1))
  10865. (tail (cdr member))
  10866. (org-state (cond
  10867. ((and org-todo-key-trigger
  10868. (or (and (equal arg '(4))
  10869. (eq org-use-fast-todo-selection 'prefix))
  10870. (and (not arg) org-use-fast-todo-selection
  10871. (not (eq org-use-fast-todo-selection
  10872. 'prefix)))))
  10873. ;; Use fast selection.
  10874. (org-fast-todo-selection))
  10875. ((and (equal arg '(4))
  10876. (or (not org-use-fast-todo-selection)
  10877. (not org-todo-key-trigger)))
  10878. ;; Read a state with completion.
  10879. (completing-read
  10880. "State: " (mapcar #'list org-todo-keywords-1)
  10881. nil t))
  10882. ((eq arg 'right)
  10883. (if this
  10884. (if tail (car tail) nil)
  10885. (car org-todo-keywords-1)))
  10886. ((eq arg 'left)
  10887. (unless (equal member org-todo-keywords-1)
  10888. (if this
  10889. (nth (- (length org-todo-keywords-1)
  10890. (length tail) 2)
  10891. org-todo-keywords-1)
  10892. (org-last org-todo-keywords-1))))
  10893. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  10894. (setq arg nil))) ;hack to fall back to cycling
  10895. (arg
  10896. ;; User or caller requests a specific state.
  10897. (cond
  10898. ((equal arg "") nil)
  10899. ((eq arg 'none) nil)
  10900. ((eq arg 'done) (or done-word (car org-done-keywords)))
  10901. ((eq arg 'nextset)
  10902. (or (car (cdr (member head org-todo-heads)))
  10903. (car org-todo-heads)))
  10904. ((eq arg 'previousset)
  10905. (let ((org-todo-heads (reverse org-todo-heads)))
  10906. (or (car (cdr (member head org-todo-heads)))
  10907. (car org-todo-heads))))
  10908. ((car (member arg org-todo-keywords-1)))
  10909. ((stringp arg)
  10910. (user-error "State `%s' not valid in this file" arg))
  10911. ((nth (1- (prefix-numeric-value arg))
  10912. org-todo-keywords-1))))
  10913. ((null member) (or head (car org-todo-keywords-1)))
  10914. ((equal this final-done-word) nil) ;-> make empty
  10915. ((null tail) nil) ;-> first entry
  10916. ((memq interpret '(type priority))
  10917. (if (eq this-command last-command)
  10918. (car tail)
  10919. (if (> (length tail) 0)
  10920. (or done-word (car org-done-keywords))
  10921. nil)))
  10922. (t
  10923. (car tail))))
  10924. (org-state (or
  10925. (run-hook-with-args-until-success
  10926. 'org-todo-get-default-hook org-state org-last-state)
  10927. org-state))
  10928. (next (if org-state (concat " " org-state " ") " "))
  10929. (change-plist (list :type 'todo-state-change :from this :to org-state
  10930. :position startpos))
  10931. dolog now-done-p)
  10932. (when org-blocker-hook
  10933. (let (org-blocked-by-checkboxes block-reason)
  10934. (setq org-last-todo-state-is-todo
  10935. (not (member this org-done-keywords)))
  10936. (unless (save-excursion
  10937. (save-match-data
  10938. (org-with-wide-buffer
  10939. (run-hook-with-args-until-failure
  10940. 'org-blocker-hook change-plist))))
  10941. (setq block-reason (if org-blocked-by-checkboxes
  10942. "contained checkboxes"
  10943. (format "\"%s\"" org-block-entry-blocking)))
  10944. (if (called-interactively-p 'interactive)
  10945. (user-error "TODO state change from %s to %s blocked (by %s)"
  10946. this org-state block-reason)
  10947. ;; Fail silently.
  10948. (message "TODO state change from %s to %s blocked (by %s)"
  10949. this org-state block-reason)
  10950. (throw 'exit nil)))))
  10951. (store-match-data match-data)
  10952. (replace-match next t t)
  10953. (cond ((equal this org-state)
  10954. (message "TODO state was already %s" (org-trim next)))
  10955. ((not (pos-visible-in-window-p hl-pos))
  10956. (message "TODO state changed to %s" (org-trim next))))
  10957. (unless head
  10958. (setq head (org-get-todo-sequence-head org-state)
  10959. ass (assoc head org-todo-kwd-alist)
  10960. interpret (nth 1 ass)
  10961. done-word (nth 3 ass)
  10962. final-done-word (nth 4 ass)))
  10963. (when (memq arg '(nextset previousset))
  10964. (message "Keyword-Set %d/%d: %s"
  10965. (- (length org-todo-sets) -1
  10966. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  10967. (length org-todo-sets)
  10968. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  10969. (setq org-last-todo-state-is-todo
  10970. (not (member org-state org-done-keywords)))
  10971. (setq now-done-p (and (member org-state org-done-keywords)
  10972. (not (member this org-done-keywords))))
  10973. (and logging (org-local-logging logging))
  10974. (when (and (or org-todo-log-states org-log-done)
  10975. (not (eq org-inhibit-logging t))
  10976. (not (memq arg '(nextset previousset))))
  10977. ;; We need to look at recording a time and note.
  10978. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  10979. (nth 2 (assoc this org-todo-log-states))))
  10980. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  10981. (setq dolog 'time))
  10982. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  10983. (and org-state
  10984. (member org-state org-not-done-keywords)
  10985. (not (member this org-not-done-keywords))))
  10986. ;; This is now a todo state and was not one before
  10987. ;; If there was a CLOSED time stamp, get rid of it.
  10988. (org-add-planning-info nil nil 'closed))
  10989. (when (and now-done-p org-log-done)
  10990. ;; It is now done, and it was not done before.
  10991. (org-add-planning-info 'closed (org-current-effective-time))
  10992. (when (and (not dolog) (eq 'note org-log-done))
  10993. (org-add-log-setup 'done org-state this 'note)))
  10994. (when (and org-state dolog)
  10995. ;; This is a non-nil state, and we need to log it.
  10996. (org-add-log-setup 'state org-state this dolog)))
  10997. ;; Fixup tag positioning.
  10998. (org-todo-trigger-tag-changes org-state)
  10999. (when org-auto-align-tags (org-align-tags))
  11000. (when org-provide-todo-statistics
  11001. (org-update-parent-todo-statistics))
  11002. (run-hooks 'org-after-todo-state-change-hook)
  11003. (when (and arg (not (member org-state org-done-keywords)))
  11004. (setq head (org-get-todo-sequence-head org-state)))
  11005. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11006. ;; Do we need to trigger a repeat?
  11007. (when now-done-p
  11008. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11009. ;; This is for the agenda, take a snapshot of the headline.
  11010. (save-match-data
  11011. (setq org-agenda-headline-snapshot-before-repeat
  11012. (org-get-heading))))
  11013. (org-auto-repeat-maybe org-state))
  11014. ;; Fixup cursor location if close to the keyword.
  11015. (when (and (outline-on-heading-p)
  11016. (not (bolp))
  11017. (save-excursion (beginning-of-line 1)
  11018. (looking-at org-todo-line-regexp))
  11019. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11020. (goto-char (or (match-end 2) (match-end 1)))
  11021. (and (looking-at " ") (just-one-space)))
  11022. (when org-trigger-hook
  11023. (save-excursion
  11024. (run-hook-with-args 'org-trigger-hook change-plist)))
  11025. (when commentp (org-toggle-comment))))))))
  11026. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11027. "Block turning an entry into a TODO, using the hierarchy.
  11028. This checks whether the current task should be blocked from state
  11029. changes. Such blocking occurs when:
  11030. 1. The task has children which are not all in a completed state.
  11031. 2. A task has a parent with the property :ORDERED:, and there
  11032. are siblings prior to the current task with incomplete
  11033. status.
  11034. 3. The parent of the task is blocked because it has siblings that should
  11035. be done first, or is child of a block grandparent TODO entry."
  11036. (if (not org-enforce-todo-dependencies)
  11037. t ; if locally turned off don't block
  11038. (catch 'dont-block
  11039. ;; If this is not a todo state change, or if this entry is already DONE,
  11040. ;; do not block
  11041. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11042. (member (plist-get change-plist :from)
  11043. (cons 'done org-done-keywords))
  11044. (member (plist-get change-plist :to)
  11045. (cons 'todo org-not-done-keywords))
  11046. (not (plist-get change-plist :to)))
  11047. (throw 'dont-block t))
  11048. ;; If this task has children, and any are undone, it's blocked
  11049. (save-excursion
  11050. (org-back-to-heading t)
  11051. (let ((this-level (funcall outline-level)))
  11052. (outline-next-heading)
  11053. (let ((child-level (funcall outline-level)))
  11054. (while (and (not (eobp))
  11055. (> child-level this-level))
  11056. ;; this todo has children, check whether they are all
  11057. ;; completed
  11058. (when (and (not (org-entry-is-done-p))
  11059. (org-entry-is-todo-p))
  11060. (setq org-block-entry-blocking (org-get-heading))
  11061. (throw 'dont-block nil))
  11062. (outline-next-heading)
  11063. (setq child-level (funcall outline-level))))))
  11064. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11065. ;; any previous siblings are undone, it's blocked
  11066. (save-excursion
  11067. (org-back-to-heading t)
  11068. (let* ((pos (point))
  11069. (parent-pos (and (org-up-heading-safe) (point)))
  11070. (case-fold-search nil))
  11071. (unless parent-pos (throw 'dont-block t)) ; no parent
  11072. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11073. (forward-line 1)
  11074. (re-search-forward org-not-done-heading-regexp pos t))
  11075. (setq org-block-entry-blocking (match-string 0))
  11076. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11077. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11078. (while t
  11079. (goto-char parent-pos)
  11080. (unless (looking-at org-not-done-heading-regexp)
  11081. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11082. (setq pos (point))
  11083. (setq parent-pos (and (org-up-heading-safe) (point)))
  11084. (unless parent-pos (throw 'dont-block t)) ; no parent
  11085. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11086. (forward-line 1)
  11087. (re-search-forward org-not-done-heading-regexp pos t)
  11088. (setq org-block-entry-blocking (org-get-heading)))
  11089. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11090. (defcustom org-track-ordered-property-with-tag nil
  11091. "Should the ORDERED property also be shown as a tag?
  11092. The ORDERED property decides if an entry should require subtasks to be
  11093. completed in sequence. Since a property is not very visible, setting
  11094. this option means that toggling the ORDERED property with the command
  11095. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11096. not relevant for the behavior, but it makes things more visible.
  11097. Note that toggling the tag with tags commands will not change the property
  11098. and therefore not influence behavior!
  11099. This can be t, meaning the tag ORDERED should be used, It can also be a
  11100. string to select a different tag for this task."
  11101. :group 'org-todo
  11102. :type '(choice
  11103. (const :tag "No tracking" nil)
  11104. (const :tag "Track with ORDERED tag" t)
  11105. (string :tag "Use other tag")))
  11106. (defun org-toggle-ordered-property ()
  11107. "Toggle the ORDERED property of the current entry.
  11108. For better visibility, you can track the value of this property with a tag.
  11109. See variable `org-track-ordered-property-with-tag'."
  11110. (interactive)
  11111. (let* ((t1 org-track-ordered-property-with-tag)
  11112. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11113. (save-excursion
  11114. (org-back-to-heading)
  11115. (if (org-entry-get nil "ORDERED")
  11116. (progn
  11117. (org-delete-property "ORDERED")
  11118. (and tag (org-toggle-tag tag 'off))
  11119. (message "Subtasks can be completed in arbitrary order"))
  11120. (org-entry-put nil "ORDERED" "t")
  11121. (and tag (org-toggle-tag tag 'on))
  11122. (message "Subtasks must be completed in sequence")))))
  11123. (defun org-block-todo-from-checkboxes (change-plist)
  11124. "Block turning an entry into a TODO, using checkboxes.
  11125. This checks whether the current task should be blocked from state
  11126. changes because there are unchecked boxes in this entry."
  11127. (if (not org-enforce-todo-checkbox-dependencies)
  11128. t ; if locally turned off don't block
  11129. (catch 'dont-block
  11130. ;; If this is not a todo state change, or if this entry is already DONE,
  11131. ;; do not block
  11132. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11133. (member (plist-get change-plist :from)
  11134. (cons 'done org-done-keywords))
  11135. (member (plist-get change-plist :to)
  11136. (cons 'todo org-not-done-keywords))
  11137. (not (plist-get change-plist :to)))
  11138. (throw 'dont-block t))
  11139. ;; If this task has checkboxes that are not checked, it's blocked
  11140. (save-excursion
  11141. (org-back-to-heading t)
  11142. (let ((beg (point)) end)
  11143. (outline-next-heading)
  11144. (setq end (point))
  11145. (goto-char beg)
  11146. (when (org-list-search-forward
  11147. (concat (org-item-beginning-re)
  11148. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11149. "\\[[- ]\\]")
  11150. end t)
  11151. (when (boundp 'org-blocked-by-checkboxes)
  11152. (setq org-blocked-by-checkboxes t))
  11153. (throw 'dont-block nil))))
  11154. t))) ; do not block
  11155. (defun org-entry-blocked-p ()
  11156. "Non-nil if entry at point is blocked."
  11157. (and (not (org-entry-get nil "NOBLOCKING"))
  11158. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11159. (not (run-hook-with-args-until-failure
  11160. 'org-blocker-hook
  11161. (list :type 'todo-state-change
  11162. :position (point)
  11163. :from 'todo
  11164. :to 'done)))))
  11165. (defun org-update-statistics-cookies (all)
  11166. "Update the statistics cookie, either from TODO or from checkboxes.
  11167. This should be called with the cursor in a line with a statistics
  11168. cookie. When called with a \\[universal-argument] prefix, update
  11169. all statistics cookies in the buffer."
  11170. (interactive "P")
  11171. (if all
  11172. (progn
  11173. (org-update-checkbox-count 'all)
  11174. (org-map-entries 'org-update-parent-todo-statistics))
  11175. (if (not (org-at-heading-p))
  11176. (org-update-checkbox-count)
  11177. (let ((pos (point-marker))
  11178. end l1 l2)
  11179. (ignore-errors (org-back-to-heading t))
  11180. (if (not (org-at-heading-p))
  11181. (org-update-checkbox-count)
  11182. (setq l1 (org-outline-level))
  11183. (setq end (save-excursion
  11184. (outline-next-heading)
  11185. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11186. (point)))
  11187. (if (and (save-excursion
  11188. (re-search-forward
  11189. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11190. (not (save-excursion (re-search-forward
  11191. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11192. (org-update-checkbox-count)
  11193. (if (and l2 (> l2 l1))
  11194. (progn
  11195. (goto-char end)
  11196. (org-update-parent-todo-statistics))
  11197. (goto-char pos)
  11198. (beginning-of-line 1)
  11199. (while (re-search-forward
  11200. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11201. (point-at-eol) t)
  11202. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11203. (goto-char pos)
  11204. (move-marker pos nil)))))
  11205. (defvar org-entry-property-inherited-from) ;; defined below
  11206. (defun org-update-parent-todo-statistics ()
  11207. "Update any statistics cookie in the parent of the current headline.
  11208. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11209. the entire subtree and this will travel up the hierarchy and update
  11210. statistics everywhere."
  11211. (let* ((prop (save-excursion (org-up-heading-safe)
  11212. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11213. (recursive (or (not org-hierarchical-todo-statistics)
  11214. (and prop (string-match "\\<recursive\\>" prop))))
  11215. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11216. 0))
  11217. (first t)
  11218. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11219. level ltoggle l1 new ndel
  11220. (cnt-all 0) (cnt-done 0) is-percent kwd
  11221. checkbox-beg cookie-present)
  11222. (catch 'exit
  11223. (save-excursion
  11224. (beginning-of-line 1)
  11225. (setq ltoggle (funcall outline-level))
  11226. ;; Three situations are to consider:
  11227. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11228. ;; to the top-level ancestor on the headline;
  11229. ;; 2. If parent has "recursive" property, repeat up to the
  11230. ;; headline setting that property, taking inheritance into
  11231. ;; account;
  11232. ;; 3. Else, move up to direct parent and proceed only once.
  11233. (while (and (setq level (org-up-heading-safe))
  11234. (or recursive first)
  11235. (>= (point) lim))
  11236. (setq first nil cookie-present nil)
  11237. (unless (and level
  11238. (not (string-match
  11239. "\\<checkbox\\>"
  11240. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11241. "")))))
  11242. (throw 'exit nil))
  11243. (while (re-search-forward box-re (point-at-eol) t)
  11244. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11245. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11246. (save-match-data
  11247. (unless (outline-next-heading) (throw 'exit nil))
  11248. (while (and (looking-at org-complex-heading-regexp)
  11249. (> (setq l1 (length (match-string 1))) level))
  11250. (setq kwd (and (or recursive (= l1 ltoggle))
  11251. (match-string 2)))
  11252. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11253. (and (eq org-provide-todo-statistics t)
  11254. (or (member kwd org-done-keywords)))
  11255. (and (listp org-provide-todo-statistics)
  11256. (stringp (car org-provide-todo-statistics))
  11257. (or (member kwd org-provide-todo-statistics)
  11258. (member kwd org-done-keywords)))
  11259. (and (listp org-provide-todo-statistics)
  11260. (listp (car org-provide-todo-statistics))
  11261. (or (member kwd (car org-provide-todo-statistics))
  11262. (and (member kwd org-done-keywords)
  11263. (member kwd (cadr org-provide-todo-statistics))))))
  11264. (setq cnt-all (1+ cnt-all))
  11265. (and (eq org-provide-todo-statistics t)
  11266. kwd
  11267. (setq cnt-all (1+ cnt-all))))
  11268. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11269. (member kwd org-done-keywords))
  11270. (and (listp org-provide-todo-statistics)
  11271. (listp (car org-provide-todo-statistics))
  11272. (member kwd org-done-keywords)
  11273. (member kwd (cadr org-provide-todo-statistics)))
  11274. (and (listp org-provide-todo-statistics)
  11275. (stringp (car org-provide-todo-statistics))
  11276. (member kwd org-done-keywords)))
  11277. (setq cnt-done (1+ cnt-done)))
  11278. (outline-next-heading)))
  11279. (setq new
  11280. (if is-percent
  11281. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11282. (max 1 cnt-all)))
  11283. (format "[%d/%d]" cnt-done cnt-all))
  11284. ndel (- (match-end 0) checkbox-beg))
  11285. (goto-char checkbox-beg)
  11286. (insert new)
  11287. (delete-region (point) (+ (point) ndel))
  11288. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11289. (when cookie-present
  11290. (run-hook-with-args 'org-after-todo-statistics-hook
  11291. cnt-done (- cnt-all cnt-done))))))
  11292. (run-hooks 'org-todo-statistics-hook)))
  11293. (defvar org-after-todo-statistics-hook nil
  11294. "Hook that is called after a TODO statistics cookie has been updated.
  11295. Each function is called with two arguments: the number of not-done entries
  11296. and the number of done entries.
  11297. For example, the following function, when added to this hook, will switch
  11298. an entry to DONE when all children are done, and back to TODO when new
  11299. entries are set to a TODO status. Note that this hook is only called
  11300. when there is a statistics cookie in the headline!
  11301. (defun org-summary-todo (n-done n-not-done)
  11302. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11303. (let (org-log-done org-log-states) ; turn off logging
  11304. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11305. ")
  11306. (defvar org-todo-statistics-hook nil
  11307. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11308. This hook runs even if there is no statistics cookie present, in which case
  11309. `org-after-todo-statistics-hook' would not run.")
  11310. (defun org-todo-trigger-tag-changes (state)
  11311. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11312. (let ((l org-todo-state-tags-triggers)
  11313. changes)
  11314. (when (or (not state) (equal state ""))
  11315. (setq changes (append changes (cdr (assoc "" l)))))
  11316. (when (and (stringp state) (> (length state) 0))
  11317. (setq changes (append changes (cdr (assoc state l)))))
  11318. (when (member state org-not-done-keywords)
  11319. (setq changes (append changes (cdr (assq 'todo l)))))
  11320. (when (member state org-done-keywords)
  11321. (setq changes (append changes (cdr (assq 'done l)))))
  11322. (dolist (c changes)
  11323. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11324. (defun org-local-logging (value)
  11325. "Get logging settings from a property VALUE."
  11326. ;; Directly set the variables, they are already local.
  11327. (setq org-log-done nil
  11328. org-log-repeat nil
  11329. org-todo-log-states nil)
  11330. (dolist (w (split-string value))
  11331. (let (a)
  11332. (cond
  11333. ((setq a (assoc w org-startup-options))
  11334. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11335. (set (nth 1 a) (nth 2 a))))
  11336. ((setq a (org-extract-log-state-settings w))
  11337. (and (member (car a) org-todo-keywords-1)
  11338. (push a org-todo-log-states)))))))
  11339. (defun org-get-todo-sequence-head (kwd)
  11340. "Return the head of the TODO sequence to which KWD belongs.
  11341. If KWD is not set, check if there is a text property remembering the
  11342. right sequence."
  11343. (let (p)
  11344. (cond
  11345. ((not kwd)
  11346. (or (get-text-property (point-at-bol) 'org-todo-head)
  11347. (progn
  11348. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11349. nil (point-at-eol)))
  11350. (get-text-property p 'org-todo-head))))
  11351. ((not (member kwd org-todo-keywords-1))
  11352. (car org-todo-keywords-1))
  11353. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11354. (defun org-fast-todo-selection ()
  11355. "Fast TODO keyword selection with single keys.
  11356. Returns the new TODO keyword, or nil if no state change should occur."
  11357. (let* ((fulltable org-todo-key-alist)
  11358. (done-keywords org-done-keywords) ;; needed for the faces.
  11359. (maxlen (apply 'max (mapcar
  11360. (lambda (x)
  11361. (if (stringp (car x)) (string-width (car x)) 0))
  11362. fulltable)))
  11363. (expert nil)
  11364. (fwidth (+ maxlen 3 1 3))
  11365. (ncol (/ (- (window-width) 4) fwidth))
  11366. tg cnt e c tbl
  11367. groups ingroup)
  11368. (save-excursion
  11369. (save-window-excursion
  11370. (if expert
  11371. (set-buffer (get-buffer-create " *Org todo*"))
  11372. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11373. (erase-buffer)
  11374. (setq-local org-done-keywords done-keywords)
  11375. (setq tbl fulltable cnt 0)
  11376. (while (setq e (pop tbl))
  11377. (cond
  11378. ((equal e '(:startgroup))
  11379. (push '() groups) (setq ingroup t)
  11380. (unless (= cnt 0)
  11381. (setq cnt 0)
  11382. (insert "\n"))
  11383. (insert "{ "))
  11384. ((equal e '(:endgroup))
  11385. (setq ingroup nil cnt 0)
  11386. (insert "}\n"))
  11387. ((equal e '(:newline))
  11388. (unless (= cnt 0)
  11389. (setq cnt 0)
  11390. (insert "\n")
  11391. (setq e (car tbl))
  11392. (while (equal (car tbl) '(:newline))
  11393. (insert "\n")
  11394. (setq tbl (cdr tbl)))))
  11395. (t
  11396. (setq tg (car e) c (cdr e))
  11397. (when ingroup (push tg (car groups)))
  11398. (setq tg (org-add-props tg nil 'face
  11399. (org-get-todo-face tg)))
  11400. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11401. (insert "[" c "] " tg (make-string
  11402. (- fwidth 4 (length tg)) ?\ ))
  11403. (when (= (setq cnt (1+ cnt)) ncol)
  11404. (insert "\n")
  11405. (when ingroup (insert " "))
  11406. (setq cnt 0)))))
  11407. (insert "\n")
  11408. (goto-char (point-min))
  11409. (unless expert (org-fit-window-to-buffer))
  11410. (message "[a-z..]:Set [SPC]:clear")
  11411. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11412. (cond
  11413. ((or (= c ?\C-g)
  11414. (and (= c ?q) (not (rassoc c fulltable))))
  11415. (setq quit-flag t))
  11416. ((= c ?\ ) nil)
  11417. ((setq e (rassoc c fulltable) tg (car e))
  11418. tg)
  11419. (t (setq quit-flag t)))))))
  11420. (defun org-entry-is-todo-p ()
  11421. (member (org-get-todo-state) org-not-done-keywords))
  11422. (defun org-entry-is-done-p ()
  11423. (member (org-get-todo-state) org-done-keywords))
  11424. (defun org-get-todo-state ()
  11425. "Return the TODO keyword of the current subtree."
  11426. (save-excursion
  11427. (org-back-to-heading t)
  11428. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11429. (match-end 2)
  11430. (match-string 2))))
  11431. (defun org-at-date-range-p (&optional inactive-ok)
  11432. "Non-nil if point is inside a date range.
  11433. When optional argument INACTIVE-OK is non-nil, also consider
  11434. inactive time ranges.
  11435. When this function returns a non-nil value, match data is set
  11436. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11437. on INACTIVE-OK."
  11438. (interactive)
  11439. (save-excursion
  11440. (catch 'exit
  11441. (let ((pos (point)))
  11442. (skip-chars-backward "^[<\r\n")
  11443. (skip-chars-backward "<[")
  11444. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11445. (>= (match-end 0) pos)
  11446. (throw 'exit t))
  11447. (skip-chars-backward "^<[\r\n")
  11448. (skip-chars-backward "<[")
  11449. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11450. (>= (match-end 0) pos)
  11451. (throw 'exit t)))
  11452. nil)))
  11453. (defun org-get-repeat (&optional timestamp)
  11454. "Check if there is a time-stamp with repeater in this entry.
  11455. Return the repeater, as a string, or nil. Also return nil when
  11456. this function is called before first heading.
  11457. When optional argument TIMESTAMP is a string, extract the
  11458. repeater from there instead."
  11459. (save-match-data
  11460. (cond (timestamp
  11461. (and (string-match org-repeat-re timestamp)
  11462. (match-string-no-properties 1 timestamp)))
  11463. ((org-before-first-heading-p) nil)
  11464. (t
  11465. (save-excursion
  11466. (org-back-to-heading t)
  11467. (let ((end (org-entry-end-position)))
  11468. (catch :repeat
  11469. (while (re-search-forward org-repeat-re end t)
  11470. (when (save-match-data (org-at-timestamp-p 'agenda))
  11471. (throw :repeat (match-string-no-properties 1)))))))))))
  11472. (defvar org-last-changed-timestamp)
  11473. (defvar org-last-inserted-timestamp)
  11474. (defvar org-log-post-message)
  11475. (defvar org-log-note-purpose)
  11476. (defvar org-log-note-how nil)
  11477. (defvar org-log-note-extra)
  11478. (defun org-auto-repeat-maybe (done-word)
  11479. "Check if the current headline contains a repeated time-stamp.
  11480. If yes, set TODO state back to what it was and change the base date
  11481. of repeating deadline/scheduled time stamps to new date.
  11482. This function is run automatically after each state change to a DONE state."
  11483. (let* ((repeat (org-get-repeat))
  11484. (aa (assoc org-last-state org-todo-kwd-alist))
  11485. (interpret (nth 1 aa))
  11486. (head (nth 2 aa))
  11487. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11488. (msg "Entry repeats: ")
  11489. (org-log-done nil)
  11490. (org-todo-log-states nil)
  11491. (end (copy-marker (org-entry-end-position))))
  11492. (unwind-protect
  11493. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11494. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11495. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11496. (and (stringp org-todo-repeat-to-state)
  11497. org-todo-repeat-to-state)
  11498. (and org-todo-repeat-to-state org-last-state))))
  11499. (org-todo (cond
  11500. ((and to-state (member to-state org-todo-keywords-1))
  11501. to-state)
  11502. ((eq interpret 'type) org-last-state)
  11503. (head)
  11504. (t 'none))))
  11505. (org-back-to-heading t)
  11506. (org-add-planning-info nil nil 'closed)
  11507. ;; When `org-log-repeat' is non-nil or entry contains
  11508. ;; a clock, set LAST_REPEAT property.
  11509. (when (or org-log-repeat
  11510. (catch :clock
  11511. (save-excursion
  11512. (while (re-search-forward org-clock-line-re end t)
  11513. (when (org-at-clock-log-p) (throw :clock t))))))
  11514. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11515. (org-time-stamp-format t t)
  11516. (current-time))))
  11517. (when org-log-repeat
  11518. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11519. (memq 'org-add-log-note post-command-hook))
  11520. ;; We are already setup for some record.
  11521. (when (eq org-log-repeat 'note)
  11522. ;; Make sure we take a note, not only a time stamp.
  11523. (setq org-log-note-how 'note))
  11524. ;; Set up for taking a record.
  11525. (org-add-log-setup 'state
  11526. (or done-word (car org-done-keywords))
  11527. org-last-state
  11528. org-log-repeat)))
  11529. (let ((planning-re (regexp-opt
  11530. (list org-scheduled-string org-deadline-string))))
  11531. (while (re-search-forward org-ts-regexp end t)
  11532. (let* ((ts (match-string 0))
  11533. (planning? (org-at-planning-p))
  11534. (type (if (not planning?) "Plain:"
  11535. (save-excursion
  11536. (re-search-backward
  11537. planning-re (line-beginning-position) t)
  11538. (match-string 0)))))
  11539. (cond
  11540. ;; Ignore fake time-stamps (e.g., within comments).
  11541. ((not (org-at-timestamp-p 'agenda)))
  11542. ;; Time-stamps without a repeater are usually
  11543. ;; skipped. However, a SCHEDULED time-stamp without
  11544. ;; one is removed, as they are no longer relevant.
  11545. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11546. ts))
  11547. (when (equal type org-scheduled-string)
  11548. (org-remove-timestamp-with-keyword type)))
  11549. (t
  11550. (let ((n (string-to-number (match-string 2 ts)))
  11551. (what (match-string 3 ts)))
  11552. (when (equal what "w") (setq n (* n 7) what "d"))
  11553. (when (and (equal what "h")
  11554. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11555. ts)))
  11556. (user-error
  11557. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11558. has been set"
  11559. n))
  11560. ;; Preparation, see if we need to modify the start
  11561. ;; date for the change.
  11562. (when (match-end 1)
  11563. (let ((time (save-match-data
  11564. (org-time-string-to-time ts))))
  11565. (cond
  11566. ((equal (match-string 1 ts) ".")
  11567. ;; Shift starting date to today
  11568. (org-timestamp-change
  11569. (- (org-today) (time-to-days time))
  11570. 'day))
  11571. ((equal (match-string 1 ts) "+")
  11572. (let ((nshiftmax 10)
  11573. (nshift 0))
  11574. (while (or (= nshift 0)
  11575. (not (time-less-p (current-time) time)))
  11576. (when (= (cl-incf nshift) nshiftmax)
  11577. (or (y-or-n-p
  11578. (format "%d repeater intervals were not \
  11579. enough to shift date past today. Continue? "
  11580. nshift))
  11581. (user-error "Abort")))
  11582. (org-timestamp-change n (cdr (assoc what whata)))
  11583. (org-in-regexp org-ts-regexp3)
  11584. (setq ts (match-string 1))
  11585. (setq time
  11586. (save-match-data
  11587. (org-time-string-to-time ts)))))
  11588. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11589. ;; Rematch, so that we have everything in place
  11590. ;; for the real shift.
  11591. (org-in-regexp org-ts-regexp3)
  11592. (setq ts (match-string 1))
  11593. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11594. ts)))))
  11595. (save-excursion
  11596. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11597. (setq msg
  11598. (concat
  11599. msg type " " org-last-changed-timestamp " "))))))))
  11600. (setq org-log-post-message msg)
  11601. (message "%s" msg))
  11602. (set-marker end nil))))
  11603. (defun org-show-todo-tree (arg)
  11604. "Make a compact tree which shows all headlines marked with TODO.
  11605. The tree will show the lines where the regexp matches, and all higher
  11606. headlines above the match.
  11607. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11608. With a numeric prefix N, construct a sparse tree for the Nth element
  11609. of `org-todo-keywords-1'."
  11610. (interactive "P")
  11611. (let ((case-fold-search nil)
  11612. (kwd-re
  11613. (cond ((null arg) org-not-done-regexp)
  11614. ((equal arg '(4))
  11615. (let ((kwd
  11616. (completing-read "Keyword (or KWD1|KWD2|...): "
  11617. (mapcar #'list org-todo-keywords-1))))
  11618. (concat "\\("
  11619. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11620. "\\)\\>")))
  11621. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11622. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11623. org-todo-keywords-1)))
  11624. (t (user-error "Invalid prefix argument: %s" arg)))))
  11625. (message "%d TODO entries found"
  11626. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11627. (defun org--deadline-or-schedule (arg type time)
  11628. "Insert DEADLINE or SCHEDULE information in current entry.
  11629. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11630. `org-schedule' for information about ARG and TIME arguments."
  11631. (let* ((deadline? (eq type 'deadline))
  11632. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11633. (log (if deadline? org-log-redeadline org-log-reschedule))
  11634. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11635. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11636. ;; Save repeater cookie from either TIME or current scheduled
  11637. ;; time stamp. We are going to insert it back at the end of
  11638. ;; the process.
  11639. (repeater (or (and (org-string-nw-p time)
  11640. ;; We use `org-repeat-re' because we need
  11641. ;; to tell the difference between a real
  11642. ;; repeater and a time delta, e.g. "+2d".
  11643. (string-match org-repeat-re time)
  11644. (match-string 1 time))
  11645. (and (org-string-nw-p old-date)
  11646. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11647. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11648. old-date)
  11649. (match-string 1 old-date)))))
  11650. (pcase arg
  11651. (`(4)
  11652. (if (not old-date)
  11653. (message (if deadline? "Entry had no deadline to remove"
  11654. "Entry was not scheduled"))
  11655. (when (and old-date log)
  11656. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11657. nil old-date log))
  11658. (org-remove-timestamp-with-keyword keyword)
  11659. (message (if deadline? "Entry no longer has a deadline."
  11660. "Entry is no longer scheduled."))))
  11661. (`(16)
  11662. (save-excursion
  11663. (org-back-to-heading t)
  11664. (let ((regexp (if deadline? org-deadline-time-regexp
  11665. org-scheduled-time-regexp)))
  11666. (if (not (re-search-forward regexp (line-end-position 2) t))
  11667. (user-error (if deadline? "No deadline information to update"
  11668. "No scheduled information to update"))
  11669. (let* ((rpl0 (match-string 1))
  11670. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11671. (msg (if deadline? "Warn starting from" "Delay until")))
  11672. (replace-match
  11673. (concat keyword
  11674. " <" rpl
  11675. (format " -%dd"
  11676. (abs (- (time-to-days
  11677. (save-match-data
  11678. (org-read-date
  11679. nil t nil msg old-date-time)))
  11680. (time-to-days old-date-time))))
  11681. ">") t t))))))
  11682. (_
  11683. (org-add-planning-info type time 'closed)
  11684. (when (and old-date
  11685. log
  11686. (not (equal old-date org-last-inserted-timestamp)))
  11687. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11688. org-last-inserted-timestamp
  11689. old-date
  11690. log))
  11691. (when repeater
  11692. (save-excursion
  11693. (org-back-to-heading t)
  11694. (when (re-search-forward
  11695. (concat keyword " " org-last-inserted-timestamp)
  11696. (line-end-position 2)
  11697. t)
  11698. (goto-char (1- (match-end 0)))
  11699. (insert " " repeater)
  11700. (setq org-last-inserted-timestamp
  11701. (concat (substring org-last-inserted-timestamp 0 -1)
  11702. " " repeater
  11703. (substring org-last-inserted-timestamp -1))))))
  11704. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11705. org-last-inserted-timestamp)))))
  11706. (defun org-deadline (arg &optional time)
  11707. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11708. With one universal prefix argument, remove any deadline from the item.
  11709. With two universal prefix arguments, prompt for a warning delay.
  11710. With argument TIME, set the deadline at the corresponding date. TIME
  11711. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11712. (interactive "P")
  11713. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11714. (org-map-entries
  11715. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11716. nil
  11717. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11718. 'region-start-level
  11719. 'region)
  11720. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11721. (org--deadline-or-schedule arg 'deadline time)))
  11722. (defun org-schedule (arg &optional time)
  11723. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  11724. With one universal prefix argument, remove any scheduling date from the item.
  11725. With two universal prefix arguments, prompt for a delay cookie.
  11726. With argument TIME, scheduled at the corresponding date. TIME can
  11727. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11728. (interactive "P")
  11729. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11730. (org-map-entries
  11731. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  11732. nil
  11733. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11734. 'region-start-level
  11735. 'region)
  11736. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11737. (org--deadline-or-schedule arg 'scheduled time)))
  11738. (defun org-get-scheduled-time (pom &optional inherit)
  11739. "Get the scheduled time as a time tuple, of a format suitable
  11740. for calling org-schedule with, or if there is no scheduling,
  11741. returns nil."
  11742. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  11743. (when time
  11744. (apply 'encode-time (org-parse-time-string time)))))
  11745. (defun org-get-deadline-time (pom &optional inherit)
  11746. "Get the deadline as a time tuple, of a format suitable for
  11747. calling org-deadline with, or if there is no scheduling, returns
  11748. nil."
  11749. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  11750. (when time
  11751. (apply 'encode-time (org-parse-time-string time)))))
  11752. (defun org-remove-timestamp-with-keyword (keyword)
  11753. "Remove all time stamps with KEYWORD in the current entry."
  11754. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  11755. beg)
  11756. (save-excursion
  11757. (org-back-to-heading t)
  11758. (setq beg (point))
  11759. (outline-next-heading)
  11760. (while (re-search-backward re beg t)
  11761. (replace-match "")
  11762. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  11763. (equal (char-before) ?\ ))
  11764. (backward-delete-char 1)
  11765. (when (string-match "^[ \t]*$" (buffer-substring
  11766. (point-at-bol) (point-at-eol)))
  11767. (delete-region (point-at-bol)
  11768. (min (point-max) (1+ (point-at-eol))))))))))
  11769. (defvar org-time-was-given) ; dynamically scoped parameter
  11770. (defvar org-end-time-was-given) ; dynamically scoped parameter
  11771. (defun org-at-planning-p ()
  11772. "Non-nil when point is on a planning info line."
  11773. ;; This is as accurate and faster than `org-element-at-point' since
  11774. ;; planning info location is fixed in the section.
  11775. (org-with-wide-buffer
  11776. (beginning-of-line)
  11777. (and (looking-at-p org-planning-line-re)
  11778. (eq (point)
  11779. (ignore-errors
  11780. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  11781. (org-back-to-heading t)
  11782. (org-with-limited-levels (org-back-to-heading t)))
  11783. (line-beginning-position 2))))))
  11784. (defun org-add-planning-info (what &optional time &rest remove)
  11785. "Insert new timestamp with keyword in the planning line.
  11786. WHAT indicates what kind of time stamp to add. It is a symbol
  11787. among `closed', `deadline', `scheduled' and nil. TIME indicates
  11788. the time to use. If none is given, the user is prompted for
  11789. a date. REMOVE indicates what kind of entries to remove. An old
  11790. WHAT entry will also be removed."
  11791. (let (org-time-was-given org-end-time-was-given default-time default-input)
  11792. (catch 'exit
  11793. (when (and (memq what '(scheduled deadline))
  11794. (or (not time)
  11795. (and (stringp time)
  11796. (string-match "^[-+]+[0-9]" time))))
  11797. ;; Try to get a default date/time from existing timestamp
  11798. (save-excursion
  11799. (org-back-to-heading t)
  11800. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  11801. (when (re-search-forward (if (eq what 'scheduled)
  11802. org-scheduled-time-regexp
  11803. org-deadline-time-regexp)
  11804. end t)
  11805. (setq ts (match-string 1)
  11806. default-time (apply 'encode-time (org-parse-time-string ts))
  11807. default-input (and ts (org-get-compact-tod ts)))))))
  11808. (when what
  11809. (setq time
  11810. (if (stringp time)
  11811. ;; This is a string (relative or absolute), set
  11812. ;; proper date.
  11813. (apply #'encode-time
  11814. (org-read-date-analyze
  11815. time default-time (decode-time default-time)))
  11816. ;; If necessary, get the time from the user
  11817. (or time (org-read-date nil 'to-time nil nil
  11818. default-time default-input)))))
  11819. (org-with-wide-buffer
  11820. (org-back-to-heading t)
  11821. (forward-line)
  11822. (unless (bolp) (insert "\n"))
  11823. (cond ((looking-at-p org-planning-line-re)
  11824. ;; Move to current indentation.
  11825. (skip-chars-forward " \t")
  11826. ;; Check if we have to remove something.
  11827. (dolist (type (if what (cons what remove) remove))
  11828. (save-excursion
  11829. (when (re-search-forward
  11830. (cl-case type
  11831. (closed org-closed-time-regexp)
  11832. (deadline org-deadline-time-regexp)
  11833. (scheduled org-scheduled-time-regexp)
  11834. (otherwise
  11835. (error "Invalid planning type: %s" type)))
  11836. (line-end-position) t)
  11837. ;; Delete until next keyword or end of line.
  11838. (delete-region
  11839. (match-beginning 0)
  11840. (if (re-search-forward org-keyword-time-not-clock-regexp
  11841. (line-end-position)
  11842. t)
  11843. (match-beginning 0)
  11844. (line-end-position))))))
  11845. ;; If there is nothing more to add and no more keyword
  11846. ;; is left, remove the line completely.
  11847. (if (and (looking-at-p "[ \t]*$") (not what))
  11848. (delete-region (line-beginning-position)
  11849. (line-beginning-position 2))
  11850. ;; If we removed last keyword, do not leave trailing
  11851. ;; white space at the end of line.
  11852. (let ((p (point)))
  11853. (save-excursion
  11854. (end-of-line)
  11855. (unless (= (skip-chars-backward " \t" p) 0)
  11856. (delete-region (point) (line-end-position)))))))
  11857. ((not what) (throw 'exit nil)) ; Nothing to do.
  11858. (t (insert-before-markers "\n")
  11859. (backward-char 1)
  11860. (when org-adapt-indentation
  11861. (indent-to-column (1+ (org-outline-level))))))
  11862. (when what
  11863. ;; Insert planning keyword.
  11864. (insert (cl-case what
  11865. (closed org-closed-string)
  11866. (deadline org-deadline-string)
  11867. (scheduled org-scheduled-string)
  11868. (otherwise (error "Invalid planning type: %s" what)))
  11869. " ")
  11870. ;; Insert associated timestamp.
  11871. (let ((ts (org-insert-time-stamp
  11872. time
  11873. (or org-time-was-given
  11874. (and (eq what 'closed) org-log-done-with-time))
  11875. (eq what 'closed)
  11876. nil nil (list org-end-time-was-given))))
  11877. (unless (eolp) (insert " "))
  11878. ts))))))
  11879. (defvar org-log-note-marker (make-marker)
  11880. "Marker pointing at the entry where the note is to be inserted.")
  11881. (defvar org-log-note-purpose nil)
  11882. (defvar org-log-note-state nil)
  11883. (defvar org-log-note-previous-state nil)
  11884. (defvar org-log-note-extra nil)
  11885. (defvar org-log-note-window-configuration nil)
  11886. (defvar org-log-note-return-to (make-marker))
  11887. (defvar org-log-note-effective-time nil
  11888. "Remembered current time so that dynamically scoped
  11889. `org-extend-today-until' affects timestamps in state change log")
  11890. (defvar org-log-post-message nil
  11891. "Message to be displayed after a log note has been stored.
  11892. The auto-repeater uses this.")
  11893. (defun org-add-note ()
  11894. "Add a note to the current entry.
  11895. This is done in the same way as adding a state change note."
  11896. (interactive)
  11897. (org-add-log-setup 'note))
  11898. (defun org-log-beginning (&optional create)
  11899. "Return expected start of log notes in current entry.
  11900. When optional argument CREATE is non-nil, the function creates
  11901. a drawer to store notes, if necessary. Returned position ignores
  11902. narrowing."
  11903. (org-with-wide-buffer
  11904. (let ((drawer (org-log-into-drawer)))
  11905. (cond
  11906. (drawer
  11907. (org-end-of-meta-data)
  11908. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  11909. (end (if (org-at-heading-p) (point)
  11910. (save-excursion (outline-next-heading) (point))))
  11911. (case-fold-search t))
  11912. (catch 'exit
  11913. ;; Try to find existing drawer.
  11914. (while (re-search-forward regexp end t)
  11915. (let ((element (org-element-at-point)))
  11916. (when (eq (org-element-type element) 'drawer)
  11917. (let ((cend (org-element-property :contents-end element)))
  11918. (when (and (not org-log-states-order-reversed) cend)
  11919. (goto-char cend)))
  11920. (throw 'exit nil))))
  11921. ;; No drawer found. Create one, if permitted.
  11922. (when create
  11923. (unless (bolp) (insert "\n"))
  11924. (let ((beg (point)))
  11925. (insert ":" drawer ":\n:END:\n")
  11926. (org-indent-region beg (point))
  11927. (org-flag-region
  11928. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  11929. (end-of-line -1)))))
  11930. (t
  11931. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  11932. (skip-chars-forward " \t\n")
  11933. (beginning-of-line)
  11934. (unless org-log-states-order-reversed
  11935. (org-skip-over-state-notes)
  11936. (skip-chars-backward " \t\n")
  11937. (forward-line)))))
  11938. (if (bolp) (point) (line-beginning-position 2))))
  11939. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  11940. "Set up the post command hook to take a note.
  11941. If this is about to TODO state change, the new state is expected in STATE.
  11942. HOW is an indicator what kind of note should be created.
  11943. EXTRA is additional text that will be inserted into the notes buffer."
  11944. (move-marker org-log-note-marker (point))
  11945. (setq org-log-note-purpose purpose
  11946. org-log-note-state state
  11947. org-log-note-previous-state prev-state
  11948. org-log-note-how how
  11949. org-log-note-extra extra
  11950. org-log-note-effective-time (org-current-effective-time))
  11951. (add-hook 'post-command-hook 'org-add-log-note 'append))
  11952. (defun org-skip-over-state-notes ()
  11953. "Skip past the list of State notes in an entry."
  11954. (when (ignore-errors (goto-char (org-in-item-p)))
  11955. (let* ((struct (org-list-struct))
  11956. (prevs (org-list-prevs-alist struct))
  11957. (regexp
  11958. (concat "[ \t]*- +"
  11959. (replace-regexp-in-string
  11960. " +" " +"
  11961. (org-replace-escapes
  11962. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  11963. `(("%d" . ,org-ts-regexp-inactive)
  11964. ("%D" . ,org-ts-regexp)
  11965. ("%s" . "\\(?:\"\\S-+\"\\)?")
  11966. ("%S" . "\\(?:\"\\S-+\"\\)?")
  11967. ("%t" . ,org-ts-regexp-inactive)
  11968. ("%T" . ,org-ts-regexp)
  11969. ("%u" . ".*?")
  11970. ("%U" . ".*?")))))))
  11971. (while (looking-at-p regexp)
  11972. (goto-char (or (org-list-get-next-item (point) struct prevs)
  11973. (org-list-get-item-end (point) struct)))))))
  11974. (defun org-add-log-note (&optional _purpose)
  11975. "Pop up a window for taking a note, and add this note later."
  11976. (remove-hook 'post-command-hook 'org-add-log-note)
  11977. (setq org-log-note-window-configuration (current-window-configuration))
  11978. (delete-other-windows)
  11979. (move-marker org-log-note-return-to (point))
  11980. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  11981. (goto-char org-log-note-marker)
  11982. (org-switch-to-buffer-other-window "*Org Note*")
  11983. (erase-buffer)
  11984. (if (memq org-log-note-how '(time state))
  11985. (org-store-log-note)
  11986. (let ((org-inhibit-startup t)) (org-mode))
  11987. (insert (format "# Insert note for %s.
  11988. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  11989. (cl-case org-log-note-purpose
  11990. (clock-out "stopped clock")
  11991. (done "closed todo item")
  11992. (reschedule "rescheduling")
  11993. (delschedule "no longer scheduled")
  11994. (redeadline "changing deadline")
  11995. (deldeadline "removing deadline")
  11996. (refile "refiling")
  11997. (note "this entry")
  11998. (state
  11999. (format "state change from \"%s\" to \"%s\""
  12000. (or org-log-note-previous-state "")
  12001. (or org-log-note-state "")))
  12002. (t (error "This should not happen")))))
  12003. (when org-log-note-extra (insert org-log-note-extra))
  12004. (setq-local org-finish-function 'org-store-log-note)
  12005. (run-hooks 'org-log-buffer-setup-hook)))
  12006. (defvar org-note-abort nil) ; dynamically scoped
  12007. (defun org-store-log-note ()
  12008. "Finish taking a log note, and insert it to where it belongs."
  12009. (let ((txt (prog1 (buffer-string)
  12010. (kill-buffer)))
  12011. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12012. lines)
  12013. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12014. (setq txt (replace-match "" t t txt)))
  12015. (when (string-match "\\s-+\\'" txt)
  12016. (setq txt (replace-match "" t t txt)))
  12017. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  12018. (when (org-string-nw-p note)
  12019. (setq note
  12020. (org-replace-escapes
  12021. note
  12022. (list (cons "%u" (user-login-name))
  12023. (cons "%U" user-full-name)
  12024. (cons "%t" (format-time-string
  12025. (org-time-stamp-format 'long 'inactive)
  12026. org-log-note-effective-time))
  12027. (cons "%T" (format-time-string
  12028. (org-time-stamp-format 'long nil)
  12029. org-log-note-effective-time))
  12030. (cons "%d" (format-time-string
  12031. (org-time-stamp-format nil 'inactive)
  12032. org-log-note-effective-time))
  12033. (cons "%D" (format-time-string
  12034. (org-time-stamp-format nil nil)
  12035. org-log-note-effective-time))
  12036. (cons "%s" (cond
  12037. ((not org-log-note-state) "")
  12038. ((string-match-p org-ts-regexp
  12039. org-log-note-state)
  12040. (format "\"[%s]\""
  12041. (substring org-log-note-state 1 -1)))
  12042. (t (format "\"%s\"" org-log-note-state))))
  12043. (cons "%S"
  12044. (cond
  12045. ((not org-log-note-previous-state) "")
  12046. ((string-match-p org-ts-regexp
  12047. org-log-note-previous-state)
  12048. (format "\"[%s]\""
  12049. (substring
  12050. org-log-note-previous-state 1 -1)))
  12051. (t (format "\"%s\""
  12052. org-log-note-previous-state)))))))
  12053. (when lines (setq note (concat note " \\\\")))
  12054. (push note lines))
  12055. (when (and lines (not org-note-abort))
  12056. (with-current-buffer (marker-buffer org-log-note-marker)
  12057. (org-with-wide-buffer
  12058. ;; Find location for the new note.
  12059. (goto-char org-log-note-marker)
  12060. (set-marker org-log-note-marker nil)
  12061. ;; Note associated to a clock is to be located right after
  12062. ;; the clock. Do not move point.
  12063. (unless (eq org-log-note-purpose 'clock-out)
  12064. (goto-char (org-log-beginning t)))
  12065. ;; Make sure point is at the beginning of an empty line.
  12066. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12067. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12068. ;; In an existing list, add a new item at the top level.
  12069. ;; Otherwise, indent line like a regular one.
  12070. (let ((itemp (org-in-item-p)))
  12071. (if itemp
  12072. (indent-line-to
  12073. (let ((struct (save-excursion
  12074. (goto-char itemp) (org-list-struct))))
  12075. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12076. (org-indent-line)))
  12077. (insert (org-list-bullet-string "-") (pop lines))
  12078. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12079. (dolist (line lines)
  12080. (insert "\n")
  12081. (indent-line-to ind)
  12082. (insert line)))
  12083. (message "Note stored")
  12084. (org-back-to-heading t))
  12085. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12086. ;; from within `org-add-log-note' because `buffer-undo-list'
  12087. ;; is then modified outside of `org-with-remote-undo'.
  12088. (when (eq this-command 'org-agenda-todo)
  12089. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12090. ;; Don't add undo information when called from `org-agenda-todo'.
  12091. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12092. (set-window-configuration org-log-note-window-configuration)
  12093. (with-current-buffer (marker-buffer org-log-note-return-to)
  12094. (goto-char org-log-note-return-to))
  12095. (move-marker org-log-note-return-to nil)
  12096. (when org-log-post-message (message "%s" org-log-post-message))))
  12097. (defun org-remove-empty-drawer-at (pos)
  12098. "Remove an empty drawer at position POS.
  12099. POS may also be a marker."
  12100. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12101. (org-with-wide-buffer
  12102. (goto-char pos)
  12103. (let ((drawer (org-element-at-point)))
  12104. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12105. (not (org-element-property :contents-begin drawer)))
  12106. (delete-region (org-element-property :begin drawer)
  12107. (progn (goto-char (org-element-property :end drawer))
  12108. (skip-chars-backward " \r\t\n")
  12109. (forward-line)
  12110. (point))))))))
  12111. (defvar org-ts-type nil)
  12112. (defun org-sparse-tree (&optional arg type)
  12113. "Create a sparse tree, prompt for the details.
  12114. This command can create sparse trees. You first need to select the type
  12115. of match used to create the tree:
  12116. t Show all TODO entries.
  12117. T Show entries with a specific TODO keyword.
  12118. m Show entries selected by a tags/property match.
  12119. p Enter a property name and its value (both with completion on existing
  12120. names/values) and show entries with that property.
  12121. r Show entries matching a regular expression (`/' can be used as well).
  12122. b Show deadlines and scheduled items before a date.
  12123. a Show deadlines and scheduled items after a date.
  12124. d Show deadlines due within `org-deadline-warning-days'.
  12125. D Show deadlines and scheduled items between a date range."
  12126. (interactive "P")
  12127. (setq type (or type org-sparse-tree-default-date-type))
  12128. (setq org-ts-type type)
  12129. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12130. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12131. \[c]ycle through date types: %s"
  12132. (cl-case type
  12133. (all "all timestamps")
  12134. (scheduled "only scheduled")
  12135. (deadline "only deadline")
  12136. (active "only active timestamps")
  12137. (inactive "only inactive timestamps")
  12138. (closed "with a closed time-stamp")
  12139. (otherwise "scheduled/deadline")))
  12140. (let ((answer (read-char-exclusive)))
  12141. (cl-case answer
  12142. (?c
  12143. (org-sparse-tree
  12144. arg
  12145. (cadr
  12146. (memq type '(nil all scheduled deadline active inactive closed)))))
  12147. (?d (call-interactively 'org-check-deadlines))
  12148. (?b (call-interactively 'org-check-before-date))
  12149. (?a (call-interactively 'org-check-after-date))
  12150. (?D (call-interactively 'org-check-dates-range))
  12151. (?t (call-interactively 'org-show-todo-tree))
  12152. (?T (org-show-todo-tree '(4)))
  12153. (?m (call-interactively 'org-match-sparse-tree))
  12154. ((?p ?P)
  12155. (let* ((kwd (completing-read
  12156. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12157. (value (completing-read
  12158. "Value: " (mapcar #'list (org-property-values kwd)))))
  12159. (unless (string-match "\\`{.*}\\'" value)
  12160. (setq value (concat "\"" value "\"")))
  12161. (org-match-sparse-tree arg (concat kwd "=" value))))
  12162. ((?r ?R ?/) (call-interactively 'org-occur))
  12163. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12164. (defvar-local org-occur-highlights nil
  12165. "List of overlays used for occur matches.")
  12166. (defvar-local org-occur-parameters nil
  12167. "Parameters of the active org-occur calls.
  12168. This is a list, each call to org-occur pushes as cons cell,
  12169. containing the regular expression and the callback, onto the list.
  12170. The list can contain several entries if `org-occur' has been called
  12171. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12172. will only contain one set of parameters. When the highlights are
  12173. removed (for example with `C-c C-c', or with the next edit (depending
  12174. on `org-remove-highlights-with-change'), this variable is emptied
  12175. as well.")
  12176. (defun org-occur (regexp &optional keep-previous callback)
  12177. "Make a compact tree which shows all matches of REGEXP.
  12178. The tree will show the lines where the regexp matches, and any other context
  12179. defined in `org-show-context-detail', which see.
  12180. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12181. done by a previous call to `org-occur' will be kept, to allow stacking of
  12182. calls to this command.
  12183. Optional argument CALLBACK can be a function of no argument. In this case,
  12184. it is called with point at the end of the match, match data being set
  12185. accordingly. Current match is shown only if the return value is non-nil.
  12186. The function must neither move point nor alter narrowing."
  12187. (interactive "sRegexp: \nP")
  12188. (when (equal regexp "")
  12189. (user-error "Regexp cannot be empty"))
  12190. (unless keep-previous
  12191. (org-remove-occur-highlights nil nil t))
  12192. (push (cons regexp callback) org-occur-parameters)
  12193. (let ((cnt 0))
  12194. (save-excursion
  12195. (goto-char (point-min))
  12196. (when (or (not keep-previous) ; do not want to keep
  12197. (not org-occur-highlights)) ; no previous matches
  12198. ;; hide everything
  12199. (org-overview))
  12200. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12201. (isearch-no-upper-case-p regexp t)
  12202. org-occur-case-fold-search)))
  12203. (while (re-search-forward regexp nil t)
  12204. (when (or (not callback)
  12205. (save-match-data (funcall callback)))
  12206. (setq cnt (1+ cnt))
  12207. (when org-highlight-sparse-tree-matches
  12208. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12209. (org-show-context 'occur-tree)))))
  12210. (when org-remove-highlights-with-change
  12211. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12212. nil 'local))
  12213. (unless org-sparse-tree-open-archived-trees
  12214. (org-hide-archived-subtrees (point-min) (point-max)))
  12215. (run-hooks 'org-occur-hook)
  12216. (when (called-interactively-p 'interactive)
  12217. (message "%d match(es) for regexp %s" cnt regexp))
  12218. cnt))
  12219. (defun org-occur-next-match (&optional n _reset)
  12220. "Function for `next-error-function' to find sparse tree matches.
  12221. N is the number of matches to move, when negative move backwards.
  12222. This function always goes back to the starting point when no
  12223. match is found."
  12224. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12225. (search-func (if (< n 0)
  12226. 'previous-single-char-property-change
  12227. 'next-single-char-property-change))
  12228. (n (abs n))
  12229. (pos (point))
  12230. p1)
  12231. (catch 'exit
  12232. (while (setq p1 (funcall search-func (point) 'org-type))
  12233. (when (equal p1 limit)
  12234. (goto-char pos)
  12235. (user-error "No more matches"))
  12236. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12237. (setq n (1- n))
  12238. (when (= n 0)
  12239. (goto-char p1)
  12240. (throw 'exit (point))))
  12241. (goto-char p1))
  12242. (goto-char p1)
  12243. (user-error "No more matches"))))
  12244. (defun org-highlight-new-match (beg end)
  12245. "Highlight from BEG to END and mark the highlight is an occur headline."
  12246. (let ((ov (make-overlay beg end)))
  12247. (overlay-put ov 'face 'secondary-selection)
  12248. (overlay-put ov 'org-type 'org-occur)
  12249. (push ov org-occur-highlights)))
  12250. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12251. "Remove the occur highlights from the buffer.
  12252. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12253. from the `before-change-functions' in the current buffer."
  12254. (interactive)
  12255. (unless org-inhibit-highlight-removal
  12256. (mapc #'delete-overlay org-occur-highlights)
  12257. (setq org-occur-highlights nil)
  12258. (setq org-occur-parameters nil)
  12259. (unless noremove
  12260. (remove-hook 'before-change-functions
  12261. 'org-remove-occur-highlights 'local))))
  12262. ;;;; Priorities
  12263. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12264. "Regular expression matching the priority indicator.")
  12265. (defvar org-remove-priority-next-time nil)
  12266. (defun org-priority-up ()
  12267. "Increase the priority of the current item."
  12268. (interactive)
  12269. (org-priority 'up))
  12270. (defun org-priority-down ()
  12271. "Decrease the priority of the current item."
  12272. (interactive)
  12273. (org-priority 'down))
  12274. (defun org-priority (&optional action show)
  12275. "Change the priority of an item.
  12276. When called interactively with a `\\[universal-argument]' prefix,
  12277. show the priority in the minibuffer instead of changing it.
  12278. When called programatically, ACTION can be `set', `up', `down',
  12279. or a character."
  12280. (interactive "P")
  12281. (when show
  12282. ;; Deprecation warning inserted for Org 9.2; once enough time has
  12283. ;; passed the SHOW argument should be removed.
  12284. (warn "`org-priority' called with deprecated SHOW argument"))
  12285. (if (equal action '(4))
  12286. (org-show-priority)
  12287. (unless org-enable-priority-commands
  12288. (user-error "Priority commands are disabled"))
  12289. (setq action (or action 'set))
  12290. (let (current new news have remove)
  12291. (save-excursion
  12292. (org-back-to-heading t)
  12293. (when (looking-at org-priority-regexp)
  12294. (setq current (string-to-char (match-string 2))
  12295. have t))
  12296. (cond
  12297. ((eq action 'remove)
  12298. (setq remove t new ?\ ))
  12299. ((or (eq action 'set)
  12300. (integerp action))
  12301. (if (not (eq action 'set))
  12302. (setq new action)
  12303. (message "Priority %c-%c, SPC to remove: "
  12304. org-highest-priority org-lowest-priority)
  12305. (save-match-data
  12306. (setq new (read-char-exclusive))))
  12307. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12308. (= (upcase org-lowest-priority) org-lowest-priority))
  12309. (setq new (upcase new)))
  12310. (cond ((equal new ?\s) (setq remove t))
  12311. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12312. (user-error "Priority must be between `%c' and `%c'"
  12313. org-highest-priority org-lowest-priority))))
  12314. ((eq action 'up)
  12315. (setq new (if have
  12316. (1- current) ; normal cycling
  12317. ;; last priority was empty
  12318. (if (eq last-command this-command)
  12319. org-lowest-priority ; wrap around empty to lowest
  12320. ;; default
  12321. (if org-priority-start-cycle-with-default
  12322. org-default-priority
  12323. (1- org-default-priority))))))
  12324. ((eq action 'down)
  12325. (setq new (if have
  12326. (1+ current) ; normal cycling
  12327. ;; last priority was empty
  12328. (if (eq last-command this-command)
  12329. org-highest-priority ; wrap around empty to highest
  12330. ;; default
  12331. (if org-priority-start-cycle-with-default
  12332. org-default-priority
  12333. (1+ org-default-priority))))))
  12334. (t (user-error "Invalid action")))
  12335. (when (or (< (upcase new) org-highest-priority)
  12336. (> (upcase new) org-lowest-priority))
  12337. (if (and (memq action '(up down))
  12338. (not have) (not (eq last-command this-command)))
  12339. ;; `new' is from default priority
  12340. (error
  12341. "The default can not be set, see `org-default-priority' why")
  12342. ;; normal cycling: `new' is beyond highest/lowest priority
  12343. ;; and is wrapped around to the empty priority
  12344. (setq remove t)))
  12345. (setq news (format "%c" new))
  12346. (if have
  12347. (if remove
  12348. (replace-match "" t t nil 1)
  12349. (replace-match news t t nil 2))
  12350. (if remove
  12351. (user-error "No priority cookie found in line")
  12352. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12353. (if (match-end 2)
  12354. (progn
  12355. (goto-char (match-end 2))
  12356. (insert " [#" news "]"))
  12357. (goto-char (match-beginning 3))
  12358. (insert "[#" news "] "))))
  12359. (org-align-tags))
  12360. (if remove
  12361. (message "Priority removed")
  12362. (message "Priority of current item set to %s" news)))))
  12363. (defun org-show-priority ()
  12364. "Show the priority of the current item.
  12365. This priority is composed of the main priority given with the [#A] cookies,
  12366. and by additional input from the age of a schedules or deadline entry."
  12367. (interactive)
  12368. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12369. (org-get-at-bol 'priority)
  12370. (save-excursion
  12371. (save-match-data
  12372. (beginning-of-line)
  12373. (and (looking-at org-heading-regexp)
  12374. (org-get-priority (match-string 0))))))))
  12375. (message "Priority is %d" (if pri pri -1000))))
  12376. (defun org-get-priority (s)
  12377. "Find priority cookie and return priority."
  12378. (save-match-data
  12379. (if (functionp org-get-priority-function)
  12380. (funcall org-get-priority-function)
  12381. (if (not (string-match org-priority-regexp s))
  12382. (* 1000 (- org-lowest-priority org-default-priority))
  12383. (* 1000 (- org-lowest-priority
  12384. (string-to-char (match-string 2 s))))))))
  12385. ;;;; Tags
  12386. (defvar org-agenda-archives-mode)
  12387. (defvar org-map-continue-from nil
  12388. "Position from where mapping should continue.
  12389. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12390. (defvar org-scanner-tags nil
  12391. "The current tag list while the tags scanner is running.")
  12392. (defvar org-trust-scanner-tags nil
  12393. "Should `org-get-tags' use the tags for the scanner.
  12394. This is for internal dynamical scoping only.
  12395. When this is non-nil, the function `org-get-tags' will return the value
  12396. of `org-scanner-tags' instead of building the list by itself. This
  12397. can lead to large speed-ups when the tags scanner is used in a file with
  12398. many entries, and when the list of tags is retrieved, for example to
  12399. obtain a list of properties. Building the tags list for each entry in such
  12400. a file becomes an N^2 operation - but with this variable set, it scales
  12401. as N.")
  12402. (defvar org--matcher-tags-todo-only nil)
  12403. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12404. "Scan headline tags with inheritance and produce output ACTION.
  12405. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12406. or `agenda' to produce an entry list for an agenda view. It can also be
  12407. a Lisp form or a function that should be called at each matched headline, in
  12408. this case the return value is a list of all return values from these calls.
  12409. MATCHER is a function accepting three arguments, returning
  12410. a non-nil value whenever a given set of tags qualifies a headline
  12411. for inclusion. See `org-make-tags-matcher' for more information.
  12412. As a special case, it can also be set to t (respectively nil) in
  12413. order to match all (respectively none) headline.
  12414. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12415. included in the output.
  12416. START-LEVEL can be a string with asterisks, reducing the scope to
  12417. headlines matching this string."
  12418. (require 'org-agenda)
  12419. (let* ((re (concat "^"
  12420. (if start-level
  12421. ;; Get the correct level to match
  12422. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12423. org-outline-regexp)
  12424. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  12425. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  12426. (props (list 'face 'default
  12427. 'done-face 'org-agenda-done
  12428. 'undone-face 'default
  12429. 'mouse-face 'highlight
  12430. 'org-not-done-regexp org-not-done-regexp
  12431. 'org-todo-regexp org-todo-regexp
  12432. 'org-complex-heading-regexp org-complex-heading-regexp
  12433. 'help-echo
  12434. (format "mouse-2 or RET jump to Org file %S"
  12435. (abbreviate-file-name
  12436. (or (buffer-file-name (buffer-base-buffer))
  12437. (buffer-name (buffer-base-buffer)))))))
  12438. (org-map-continue-from nil)
  12439. lspos tags tags-list
  12440. (tags-alist (list (cons 0 org-file-tags)))
  12441. (llast 0) rtn rtn1 level category i txt
  12442. todo marker entry priority
  12443. ts-date ts-date-type ts-date-pair)
  12444. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12445. (setq action (list 'lambda nil action)))
  12446. (save-excursion
  12447. (goto-char (point-min))
  12448. (when (eq action 'sparse-tree)
  12449. (org-overview)
  12450. (org-remove-occur-highlights))
  12451. (while (let (case-fold-search)
  12452. (re-search-forward re nil t))
  12453. (setq org-map-continue-from nil)
  12454. (catch :skip
  12455. ;; Ignore closing parts of inline tasks.
  12456. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  12457. (throw :skip t))
  12458. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  12459. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  12460. (goto-char (setq lspos (match-beginning 0)))
  12461. (setq level (org-reduced-level (org-outline-level))
  12462. category (org-get-category))
  12463. (when (eq action 'agenda)
  12464. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12465. ts-date (car ts-date-pair)
  12466. ts-date-type (cdr ts-date-pair)))
  12467. (setq i llast llast level)
  12468. ;; remove tag lists from same and sublevels
  12469. (while (>= i level)
  12470. (when (setq entry (assoc i tags-alist))
  12471. (setq tags-alist (delete entry tags-alist)))
  12472. (setq i (1- i)))
  12473. ;; add the next tags
  12474. (when tags
  12475. (setq tags (org-split-string tags ":")
  12476. tags-alist
  12477. (cons (cons level tags) tags-alist)))
  12478. ;; compile tags for current headline
  12479. (setq tags-list
  12480. (if org-use-tag-inheritance
  12481. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12482. tags)
  12483. org-scanner-tags tags-list)
  12484. (when org-use-tag-inheritance
  12485. (setcdr (car tags-alist)
  12486. (mapcar (lambda (x)
  12487. (setq x (copy-sequence x))
  12488. (org-add-prop-inherited x))
  12489. (cdar tags-alist))))
  12490. (when (and tags org-use-tag-inheritance
  12491. (or (not (eq t org-use-tag-inheritance))
  12492. org-tags-exclude-from-inheritance))
  12493. ;; Selective inheritance, remove uninherited ones.
  12494. (setcdr (car tags-alist)
  12495. (org-remove-uninherited-tags (cdar tags-alist))))
  12496. (when (and
  12497. ;; eval matcher only when the todo condition is OK
  12498. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12499. (if (functionp matcher)
  12500. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12501. (funcall matcher todo tags-list level))
  12502. matcher))
  12503. ;; Call the skipper, but return t if it does not
  12504. ;; skip, so that the `and' form continues evaluating.
  12505. (progn
  12506. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12507. t)
  12508. ;; Check if timestamps are deselecting this entry
  12509. (or (not todo-only)
  12510. (and (member todo org-todo-keywords-1)
  12511. (or (not org-agenda-tags-todo-honor-ignore-options)
  12512. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12513. ;; select this headline
  12514. (cond
  12515. ((eq action 'sparse-tree)
  12516. (and org-highlight-sparse-tree-matches
  12517. (org-get-heading) (match-end 0)
  12518. (org-highlight-new-match
  12519. (match-beginning 1) (match-end 1)))
  12520. (org-show-context 'tags-tree))
  12521. ((eq action 'agenda)
  12522. (setq txt (org-agenda-format-item
  12523. ""
  12524. (concat
  12525. (if (eq org-tags-match-list-sublevels 'indented)
  12526. (make-string (1- level) ?.) "")
  12527. (org-get-heading))
  12528. (make-string level ?\s)
  12529. category
  12530. tags-list)
  12531. priority (org-get-priority txt))
  12532. (goto-char lspos)
  12533. (setq marker (org-agenda-new-marker))
  12534. (org-add-props txt props
  12535. 'org-marker marker 'org-hd-marker marker 'org-category category
  12536. 'todo-state todo
  12537. 'ts-date ts-date
  12538. 'priority priority
  12539. 'type (concat "tagsmatch" ts-date-type))
  12540. (push txt rtn))
  12541. ((functionp action)
  12542. (setq org-map-continue-from nil)
  12543. (save-excursion
  12544. (setq rtn1 (funcall action))
  12545. (push rtn1 rtn)))
  12546. (t (user-error "Invalid action")))
  12547. ;; if we are to skip sublevels, jump to end of subtree
  12548. (unless org-tags-match-list-sublevels
  12549. (org-end-of-subtree t)
  12550. (backward-char 1))))
  12551. ;; Get the correct position from where to continue
  12552. (if org-map-continue-from
  12553. (goto-char org-map-continue-from)
  12554. (and (= (point) lspos) (end-of-line 1)))))
  12555. (when (and (eq action 'sparse-tree)
  12556. (not org-sparse-tree-open-archived-trees))
  12557. (org-hide-archived-subtrees (point-min) (point-max)))
  12558. (nreverse rtn)))
  12559. (defun org-remove-uninherited-tags (tags)
  12560. "Remove all tags that are not inherited from the list TAGS."
  12561. (cond
  12562. ((eq org-use-tag-inheritance t)
  12563. (if org-tags-exclude-from-inheritance
  12564. (org-delete-all org-tags-exclude-from-inheritance tags)
  12565. tags))
  12566. ((not org-use-tag-inheritance) nil)
  12567. ((stringp org-use-tag-inheritance)
  12568. (delq nil (mapcar
  12569. (lambda (x)
  12570. (if (and (string-match org-use-tag-inheritance x)
  12571. (not (member x org-tags-exclude-from-inheritance)))
  12572. x nil))
  12573. tags)))
  12574. ((listp org-use-tag-inheritance)
  12575. (delq nil (mapcar
  12576. (lambda (x)
  12577. (if (member x org-use-tag-inheritance) x nil))
  12578. tags)))))
  12579. (defun org-match-sparse-tree (&optional todo-only match)
  12580. "Create a sparse tree according to tags string MATCH.
  12581. MATCH is a string with match syntax. It can contain a selection
  12582. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12583. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12584. those. See the manual for details.
  12585. If optional argument TODO-ONLY is non-nil, only select lines that
  12586. are also TODO tasks."
  12587. (interactive "P")
  12588. (org-agenda-prepare-buffers (list (current-buffer)))
  12589. (let ((org--matcher-tags-todo-only todo-only))
  12590. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12591. org--matcher-tags-todo-only)))
  12592. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12593. (defvar org-cached-props nil)
  12594. (defun org-cached-entry-get (pom property)
  12595. (if (or (eq t org-use-property-inheritance)
  12596. (and (stringp org-use-property-inheritance)
  12597. (let ((case-fold-search t))
  12598. (string-match-p org-use-property-inheritance property)))
  12599. (and (listp org-use-property-inheritance)
  12600. (member-ignore-case property org-use-property-inheritance)))
  12601. ;; Caching is not possible, check it directly.
  12602. (org-entry-get pom property 'inherit)
  12603. ;; Get all properties, so we can do complicated checks easily.
  12604. (cdr (assoc-string property
  12605. (or org-cached-props
  12606. (setq org-cached-props (org-entry-properties pom)))
  12607. t))))
  12608. (defun org-global-tags-completion-table (&optional files)
  12609. "Return the list of all tags in all agenda buffer/files.
  12610. Optional FILES argument is a list of files which can be used
  12611. instead of the agenda files."
  12612. (save-excursion
  12613. (org-uniquify
  12614. (delq nil
  12615. (apply #'append
  12616. (mapcar
  12617. (lambda (file)
  12618. (set-buffer (find-file-noselect file))
  12619. (org--tag-add-to-alist
  12620. (org-get-buffer-tags)
  12621. (mapcar (lambda (x)
  12622. (and (stringp (car-safe x))
  12623. (list (car-safe x))))
  12624. org-current-tag-alist)))
  12625. (if (car-safe files) files
  12626. (org-agenda-files))))))))
  12627. (defun org-make-tags-matcher (match)
  12628. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12629. Returns a cons of the selection string MATCH and a function
  12630. implementing the matcher.
  12631. The matcher is to be called at an Org entry, with point on the
  12632. headline, and returns non-nil if the entry matches the selection
  12633. string MATCH. It must be called with three arguments: the TODO
  12634. keyword at the entry (or nil if none), the list of all tags at
  12635. the entry including inherited ones and the reduced level of the
  12636. headline. Additionally, the category of the entry, if any, must
  12637. be specified as the text property `org-category' on the headline.
  12638. This function sets the variable `org--matcher-tags-todo-only' to
  12639. a non-nil value if the matcher restricts matching to TODO
  12640. entries, otherwise it is not touched.
  12641. See also `org-scan-tags'."
  12642. (unless match
  12643. ;; Get a new match request, with completion against the global
  12644. ;; tags table and the local tags in current buffer.
  12645. (let ((org-last-tags-completion-table
  12646. (org--tag-add-to-alist
  12647. (org-get-buffer-tags)
  12648. (org-global-tags-completion-table))))
  12649. (setq match
  12650. (completing-read
  12651. "Match: "
  12652. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12653. (let ((match0 match)
  12654. (re (concat
  12655. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  12656. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  12657. "\\([<>=]\\{1,2\\}\\)"
  12658. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  12659. "\\|" org-tag-re "\\)"))
  12660. (start 0)
  12661. tagsmatch todomatch tagsmatcher todomatcher)
  12662. ;; Expand group tags.
  12663. (setq match (org-tags-expand match))
  12664. ;; Check if there is a TODO part of this match, which would be the
  12665. ;; part after a "/". To make sure that this slash is not part of
  12666. ;; a property value to be matched against, we also check that
  12667. ;; there is no / after that slash. First, find the last slash.
  12668. (let ((s 0))
  12669. (while (string-match "/+" match s)
  12670. (setq start (match-beginning 0))
  12671. (setq s (match-end 0))))
  12672. (if (and (string-match "/+" match start)
  12673. (not (string-match-p "\"" match start)))
  12674. ;; Match contains also a TODO-matching request.
  12675. (progn
  12676. (setq tagsmatch (substring match 0 (match-beginning 0)))
  12677. (setq todomatch (substring match (match-end 0)))
  12678. (when (string-prefix-p "!" todomatch)
  12679. (setq org--matcher-tags-todo-only t)
  12680. (setq todomatch (substring todomatch 1)))
  12681. (when (string-match "\\`\\s-*\\'" todomatch)
  12682. (setq todomatch nil)))
  12683. ;; Only matching tags.
  12684. (setq tagsmatch match)
  12685. (setq todomatch nil))
  12686. ;; Make the tags matcher.
  12687. (when (org-string-nw-p tagsmatch)
  12688. (let ((orlist nil)
  12689. (orterms (org-split-string tagsmatch "|"))
  12690. term)
  12691. (while (setq term (pop orterms))
  12692. (while (and (equal (substring term -1) "\\") orterms)
  12693. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  12694. (while (string-match re term)
  12695. (let* ((rest (substring term (match-end 0)))
  12696. (minus (and (match-end 1)
  12697. (equal (match-string 1 term) "-")))
  12698. (tag (save-match-data
  12699. (replace-regexp-in-string
  12700. "\\\\-" "-" (match-string 2 term))))
  12701. (regexp (eq (string-to-char tag) ?{))
  12702. (levelp (match-end 4))
  12703. (propp (match-end 5))
  12704. (mm
  12705. (cond
  12706. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  12707. (levelp
  12708. `(,(org-op-to-function (match-string 3 term))
  12709. level
  12710. ,(string-to-number (match-string 4 term))))
  12711. (propp
  12712. (let* ((gv (pcase (upcase (match-string 5 term))
  12713. ("CATEGORY"
  12714. '(get-text-property (point) 'org-category))
  12715. ("TODO" 'todo)
  12716. (p `(org-cached-entry-get nil ,p))))
  12717. (pv (match-string 7 term))
  12718. (regexp (eq (string-to-char pv) ?{))
  12719. (strp (eq (string-to-char pv) ?\"))
  12720. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  12721. (po (org-op-to-function (match-string 6 term)
  12722. (if timep 'time strp))))
  12723. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  12724. (when timep (setq pv (org-matcher-time pv)))
  12725. (cond ((and regexp (eq po '/=))
  12726. `(not (string-match ,pv (or ,gv ""))))
  12727. (regexp `(string-match ,pv (or ,gv "")))
  12728. (strp `(,po (or ,gv "") ,pv))
  12729. (t
  12730. `(,po
  12731. (string-to-number (or ,gv ""))
  12732. ,(string-to-number pv))))))
  12733. (t `(member ,tag tags-list)))))
  12734. (push (if minus `(not ,mm) mm) tagsmatcher)
  12735. (setq term rest)))
  12736. (push `(and ,@tagsmatcher) orlist)
  12737. (setq tagsmatcher nil))
  12738. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  12739. ;; Make the TODO matcher.
  12740. (when (org-string-nw-p todomatch)
  12741. (let ((orlist nil))
  12742. (dolist (term (org-split-string todomatch "|"))
  12743. (while (string-match re term)
  12744. (let* ((minus (and (match-end 1)
  12745. (equal (match-string 1 term) "-")))
  12746. (kwd (match-string 2 term))
  12747. (regexp (eq (string-to-char kwd) ?{))
  12748. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  12749. `(equal todo ,kwd))))
  12750. (push (if minus `(not ,mm) mm) todomatcher))
  12751. (setq term (substring term (match-end 0))))
  12752. (push (if (> (length todomatcher) 1)
  12753. (cons 'and todomatcher)
  12754. (car todomatcher))
  12755. orlist)
  12756. (setq todomatcher nil))
  12757. (setq todomatcher (cons 'or orlist))))
  12758. ;; Return the string and function of the matcher. If no
  12759. ;; tags-specific or todo-specific matcher exists, match
  12760. ;; everything.
  12761. (let ((matcher (if (and tagsmatcher todomatcher)
  12762. `(and ,tagsmatcher ,todomatcher)
  12763. (or tagsmatcher todomatcher t))))
  12764. (when org--matcher-tags-todo-only
  12765. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  12766. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  12767. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  12768. "Expand group tags in MATCH.
  12769. This replaces every group tag in MATCH with a regexp tag search.
  12770. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  12771. will be replaced like this:
  12772. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12773. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12774. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12775. Replacing by a regexp preserves the structure of the match.
  12776. E.g., this expansion
  12777. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  12778. will match anything tagged with \"Lab\" and \"Home\", or tagged
  12779. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  12780. A group tag in MATCH can contain regular expressions of its own.
  12781. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  12782. will be replaced like this:
  12783. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  12784. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  12785. assumed to be a single group tag, and the function will return
  12786. the list of tags in this group.
  12787. When DOWNCASE is non-nil, expand downcased TAGS."
  12788. (if org-group-tags
  12789. (let* ((case-fold-search t)
  12790. (stable org-mode-syntax-table)
  12791. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  12792. (taggroups (if downcased
  12793. (mapcar (lambda (tg) (mapcar #'downcase tg))
  12794. taggroups)
  12795. taggroups))
  12796. (taggroups-keys (mapcar #'car taggroups))
  12797. (return-match (if downcased (downcase match) match))
  12798. (count 0)
  12799. (work-already-expanded tags-already-expanded)
  12800. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  12801. ;; @ and _ are allowed as word-components in tags.
  12802. (modify-syntax-entry ?@ "w" stable)
  12803. (modify-syntax-entry ?_ "w" stable)
  12804. ;; Temporarily replace regexp-expressions in the match-expression.
  12805. (while (string-match "{.+?}" return-match)
  12806. (cl-incf count)
  12807. (push (match-string 0 return-match) regexps-in-match)
  12808. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  12809. (while (and taggroups-keys
  12810. (with-syntax-table stable
  12811. (string-match
  12812. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  12813. (regexp-opt taggroups-keys) "\\>\\)")
  12814. return-match)))
  12815. (let* ((dir (match-string 1 return-match))
  12816. (tag (match-string 2 return-match))
  12817. (tag (if downcased (downcase tag) tag)))
  12818. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  12819. (member tag tags-already-expanded))
  12820. (setq tags-in-group (assoc tag taggroups))
  12821. (push tag work-already-expanded)
  12822. ;; Recursively expand each tag in the group, if the tag hasn't
  12823. ;; already been expanded. Restore the match-data after all recursive calls.
  12824. (save-match-data
  12825. (let (tags-expanded)
  12826. (dolist (x (cdr tags-in-group))
  12827. (if (and (member x taggroups-keys)
  12828. (not (member x work-already-expanded)))
  12829. (setq tags-expanded
  12830. (delete-dups
  12831. (append
  12832. (org-tags-expand x t downcased
  12833. work-already-expanded)
  12834. tags-expanded)))
  12835. (setq tags-expanded
  12836. (append (list x) tags-expanded)))
  12837. (setq work-already-expanded
  12838. (delete-dups
  12839. (append tags-expanded
  12840. work-already-expanded))))
  12841. (setq tags-in-group
  12842. (delete-dups (cons (car tags-in-group)
  12843. tags-expanded)))))
  12844. ;; Filter tag-regexps from tags.
  12845. (setq regexp-in-group-escaped
  12846. (delq nil (mapcar (lambda (x)
  12847. (if (stringp x)
  12848. (and (equal "{" (substring x 0 1))
  12849. (equal "}" (substring x -1))
  12850. x)
  12851. x))
  12852. tags-in-group))
  12853. regexp-in-group
  12854. (mapcar (lambda (x)
  12855. (substring x 1 -1))
  12856. regexp-in-group-escaped)
  12857. tags-in-group
  12858. (delq nil (mapcar (lambda (x)
  12859. (if (stringp x)
  12860. (and (not (equal "{" (substring x 0 1)))
  12861. (not (equal "}" (substring x -1)))
  12862. x)
  12863. x))
  12864. tags-in-group)))
  12865. ;; If single-as-list, do no more in the while-loop.
  12866. (if (not single-as-list)
  12867. (progn
  12868. (when regexp-in-group
  12869. (setq regexp-in-group
  12870. (concat "\\|"
  12871. (mapconcat 'identity regexp-in-group
  12872. "\\|"))))
  12873. (setq tags-in-group
  12874. (concat dir
  12875. "{\\<"
  12876. (regexp-opt tags-in-group)
  12877. "\\>"
  12878. regexp-in-group
  12879. "}"))
  12880. (when (stringp tags-in-group)
  12881. (org-add-props tags-in-group '(grouptag t)))
  12882. (setq return-match
  12883. (replace-match tags-in-group t t return-match)))
  12884. (setq tags-in-group
  12885. (append regexp-in-group-escaped tags-in-group))))
  12886. (setq taggroups-keys (delete tag taggroups-keys))))
  12887. ;; Add the regular expressions back into the match-expression again.
  12888. (while regexps-in-match
  12889. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  12890. (pop regexps-in-match)
  12891. return-match t t))
  12892. (cl-decf count))
  12893. (if single-as-list
  12894. (if tags-in-group tags-in-group (list return-match))
  12895. return-match))
  12896. (if single-as-list
  12897. (list (if downcased (downcase match) match))
  12898. match)))
  12899. (defun org-op-to-function (op &optional stringp)
  12900. "Turn an operator into the appropriate function."
  12901. (setq op
  12902. (cond
  12903. ((equal op "<" ) '(< org-string< org-time<))
  12904. ((equal op ">" ) '(> org-string> org-time>))
  12905. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  12906. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  12907. ((member op '("=" "==")) '(= string= org-time=))
  12908. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  12909. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  12910. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  12911. (defvar org-tags-overlay (make-overlay 1 1))
  12912. (delete-overlay org-tags-overlay)
  12913. (defun org-add-prop-inherited (s)
  12914. (add-text-properties 0 (length s) '(inherited t) s)
  12915. s)
  12916. (defun org-toggle-tag (tag &optional onoff)
  12917. "Toggle the tag TAG for the current line.
  12918. If ONOFF is `on' or `off', don't toggle but set to this state."
  12919. (save-excursion
  12920. (org-back-to-heading t)
  12921. (let ((current
  12922. ;; Reverse the tags list so any new tag is appended to the
  12923. ;; current list of tags.
  12924. (nreverse (org-get-tags nil t)))
  12925. res)
  12926. (pcase onoff
  12927. (`off (setq current (delete tag current)))
  12928. ((or `on (guard (not (member tag current))))
  12929. (setq res t)
  12930. (cl-pushnew tag current :test #'equal))
  12931. (_ (setq current (delete tag current))))
  12932. (org-set-tags (nreverse current))
  12933. res)))
  12934. (defun org--align-tags-here (to-col)
  12935. "Align tags on the current headline to TO-COL.
  12936. Assume point is on a headline. Preserve point when aligning
  12937. tags."
  12938. (when (and (org-match-line org-tag-line-re)
  12939. (/= to-col (save-excursion ;nothing to do?
  12940. (goto-char (match-beginning 1)) (current-column))))
  12941. (let* ((shift (if (>= to-col 0) to-col
  12942. (- (abs to-col) (string-width (match-string 1)))))
  12943. (origin (point-marker))
  12944. (column (current-column))
  12945. (tags-start (match-beginning 1))
  12946. (blank-start (save-excursion
  12947. (goto-char tags-start)
  12948. (skip-chars-backward " \t")
  12949. (point)))
  12950. (in-blank? (and (> origin blank-start)
  12951. (<= origin tags-start))))
  12952. (delete-region blank-start tags-start)
  12953. (goto-char blank-start)
  12954. (let ((indent-tabs-mode nil)) (indent-to shift 1))
  12955. ;; Try to move back to original position. If point was in the
  12956. ;; blanks before the tags, ORIGIN marker is of no use because it
  12957. ;; now points to BLANK-START. Use COLUMN instead.
  12958. (if in-blank? (org-move-to-column column)
  12959. (goto-char origin)))))
  12960. (defun org-set-tags-command (&optional arg)
  12961. "Set the tags for the current visible entry.
  12962. When called with `\\[universal-argument]' prefix argument ARG, \
  12963. realign all tags
  12964. in the current buffer. If a region is active, set tags for
  12965. all headlines in the region.
  12966. This function is for interactive use only;
  12967. in Lisp code use `org-set-tags' instead."
  12968. (interactive "P")
  12969. (cond
  12970. (arg (org-align-tags t))
  12971. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12972. ;; Disable `org-loop-over-headlines-in-active-region' for
  12973. ;; successive calls.
  12974. (let (org-loop-over-headlines-in-active-region)
  12975. (org-map-entries
  12976. #'org-set-tags-command
  12977. nil
  12978. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12979. 'region-start-level
  12980. 'region)
  12981. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  12982. (t
  12983. (save-excursion
  12984. (org-back-to-heading)
  12985. (let* ((all-tags (org-get-tags))
  12986. (table (setq org-last-tags-completion-table
  12987. (org--tag-add-to-alist
  12988. (and org-complete-tags-always-offer-all-agenda-tags
  12989. (org-global-tags-completion-table
  12990. (org-agenda-files)))
  12991. (or org-current-tag-alist (org-get-buffer-tags)))))
  12992. (current-tags
  12993. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  12994. all-tags))
  12995. (inherited-tags
  12996. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  12997. all-tags))
  12998. (tags
  12999. (replace-regexp-in-string
  13000. ;; Ignore all forbidden characters in tags.
  13001. "[^[:alnum:]_@#%]+" ":"
  13002. (if (or (eq t org-use-fast-tag-selection)
  13003. (and org-use-fast-tag-selection
  13004. (delq nil (mapcar #'cdr table))))
  13005. (org-fast-tag-selection
  13006. current-tags
  13007. inherited-tags
  13008. table
  13009. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  13010. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  13011. (org-trim (completing-read
  13012. "Tags: "
  13013. #'org-tags-completion-function
  13014. nil nil (org-make-tag-string current-tags)
  13015. 'org-tags-history)))))))
  13016. (org-set-tags tags))))))
  13017. (defun org-align-tags (&optional all)
  13018. "Align tags in current entry.
  13019. When optional argument ALL is non-nil, align all tags in the
  13020. visible part of the buffer."
  13021. (let ((get-indent-column
  13022. (lambda ()
  13023. (let ((offset (if (bound-and-true-p org-indent-mode)
  13024. (* (1- org-indent-indentation-per-level)
  13025. (1- (org-current-level)))
  13026. 0)))
  13027. (+ org-tags-column
  13028. (if (> org-tags-column 0) (- offset) offset))))))
  13029. (if (and (not all) (org-at-heading-p))
  13030. (org--align-tags-here (funcall get-indent-column))
  13031. (save-excursion
  13032. (if all
  13033. (while (re-search-forward org-tag-line-re nil t)
  13034. (org--align-tags-here (funcall get-indent-column)))
  13035. (org-back-to-heading t)
  13036. (org--align-tags-here (funcall get-indent-column)))))))
  13037. (defun org-set-tags (tags)
  13038. "Set the tags of the current entry to TAGS, replacing current tags.
  13039. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  13040. If TAGS is nil or the empty string, all tags are removed.
  13041. This function assumes point is on a headline."
  13042. (org-with-wide-buffer
  13043. (let ((tags (pcase tags
  13044. ((pred listp) tags)
  13045. ((pred stringp) (split-string (org-trim tags) ":" t))
  13046. (_ (error "Invalid tag specification: %S" tags))))
  13047. (old-tags (org-get-tags nil t))
  13048. (change-flag nil))
  13049. (when (functionp org-tags-sort-function)
  13050. (setq tags (sort tags org-tags-sort-function)))
  13051. (unless (equal tags old-tags) (setq change-flag t))
  13052. ;; Delete previous tags and any trailing white space.
  13053. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  13054. (line-end-position)))
  13055. (skip-chars-backward " \t")
  13056. (delete-region (point) (line-end-position))
  13057. ;; Deleting white spaces may break an otherwise empty headline.
  13058. ;; Re-introduce one space in this case.
  13059. (unless (org-at-heading-p) (insert " "))
  13060. (when tags
  13061. (save-excursion (insert " " (org-make-tag-string tags)))
  13062. ;; When text is being inserted on an invisible region
  13063. ;; boundary, it can be inadvertently sucked into
  13064. ;; invisibility.
  13065. (unless (org-invisible-p (line-beginning-position))
  13066. (org-flag-region (point) (line-end-position) nil 'outline)))
  13067. ;; Align tags, if any.
  13068. (when tags (org-align-tags))
  13069. (when change-flag (run-hooks 'org-after-tags-change-hook)))))
  13070. (defun org-change-tag-in-region (beg end tag off)
  13071. "Add or remove TAG for each entry in the region.
  13072. This works in the agenda, and also in an Org buffer."
  13073. (interactive
  13074. (list (region-beginning) (region-end)
  13075. (let ((org-last-tags-completion-table
  13076. (if (derived-mode-p 'org-mode)
  13077. (org--tag-add-to-alist
  13078. (org-get-buffer-tags)
  13079. (org-global-tags-completion-table))
  13080. (org-global-tags-completion-table))))
  13081. (completing-read
  13082. "Tag: " 'org-tags-completion-function nil nil nil
  13083. 'org-tags-history))
  13084. (progn
  13085. (message "[s]et or [r]emove? ")
  13086. (equal (read-char-exclusive) ?r))))
  13087. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13088. (let ((agendap (equal major-mode 'org-agenda-mode))
  13089. l1 l2 m buf pos newhead (cnt 0))
  13090. (goto-char end)
  13091. (setq l2 (1- (org-current-line)))
  13092. (goto-char beg)
  13093. (setq l1 (org-current-line))
  13094. (cl-loop for l from l1 to l2 do
  13095. (org-goto-line l)
  13096. (setq m (get-text-property (point) 'org-hd-marker))
  13097. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13098. (and agendap m))
  13099. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13100. pos (if agendap m (point)))
  13101. (with-current-buffer buf
  13102. (save-excursion
  13103. (save-restriction
  13104. (goto-char pos)
  13105. (setq cnt (1+ cnt))
  13106. (org-toggle-tag tag (if off 'off 'on))
  13107. (setq newhead (org-get-heading)))))
  13108. (and agendap (org-agenda-change-all-lines newhead m))))
  13109. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13110. (defun org-tags-completion-function (string _predicate &optional flag)
  13111. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13112. (confirm (lambda (x) (stringp (car x)))))
  13113. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13114. (setq s1 (match-string 1 string)
  13115. s2 (match-string 2 string))
  13116. (setq s1 "" s2 string))
  13117. (cond
  13118. ((eq flag nil)
  13119. ;; try completion
  13120. (setq rtn (try-completion s2 ctable confirm))
  13121. (when (stringp rtn)
  13122. (setq rtn
  13123. (concat s1 s2 (substring rtn (length s2))
  13124. (if (and org-add-colon-after-tag-completion
  13125. (assoc rtn ctable))
  13126. ":" ""))))
  13127. rtn)
  13128. ((eq flag t)
  13129. ;; all-completions
  13130. (all-completions s2 ctable confirm))
  13131. ((eq flag 'lambda)
  13132. ;; exact match?
  13133. (assoc s2 ctable)))))
  13134. (defun org-fast-tag-insert (kwd tags face &optional end)
  13135. "Insert KWD, and the TAGS, the latter with face FACE.
  13136. Also insert END."
  13137. (insert (format "%-12s" (concat kwd ":"))
  13138. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13139. (or end "")))
  13140. (defun org-fast-tag-show-exit (flag)
  13141. (save-excursion
  13142. (org-goto-line 3)
  13143. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13144. (replace-match ""))
  13145. (when flag
  13146. (end-of-line 1)
  13147. (org-move-to-column (- (window-width) 19) t)
  13148. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13149. (defun org-set-current-tags-overlay (current prefix)
  13150. "Add an overlay to CURRENT tag with PREFIX."
  13151. (let ((s (org-make-tag-string current)))
  13152. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13153. (org-overlay-display org-tags-overlay (concat prefix s))))
  13154. (defvar org-last-tag-selection-key nil)
  13155. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13156. "Fast tag selection with single keys.
  13157. CURRENT is the current list of tags in the headline, INHERITED is the
  13158. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13159. possibly with grouping information. TODO-TABLE is a similar table with
  13160. TODO keywords, should these have keys assigned to them.
  13161. If the keys are nil, a-z are automatically assigned.
  13162. Returns the new tags string, or nil to not change the current settings."
  13163. (let* ((fulltable (append table todo-table))
  13164. (maxlen (if (null fulltable) 0
  13165. (apply #'max
  13166. (mapcar (lambda (x)
  13167. (if (stringp (car x)) (string-width (car x))
  13168. 0))
  13169. fulltable))))
  13170. (buf (current-buffer))
  13171. (expert (eq org-fast-tag-selection-single-key 'expert))
  13172. (buffer-tags nil)
  13173. (fwidth (+ maxlen 3 1 3))
  13174. (ncol (/ (- (window-width) 4) fwidth))
  13175. (i-face 'org-done)
  13176. (c-face 'org-todo)
  13177. tg cnt e c char c1 c2 ntable tbl rtn
  13178. ov-start ov-end ov-prefix
  13179. (exit-after-next org-fast-tag-selection-single-key)
  13180. (done-keywords org-done-keywords)
  13181. groups ingroup intaggroup)
  13182. (save-excursion
  13183. (beginning-of-line)
  13184. (if (looking-at org-tag-line-re)
  13185. (setq ov-start (match-beginning 1)
  13186. ov-end (match-end 1)
  13187. ov-prefix "")
  13188. (setq ov-start (1- (point-at-eol))
  13189. ov-end (1+ ov-start))
  13190. (skip-chars-forward "^\n\r")
  13191. (setq ov-prefix
  13192. (concat
  13193. (buffer-substring (1- (point)) (point))
  13194. (if (> (current-column) org-tags-column)
  13195. " "
  13196. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13197. (move-overlay org-tags-overlay ov-start ov-end)
  13198. (save-window-excursion
  13199. (if expert
  13200. (set-buffer (get-buffer-create " *Org tags*"))
  13201. (delete-other-windows)
  13202. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13203. (org-switch-to-buffer-other-window " *Org tags*"))
  13204. (erase-buffer)
  13205. (setq-local org-done-keywords done-keywords)
  13206. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13207. (org-fast-tag-insert "Current" current c-face "\n\n")
  13208. (org-fast-tag-show-exit exit-after-next)
  13209. (org-set-current-tags-overlay current ov-prefix)
  13210. (setq tbl fulltable char ?a cnt 0)
  13211. (while (setq e (pop tbl))
  13212. (cond
  13213. ((eq (car e) :startgroup)
  13214. (push '() groups) (setq ingroup t)
  13215. (unless (zerop cnt)
  13216. (setq cnt 0)
  13217. (insert "\n"))
  13218. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13219. ((eq (car e) :endgroup)
  13220. (setq ingroup nil cnt 0)
  13221. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13222. ((eq (car e) :startgrouptag)
  13223. (setq intaggroup t)
  13224. (unless (zerop cnt)
  13225. (setq cnt 0)
  13226. (insert "\n"))
  13227. (insert "[ "))
  13228. ((eq (car e) :endgrouptag)
  13229. (setq intaggroup nil cnt 0)
  13230. (insert "]\n"))
  13231. ((equal e '(:newline))
  13232. (unless (zerop cnt)
  13233. (setq cnt 0)
  13234. (insert "\n")
  13235. (setq e (car tbl))
  13236. (while (equal (car tbl) '(:newline))
  13237. (insert "\n")
  13238. (setq tbl (cdr tbl)))))
  13239. ((equal e '(:grouptags)) (insert " : "))
  13240. (t
  13241. (setq tg (copy-sequence (car e)) c2 nil)
  13242. (if (cdr e)
  13243. (setq c (cdr e))
  13244. ;; automatically assign a character.
  13245. (setq c1 (string-to-char
  13246. (downcase (substring
  13247. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13248. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13249. (while (or (rassoc char ntable) (rassoc char table))
  13250. (setq char (1+ char)))
  13251. (setq c2 c1))
  13252. (setq c (or c2 char)))
  13253. (when ingroup (push tg (car groups)))
  13254. (setq tg (org-add-props tg nil 'face
  13255. (cond
  13256. ((not (assoc tg table))
  13257. (org-get-todo-face tg))
  13258. ((member tg current) c-face)
  13259. ((member tg inherited) i-face))))
  13260. (when (equal (caar tbl) :grouptags)
  13261. (org-add-props tg nil 'face 'org-tag-group))
  13262. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13263. (insert "[" c "] " tg (make-string
  13264. (- fwidth 4 (length tg)) ?\ ))
  13265. (push (cons tg c) ntable)
  13266. (when (= (cl-incf cnt) ncol)
  13267. (insert "\n")
  13268. (when (or ingroup intaggroup) (insert " "))
  13269. (setq cnt 0)))))
  13270. (setq ntable (nreverse ntable))
  13271. (insert "\n")
  13272. (goto-char (point-min))
  13273. (unless expert (org-fit-window-to-buffer))
  13274. (setq rtn
  13275. (catch 'exit
  13276. (while t
  13277. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13278. (if (not groups) "no " "")
  13279. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13280. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13281. (setq org-last-tag-selection-key c)
  13282. (cond
  13283. ((= c ?\r) (throw 'exit t))
  13284. ((= c ?!)
  13285. (setq groups (not groups))
  13286. (goto-char (point-min))
  13287. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13288. ((= c ?\C-c)
  13289. (if (not expert)
  13290. (org-fast-tag-show-exit
  13291. (setq exit-after-next (not exit-after-next)))
  13292. (setq expert nil)
  13293. (delete-other-windows)
  13294. (set-window-buffer (split-window-vertically) " *Org tags*")
  13295. (org-switch-to-buffer-other-window " *Org tags*")
  13296. (org-fit-window-to-buffer)))
  13297. ((or (= c ?\C-g)
  13298. (and (= c ?q) (not (rassoc c ntable))))
  13299. (delete-overlay org-tags-overlay)
  13300. (setq quit-flag t))
  13301. ((= c ?\ )
  13302. (setq current nil)
  13303. (when exit-after-next (setq exit-after-next 'now)))
  13304. ((= c ?\t)
  13305. (condition-case nil
  13306. (setq tg (completing-read
  13307. "Tag: "
  13308. (or buffer-tags
  13309. (with-current-buffer buf
  13310. (setq buffer-tags
  13311. (org-get-buffer-tags))))))
  13312. (quit (setq tg "")))
  13313. (when (string-match "\\S-" tg)
  13314. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13315. (if (member tg current)
  13316. (setq current (delete tg current))
  13317. (push tg current)))
  13318. (when exit-after-next (setq exit-after-next 'now)))
  13319. ((setq e (rassoc c todo-table) tg (car e))
  13320. (with-current-buffer buf
  13321. (save-excursion (org-todo tg)))
  13322. (when exit-after-next (setq exit-after-next 'now)))
  13323. ((setq e (rassoc c ntable) tg (car e))
  13324. (if (member tg current)
  13325. (setq current (delete tg current))
  13326. (cl-loop for g in groups do
  13327. (when (member tg g)
  13328. (dolist (x g) (setq current (delete x current)))))
  13329. (push tg current))
  13330. (when exit-after-next (setq exit-after-next 'now))))
  13331. ;; Create a sorted list
  13332. (setq current
  13333. (sort current
  13334. (lambda (a b)
  13335. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13336. (when (eq exit-after-next 'now) (throw 'exit t))
  13337. (goto-char (point-min))
  13338. (beginning-of-line 2)
  13339. (delete-region (point) (point-at-eol))
  13340. (org-fast-tag-insert "Current" current c-face)
  13341. (org-set-current-tags-overlay current ov-prefix)
  13342. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  13343. (while (re-search-forward tag-re nil t)
  13344. (let ((tag (match-string 1)))
  13345. (add-text-properties
  13346. (match-beginning 1) (match-end 1)
  13347. (list 'face
  13348. (cond
  13349. ((member tag current) c-face)
  13350. ((member tag inherited) i-face)
  13351. (t (get-text-property (match-beginning 1) '
  13352. face))))))))
  13353. (goto-char (point-min)))))
  13354. (delete-overlay org-tags-overlay)
  13355. (if rtn
  13356. (mapconcat 'identity current ":")
  13357. nil))))
  13358. (defun org-make-tag-string (tags)
  13359. "Return string associated to TAGS.
  13360. TAGS is a list of strings."
  13361. (if (null tags) ""
  13362. (format ":%s:" (mapconcat #'identity tags ":"))))
  13363. (defun org--get-local-tags ()
  13364. "Return list of tags for the current headline.
  13365. Assume point is at the beginning of the headline."
  13366. (and (looking-at org-tag-line-re)
  13367. (split-string (match-string-no-properties 2) ":" t)))
  13368. (defun org-get-tags (&optional pos local)
  13369. "Get the list of tags specified in the current headline.
  13370. When argument POS is non-nil, retrieve tags for headline at POS.
  13371. Accoring to `org-use-tags-inheritance', tags may be inherited
  13372. from parent headlines, and from the whole document, through
  13373. `org-file-tags'. However, when optional argument LOCAL is
  13374. non-nil, only return tags really specified in the considered
  13375. headline.
  13376. Inherited tags have the `inherited' text property."
  13377. (if (and org-trust-scanner-tags
  13378. (or (not pos) (eq pos (point)))
  13379. (not local))
  13380. org-scanner-tags
  13381. (org-with-point-at (or pos (point))
  13382. (unless (org-before-first-heading-p)
  13383. (org-back-to-heading t)
  13384. (let ((tags (org--get-local-tags)))
  13385. (if (or local (not org-use-tag-inheritance)) tags
  13386. (while (org-up-heading-safe)
  13387. (setq tags (append (mapcar #'org-add-prop-inherited
  13388. (org--get-local-tags))
  13389. tags)))
  13390. (org-remove-uninherited-tags
  13391. (delete-dups (append org-file-tags tags)))))))))
  13392. (defun org-get-buffer-tags ()
  13393. "Get a table of all tags used in the buffer, for completion."
  13394. (org-with-point-at 1
  13395. (let (tags)
  13396. (while (re-search-forward org-tag-line-re nil t)
  13397. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  13398. tags)))
  13399. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  13400. ;;;; The mapping API
  13401. (defvar org-agenda-skip-comment-trees)
  13402. (defvar org-agenda-skip-function)
  13403. (defun org-map-entries (func &optional match scope &rest skip)
  13404. "Call FUNC at each headline selected by MATCH in SCOPE.
  13405. FUNC is a function or a lisp form. The function will be called without
  13406. arguments, with the cursor positioned at the beginning of the headline.
  13407. The return values of all calls to the function will be collected and
  13408. returned as a list.
  13409. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13410. does not need to preserve point. After evaluation, the cursor will be
  13411. moved to the end of the line (presumably of the headline of the
  13412. processed entry) and search continues from there. Under some
  13413. circumstances, this may not produce the wanted results. For example,
  13414. if you have removed (e.g. archived) the current (sub)tree it could
  13415. mean that the next entry will be skipped entirely. In such cases, you
  13416. can specify the position from where search should continue by making
  13417. FUNC set the variable `org-map-continue-from' to the desired buffer
  13418. position.
  13419. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13420. Only headlines that are matched by this query will be considered during
  13421. the iteration. When MATCH is nil or t, all headlines will be
  13422. visited by the iteration.
  13423. SCOPE determines the scope of this command. It can be any of:
  13424. nil The current buffer, respecting the restriction if any
  13425. tree The subtree started with the entry at point
  13426. region The entries within the active region, if any
  13427. region-start-level
  13428. The entries within the active region, but only those at
  13429. the same level than the first one.
  13430. file The current buffer, without restriction
  13431. file-with-archives
  13432. The current buffer, and any archives associated with it
  13433. agenda All agenda files
  13434. agenda-with-archives
  13435. All agenda files with any archive files associated with them
  13436. \(file1 file2 ...)
  13437. If this is a list, all files in the list will be scanned
  13438. The remaining args are treated as settings for the skipping facilities of
  13439. the scanner. The following items can be given here:
  13440. archive skip trees with the archive tag
  13441. comment skip trees with the COMMENT keyword
  13442. function or Emacs Lisp form:
  13443. will be used as value for `org-agenda-skip-function', so
  13444. whenever the function returns a position, FUNC will not be
  13445. called for that entry and search will continue from the
  13446. position returned
  13447. If your function needs to retrieve the tags including inherited tags
  13448. at the *current* entry, you can use the value of the variable
  13449. `org-scanner-tags' which will be much faster than getting the value
  13450. with `org-get-tags'. If your function gets properties with
  13451. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13452. to t around the call to `org-entry-properties' to get the same speedup.
  13453. Note that if your function moves around to retrieve tags and properties at
  13454. a *different* entry, you cannot use these techniques."
  13455. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13456. (not (org-region-active-p)))
  13457. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13458. (org-agenda-skip-archived-trees (memq 'archive skip))
  13459. (org-agenda-skip-comment-trees (memq 'comment skip))
  13460. (org-agenda-skip-function
  13461. (car (org-delete-all '(comment archive) skip)))
  13462. (org-tags-match-list-sublevels t)
  13463. (start-level (eq scope 'region-start-level))
  13464. matcher res
  13465. org-todo-keywords-for-agenda
  13466. org-done-keywords-for-agenda
  13467. org-todo-keyword-alist-for-agenda
  13468. org-tag-alist-for-agenda
  13469. org--matcher-tags-todo-only)
  13470. (cond
  13471. ((eq match t) (setq matcher t))
  13472. ((eq match nil) (setq matcher t))
  13473. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13474. (save-excursion
  13475. (save-restriction
  13476. (cond ((eq scope 'tree)
  13477. (org-back-to-heading t)
  13478. (org-narrow-to-subtree)
  13479. (setq scope nil))
  13480. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13481. (org-region-active-p))
  13482. ;; If needed, set start-level to a string like "2"
  13483. (when start-level
  13484. (save-excursion
  13485. (goto-char (region-beginning))
  13486. (unless (org-at-heading-p) (outline-next-heading))
  13487. (setq start-level (org-current-level))))
  13488. (narrow-to-region (region-beginning)
  13489. (save-excursion
  13490. (goto-char (region-end))
  13491. (unless (and (bolp) (org-at-heading-p))
  13492. (outline-next-heading))
  13493. (point)))
  13494. (setq scope nil)))
  13495. (if (not scope)
  13496. (progn
  13497. (org-agenda-prepare-buffers
  13498. (and buffer-file-name (list buffer-file-name)))
  13499. (setq res
  13500. (org-scan-tags
  13501. func matcher org--matcher-tags-todo-only start-level)))
  13502. ;; Get the right scope
  13503. (cond
  13504. ((and scope (listp scope) (symbolp (car scope)))
  13505. (setq scope (eval scope)))
  13506. ((eq scope 'agenda)
  13507. (setq scope (org-agenda-files t)))
  13508. ((eq scope 'agenda-with-archives)
  13509. (setq scope (org-agenda-files t))
  13510. (setq scope (org-add-archive-files scope)))
  13511. ((eq scope 'file)
  13512. (setq scope (and buffer-file-name (list buffer-file-name))))
  13513. ((eq scope 'file-with-archives)
  13514. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13515. (org-agenda-prepare-buffers scope)
  13516. (dolist (file scope)
  13517. (with-current-buffer (org-find-base-buffer-visiting file)
  13518. (org-with-wide-buffer
  13519. (goto-char (point-min))
  13520. (setq res
  13521. (append
  13522. res
  13523. (org-scan-tags
  13524. func matcher org--matcher-tags-todo-only)))))))))
  13525. res)))
  13526. ;;; Properties API
  13527. (defconst org-special-properties
  13528. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  13529. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  13530. "The special properties valid in Org mode.
  13531. These are properties that are not defined in the property drawer,
  13532. but in some other way.")
  13533. (defconst org-default-properties
  13534. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  13535. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  13536. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  13537. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  13538. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  13539. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  13540. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  13541. "Some properties that are used by Org mode for various purposes.
  13542. Being in this list makes sure that they are offered for completion.")
  13543. (defun org--valid-property-p (property)
  13544. "Non nil when string PROPERTY is a valid property name."
  13545. (not
  13546. (or (equal property "")
  13547. (string-match-p "\\s-" property))))
  13548. (defun org--update-property-plist (key val props)
  13549. "Associate KEY to VAL in alist PROPS.
  13550. Modifications are made by side-effect. Return new alist."
  13551. (let* ((appending (string= (substring key -1) "+"))
  13552. (key (if appending (substring key 0 -1) key))
  13553. (old (assoc-string key props t)))
  13554. (if (not old) (cons (cons key val) props)
  13555. (setcdr old (if appending (concat (cdr old) " " val) val))
  13556. props)))
  13557. (defun org-get-property-block (&optional beg force)
  13558. "Return the (beg . end) range of the body of the property drawer.
  13559. BEG is the beginning of the current subtree, or of the part
  13560. before the first headline. If it is not given, it will be found.
  13561. If the drawer does not exist, create it if FORCE is non-nil, or
  13562. return nil."
  13563. (org-with-wide-buffer
  13564. (when beg (goto-char beg))
  13565. (unless (org-before-first-heading-p)
  13566. (let ((beg (cond (beg)
  13567. ((or (not (featurep 'org-inlinetask))
  13568. (org-inlinetask-in-task-p))
  13569. (org-back-to-heading t))
  13570. (t (org-with-limited-levels (org-back-to-heading t))))))
  13571. (forward-line)
  13572. (when (looking-at-p org-planning-line-re) (forward-line))
  13573. (cond ((looking-at org-property-drawer-re)
  13574. (forward-line)
  13575. (cons (point) (progn (goto-char (match-end 0))
  13576. (line-beginning-position))))
  13577. (force
  13578. (goto-char beg)
  13579. (org-insert-property-drawer)
  13580. (let ((pos (save-excursion (search-forward ":END:")
  13581. (line-beginning-position))))
  13582. (cons pos pos))))))))
  13583. (defun org-at-property-p ()
  13584. "Non-nil when point is inside a property drawer.
  13585. See `org-property-re' for match data, if applicable."
  13586. (save-excursion
  13587. (beginning-of-line)
  13588. (and (looking-at org-property-re)
  13589. (let ((property-drawer (save-match-data (org-get-property-block))))
  13590. (and property-drawer
  13591. (>= (point) (car property-drawer))
  13592. (< (point) (cdr property-drawer)))))))
  13593. (defun org-property-action ()
  13594. "Do an action on properties."
  13595. (interactive)
  13596. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  13597. (let ((c (read-char-exclusive)))
  13598. (cl-case c
  13599. (?s (call-interactively #'org-set-property))
  13600. (?d (call-interactively #'org-delete-property))
  13601. (?D (call-interactively #'org-delete-property-globally))
  13602. (?c (call-interactively #'org-compute-property-at-point))
  13603. (otherwise (user-error "No such property action %c" c)))))
  13604. (defun org-inc-effort ()
  13605. "Increment the value of the effort property in the current entry."
  13606. (interactive)
  13607. (org-set-effort t))
  13608. (defvar org-clock-effort) ; Defined in org-clock.el.
  13609. (defvar org-clock-current-task) ; Defined in org-clock.el.
  13610. (defun org-set-effort (&optional increment value)
  13611. "Set the effort property of the current entry.
  13612. If INCREMENT is non-nil, set the property to the next allowed
  13613. value. Otherwise, if optional argument VALUE is provided, use
  13614. it. Eventually, prompt for the new value if none of the previous
  13615. variables is set."
  13616. (interactive "P")
  13617. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  13618. (current (org-entry-get nil org-effort-property))
  13619. (value
  13620. (cond
  13621. (increment
  13622. (unless allowed (user-error "Allowed effort values are not set"))
  13623. (or (cl-caadr (member (list current) allowed))
  13624. (user-error "Unknown value %S among allowed values" current)))
  13625. (value
  13626. (if (stringp value) value
  13627. (error "Invalid effort value: %S" value)))
  13628. (t
  13629. (let ((must-match
  13630. (and allowed
  13631. (not (get-text-property 0 'org-unrestricted
  13632. (caar allowed))))))
  13633. (completing-read "Effort: " allowed nil must-match))))))
  13634. (unless (equal current value)
  13635. (org-entry-put nil org-effort-property value))
  13636. (org-refresh-property '((effort . identity)
  13637. (effort-minutes . org-duration-to-minutes))
  13638. value)
  13639. (when (equal (org-get-heading t t t t)
  13640. (bound-and-true-p org-clock-current-task))
  13641. (setq org-clock-effort (org-get-at-bol 'effort))
  13642. (org-clock-update-mode-line))
  13643. (message "%s is now %s" org-effort-property value)))
  13644. (defun org-entry-properties (&optional pom which)
  13645. "Get all properties of the current entry.
  13646. When POM is a buffer position, get all properties from the entry
  13647. there instead.
  13648. This includes the TODO keyword, the tags, time strings for
  13649. deadline, scheduled, and clocking, and any additional properties
  13650. defined in the entry.
  13651. If WHICH is nil or `all', get all properties. If WHICH is
  13652. `special' or `standard', only get that subclass. If WHICH is
  13653. a string, only get that property.
  13654. Return value is an alist. Keys are properties, as upcased
  13655. strings."
  13656. (org-with-point-at pom
  13657. (when (and (derived-mode-p 'org-mode)
  13658. (ignore-errors (org-back-to-heading t)))
  13659. (catch 'exit
  13660. (let* ((beg (point))
  13661. (specific (and (stringp which) (upcase which)))
  13662. (which (cond ((not specific) which)
  13663. ((member specific org-special-properties) 'special)
  13664. (t 'standard)))
  13665. props)
  13666. ;; Get the special properties, like TODO and TAGS.
  13667. (when (memq which '(nil all special))
  13668. (when (or (not specific) (string= specific "CLOCKSUM"))
  13669. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  13670. (when clocksum
  13671. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  13672. props)))
  13673. (when specific (throw 'exit props)))
  13674. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  13675. (let ((clocksumt (get-text-property (point)
  13676. :org-clock-minutes-today)))
  13677. (when clocksumt
  13678. (push (cons "CLOCKSUM_T"
  13679. (org-duration-from-minutes clocksumt))
  13680. props)))
  13681. (when specific (throw 'exit props)))
  13682. (when (or (not specific) (string= specific "ITEM"))
  13683. (let ((case-fold-search nil))
  13684. (when (looking-at org-complex-heading-regexp)
  13685. (push (cons "ITEM"
  13686. (let ((title (match-string-no-properties 4)))
  13687. (if (org-string-nw-p title)
  13688. (org-remove-tabs title)
  13689. "")))
  13690. props)))
  13691. (when specific (throw 'exit props)))
  13692. (when (or (not specific) (string= specific "TODO"))
  13693. (let ((case-fold-search nil))
  13694. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  13695. (push (cons "TODO" (match-string-no-properties 2)) props)))
  13696. (when specific (throw 'exit props)))
  13697. (when (or (not specific) (string= specific "PRIORITY"))
  13698. (push (cons "PRIORITY"
  13699. (if (looking-at org-priority-regexp)
  13700. (match-string-no-properties 2)
  13701. (char-to-string org-default-priority)))
  13702. props)
  13703. (when specific (throw 'exit props)))
  13704. (when (or (not specific) (string= specific "FILE"))
  13705. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  13706. props)
  13707. (when specific (throw 'exit props)))
  13708. (when (or (not specific) (string= specific "TAGS"))
  13709. (let ((tags (org-get-tags nil t)))
  13710. (when tags
  13711. (push (cons "TAGS" (org-make-tag-string tags))
  13712. props)))
  13713. (when specific (throw 'exit props)))
  13714. (when (or (not specific) (string= specific "ALLTAGS"))
  13715. (let ((tags (org-get-tags)))
  13716. (when tags
  13717. (push (cons "ALLTAGS" (org-make-tag-string tags))
  13718. props)))
  13719. (when specific (throw 'exit props)))
  13720. (when (or (not specific) (string= specific "BLOCKED"))
  13721. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  13722. (when specific (throw 'exit props)))
  13723. (when (or (not specific)
  13724. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  13725. (forward-line)
  13726. (when (looking-at-p org-planning-line-re)
  13727. (end-of-line)
  13728. (let ((bol (line-beginning-position))
  13729. ;; Backward compatibility: time keywords used to
  13730. ;; be configurable (before 8.3). Make sure we
  13731. ;; get the correct keyword.
  13732. (key-assoc `(("CLOSED" . ,org-closed-string)
  13733. ("DEADLINE" . ,org-deadline-string)
  13734. ("SCHEDULED" . ,org-scheduled-string))))
  13735. (dolist (pair (if specific (list (assoc specific key-assoc))
  13736. key-assoc))
  13737. (save-excursion
  13738. (when (search-backward (cdr pair) bol t)
  13739. (goto-char (match-end 0))
  13740. (skip-chars-forward " \t")
  13741. (and (looking-at org-ts-regexp-both)
  13742. (push (cons (car pair)
  13743. (match-string-no-properties 0))
  13744. props)))))))
  13745. (when specific (throw 'exit props)))
  13746. (when (or (not specific)
  13747. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  13748. (let ((find-ts
  13749. (lambda (end ts)
  13750. ;; Fix next time-stamp before END. TS is the
  13751. ;; list of time-stamps found so far.
  13752. (let ((ts ts)
  13753. (regexp (cond
  13754. ((string= specific "TIMESTAMP")
  13755. org-ts-regexp)
  13756. ((string= specific "TIMESTAMP_IA")
  13757. org-ts-regexp-inactive)
  13758. ((assoc "TIMESTAMP_IA" ts)
  13759. org-ts-regexp)
  13760. ((assoc "TIMESTAMP" ts)
  13761. org-ts-regexp-inactive)
  13762. (t org-ts-regexp-both))))
  13763. (catch 'next
  13764. (while (re-search-forward regexp end t)
  13765. (backward-char)
  13766. (let ((object (org-element-context)))
  13767. ;; Accept to match timestamps in node
  13768. ;; properties, too.
  13769. (when (memq (org-element-type object)
  13770. '(node-property timestamp))
  13771. (let ((type
  13772. (org-element-property :type object)))
  13773. (cond
  13774. ((and (memq type '(active active-range))
  13775. (not (equal specific "TIMESTAMP_IA")))
  13776. (unless (assoc "TIMESTAMP" ts)
  13777. (push (cons "TIMESTAMP"
  13778. (org-element-property
  13779. :raw-value object))
  13780. ts)
  13781. (when specific (throw 'exit ts))))
  13782. ((and (memq type '(inactive inactive-range))
  13783. (not (string= specific "TIMESTAMP")))
  13784. (unless (assoc "TIMESTAMP_IA" ts)
  13785. (push (cons "TIMESTAMP_IA"
  13786. (org-element-property
  13787. :raw-value object))
  13788. ts)
  13789. (when specific (throw 'exit ts))))))
  13790. ;; Both timestamp types are found,
  13791. ;; move to next part.
  13792. (when (= (length ts) 2) (throw 'next ts)))))
  13793. ts)))))
  13794. (goto-char beg)
  13795. ;; First look for timestamps within headline.
  13796. (let ((ts (funcall find-ts (line-end-position) nil)))
  13797. (if (= (length ts) 2) (setq props (nconc ts props))
  13798. ;; Then find timestamps in the section, skipping
  13799. ;; planning line.
  13800. (let ((end (save-excursion (outline-next-heading))))
  13801. (forward-line)
  13802. (when (looking-at-p org-planning-line-re) (forward-line))
  13803. (setq props (nconc (funcall find-ts end ts) props))))))))
  13804. ;; Get the standard properties, like :PROP:.
  13805. (when (memq which '(nil all standard))
  13806. ;; If we are looking after a specific property, delegate
  13807. ;; to `org-entry-get', which is faster. However, make an
  13808. ;; exception for "CATEGORY", since it can be also set
  13809. ;; through keywords (i.e. #+CATEGORY).
  13810. (if (and specific (not (equal specific "CATEGORY")))
  13811. (let ((value (org-entry-get beg specific nil t)))
  13812. (throw 'exit (and value (list (cons specific value)))))
  13813. (let ((range (org-get-property-block beg)))
  13814. (when range
  13815. (let ((end (cdr range)) seen-base)
  13816. (goto-char (car range))
  13817. ;; Unlike to `org--update-property-plist', we
  13818. ;; handle the case where base values is found
  13819. ;; after its extension. We also forbid standard
  13820. ;; properties to be named as special properties.
  13821. (while (re-search-forward org-property-re end t)
  13822. (let* ((key (upcase (match-string-no-properties 2)))
  13823. (extendp (string-match-p "\\+\\'" key))
  13824. (key-base (if extendp (substring key 0 -1) key))
  13825. (value (match-string-no-properties 3)))
  13826. (cond
  13827. ((member-ignore-case key-base org-special-properties))
  13828. (extendp
  13829. (setq props
  13830. (org--update-property-plist key value props)))
  13831. ((member key seen-base))
  13832. (t (push key seen-base)
  13833. (let ((p (assoc-string key props t)))
  13834. (if p (setcdr p (concat value " " (cdr p)))
  13835. (push (cons key value) props))))))))))))
  13836. (unless (assoc "CATEGORY" props)
  13837. (push (cons "CATEGORY" (org-get-category beg)) props)
  13838. (when (string= specific "CATEGORY") (throw 'exit props)))
  13839. ;; Return value.
  13840. props)))))
  13841. (defun org--property-local-values (property literal-nil)
  13842. "Return value for PROPERTY in current entry.
  13843. Value is a list whose car is the base value for PROPERTY and cdr
  13844. a list of accumulated values. Return nil if neither is found in
  13845. the entry. Also return nil when PROPERTY is set to \"nil\",
  13846. unless LITERAL-NIL is non-nil."
  13847. (let ((range (org-get-property-block)))
  13848. (when range
  13849. (goto-char (car range))
  13850. (let* ((case-fold-search t)
  13851. (end (cdr range))
  13852. (value
  13853. ;; Base value.
  13854. (save-excursion
  13855. (let ((v (and (re-search-forward
  13856. (org-re-property property nil t) end t)
  13857. (match-string-no-properties 3))))
  13858. (list (if literal-nil v (org-not-nil v)))))))
  13859. ;; Find additional values.
  13860. (let* ((property+ (org-re-property (concat property "+") nil t)))
  13861. (while (re-search-forward property+ end t)
  13862. (push (match-string-no-properties 3) value)))
  13863. ;; Return final values.
  13864. (and (not (equal value '(nil))) (nreverse value))))))
  13865. (defun org--property-global-value (property literal-nil)
  13866. "Return value for PROPERTY in current buffer.
  13867. Return value is a string. Return nil if property is not set
  13868. globally. Also return nil when PROPERTY is set to \"nil\",
  13869. unless LITERAL-NIL is non-nil."
  13870. (let ((global
  13871. (cdr (or (assoc-string property org-file-properties t)
  13872. (assoc-string property org-global-properties t)
  13873. (assoc-string property org-global-properties-fixed t)))))
  13874. (if literal-nil global (org-not-nil global))))
  13875. (defun org-entry-get (pom property &optional inherit literal-nil)
  13876. "Get value of PROPERTY for entry or content at point-or-marker POM.
  13877. If INHERIT is non-nil and the entry does not have the property,
  13878. then also check higher levels of the hierarchy. If INHERIT is
  13879. the symbol `selective', use inheritance only if the setting in
  13880. `org-use-property-inheritance' selects PROPERTY for inheritance.
  13881. If the property is present but empty, the return value is the
  13882. empty string. If the property is not present at all, nil is
  13883. returned. In any other case, return the value as a string.
  13884. Search is case-insensitive.
  13885. If LITERAL-NIL is set, return the string value \"nil\" as
  13886. a string, do not interpret it as the list atom nil. This is used
  13887. for inheritance when a \"nil\" value can supersede a non-nil
  13888. value higher up the hierarchy."
  13889. (org-with-point-at pom
  13890. (cond
  13891. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  13892. ;; We need a special property. Use `org-entry-properties' to
  13893. ;; retrieve it, but specify the wanted property.
  13894. (cdr (assoc-string property (org-entry-properties nil property))))
  13895. ((and inherit
  13896. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  13897. (org-entry-get-with-inheritance property literal-nil))
  13898. (t
  13899. (let* ((local (org--property-local-values property literal-nil))
  13900. (value (and local (mapconcat #'identity (delq nil local) " "))))
  13901. (if literal-nil value (org-not-nil value)))))))
  13902. (defun org-property-or-variable-value (var &optional inherit)
  13903. "Check if there is a property fixing the value of VAR.
  13904. If yes, return this value. If not, return the current value of the variable."
  13905. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  13906. (if (and prop (stringp prop) (string-match "\\S-" prop))
  13907. (read prop)
  13908. (symbol-value var))))
  13909. (defun org-entry-delete (pom property)
  13910. "Delete PROPERTY from entry at point-or-marker POM.
  13911. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  13912. non-nil when a property was removed."
  13913. (org-with-point-at pom
  13914. (pcase (org-get-property-block)
  13915. (`(,begin . ,origin)
  13916. (let* ((end (copy-marker origin))
  13917. (re (org-re-property
  13918. (concat (regexp-quote property) "\\+?") t t)))
  13919. (goto-char begin)
  13920. (while (re-search-forward re end t)
  13921. (delete-region (match-beginning 0) (line-beginning-position 2)))
  13922. ;; If drawer is empty, remove it altogether.
  13923. (when (= begin end)
  13924. (delete-region (line-beginning-position 0)
  13925. (line-beginning-position 2)))
  13926. ;; Return non-nil if some property was removed.
  13927. (prog1 (/= end origin) (set-marker end nil))))
  13928. (_ nil))))
  13929. ;; Multi-values properties are properties that contain multiple values
  13930. ;; These values are assumed to be single words, separated by whitespace.
  13931. (defun org-entry-add-to-multivalued-property (pom property value)
  13932. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  13933. (let* ((old (org-entry-get pom property))
  13934. (values (and old (split-string old))))
  13935. (setq value (org-entry-protect-space value))
  13936. (unless (member value values)
  13937. (setq values (append values (list value)))
  13938. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13939. (defun org-entry-remove-from-multivalued-property (pom property value)
  13940. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  13941. (let* ((old (org-entry-get pom property))
  13942. (values (and old (split-string old))))
  13943. (setq value (org-entry-protect-space value))
  13944. (when (member value values)
  13945. (setq values (delete value values))
  13946. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13947. (defun org-entry-member-in-multivalued-property (pom property value)
  13948. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  13949. (let* ((old (org-entry-get pom property))
  13950. (values (and old (split-string old))))
  13951. (setq value (org-entry-protect-space value))
  13952. (member value values)))
  13953. (defun org-entry-get-multivalued-property (pom property)
  13954. "Return a list of values in a multivalued property."
  13955. (let* ((value (org-entry-get pom property))
  13956. (values (and value (split-string value))))
  13957. (mapcar #'org-entry-restore-space values)))
  13958. (defun org-entry-put-multivalued-property (pom property &rest values)
  13959. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  13960. VALUES should be a list of strings. Spaces will be protected."
  13961. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  13962. (let* ((value (org-entry-get pom property))
  13963. (values (and value (split-string value))))
  13964. (mapcar #'org-entry-restore-space values)))
  13965. (defun org-entry-protect-space (s)
  13966. "Protect spaces and newline in string S."
  13967. (while (string-match " " s)
  13968. (setq s (replace-match "%20" t t s)))
  13969. (while (string-match "\n" s)
  13970. (setq s (replace-match "%0A" t t s)))
  13971. s)
  13972. (defun org-entry-restore-space (s)
  13973. "Restore spaces and newline in string S."
  13974. (while (string-match "%20" s)
  13975. (setq s (replace-match " " t t s)))
  13976. (while (string-match "%0A" s)
  13977. (setq s (replace-match "\n" t t s)))
  13978. s)
  13979. (defvar org-entry-property-inherited-from (make-marker)
  13980. "Marker pointing to the entry from where a property was inherited.
  13981. Each call to `org-entry-get-with-inheritance' will set this marker to the
  13982. location of the entry where the inheritance search matched. If there was
  13983. no match, the marker will point nowhere.
  13984. Note that also `org-entry-get' calls this function, if the INHERIT flag
  13985. is set.")
  13986. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  13987. "Get PROPERTY of entry or content at point, search higher levels if needed.
  13988. The search will stop at the first ancestor which has the property defined.
  13989. If the value found is \"nil\", return nil to show that the property
  13990. should be considered as undefined (this is the meaning of nil here).
  13991. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  13992. (move-marker org-entry-property-inherited-from nil)
  13993. (org-with-wide-buffer
  13994. (let (value)
  13995. (catch 'exit
  13996. (while t
  13997. (let ((v (org--property-local-values property literal-nil)))
  13998. (when v
  13999. (setq value
  14000. (concat (mapconcat #'identity (delq nil v) " ")
  14001. (and value " ")
  14002. value)))
  14003. (cond
  14004. ((car v)
  14005. (org-back-to-heading t)
  14006. (move-marker org-entry-property-inherited-from (point))
  14007. (throw 'exit nil))
  14008. ((org-up-heading-safe))
  14009. (t
  14010. (let ((global (org--property-global-value property literal-nil)))
  14011. (cond ((not global))
  14012. (value (setq value (concat global " " value)))
  14013. (t (setq value global))))
  14014. (throw 'exit nil))))))
  14015. (if literal-nil value (org-not-nil value)))))
  14016. (defvar org-property-changed-functions nil
  14017. "Hook called when the value of a property has changed.
  14018. Each hook function should accept two arguments, the name of the property
  14019. and the new value.")
  14020. (defun org-entry-put (pom property value)
  14021. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14022. If the value is nil, it is converted to the empty string. If it
  14023. is not a string, an error is raised. Also raise an error on
  14024. invalid property names.
  14025. PROPERTY can be any regular property (see
  14026. `org-special-properties'). It can also be \"TODO\",
  14027. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14028. For the last two properties, VALUE may have any of the special
  14029. values \"earlier\" and \"later\". The function then increases or
  14030. decreases scheduled or deadline date by one day."
  14031. (cond ((null value) (setq value ""))
  14032. ((not (stringp value)) (error "Properties values should be strings"))
  14033. ((not (org--valid-property-p property))
  14034. (user-error "Invalid property name: \"%s\"" property)))
  14035. (org-with-point-at pom
  14036. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14037. (org-back-to-heading t)
  14038. (org-with-limited-levels (org-back-to-heading t)))
  14039. (let ((beg (point)))
  14040. (cond
  14041. ((equal property "TODO")
  14042. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14043. ((not (member value org-todo-keywords-1))
  14044. (user-error "\"%s\" is not a valid TODO state" value)))
  14045. (org-todo value)
  14046. (org-align-tags))
  14047. ((equal property "PRIORITY")
  14048. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14049. (org-align-tags))
  14050. ((equal property "SCHEDULED")
  14051. (forward-line)
  14052. (if (and (looking-at-p org-planning-line-re)
  14053. (re-search-forward
  14054. org-scheduled-time-regexp (line-end-position) t))
  14055. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14056. ((string= value "later") (org-timestamp-change 1 'day))
  14057. ((string= value "") (org-schedule '(4)))
  14058. (t (org-schedule nil value)))
  14059. (if (member value '("earlier" "later" ""))
  14060. (call-interactively #'org-schedule)
  14061. (org-schedule nil value))))
  14062. ((equal property "DEADLINE")
  14063. (forward-line)
  14064. (if (and (looking-at-p org-planning-line-re)
  14065. (re-search-forward
  14066. org-deadline-time-regexp (line-end-position) t))
  14067. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14068. ((string= value "later") (org-timestamp-change 1 'day))
  14069. ((string= value "") (org-deadline '(4)))
  14070. (t (org-deadline nil value)))
  14071. (if (member value '("earlier" "later" ""))
  14072. (call-interactively #'org-deadline)
  14073. (org-deadline nil value))))
  14074. ((member property org-special-properties)
  14075. (error "The %s property cannot be set with `org-entry-put'" property))
  14076. (t
  14077. (let* ((range (org-get-property-block beg 'force))
  14078. (end (cdr range))
  14079. (case-fold-search t))
  14080. (goto-char (car range))
  14081. (if (re-search-forward (org-re-property property nil t) end t)
  14082. (progn (delete-region (match-beginning 0) (match-end 0))
  14083. (goto-char (match-beginning 0)))
  14084. (goto-char end)
  14085. (insert "\n")
  14086. (backward-char))
  14087. (insert ":" property ":")
  14088. (when value (insert " " value))
  14089. (org-indent-line)))))
  14090. (run-hook-with-args 'org-property-changed-functions property value)))
  14091. (defun org-buffer-property-keys (&optional specials defaults columns)
  14092. "Get all property keys in the current buffer.
  14093. When SPECIALS is non-nil, also list the special properties that
  14094. reflect things like tags and TODO state.
  14095. When DEFAULTS is non-nil, also include properties that has
  14096. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14097. DESCRIPTION, LOCATION, and LOGGING and others.
  14098. When COLUMNS in non-nil, also include property names given in
  14099. COLUMN formats in the current buffer."
  14100. (let ((case-fold-search t)
  14101. (props (append
  14102. (and specials org-special-properties)
  14103. (and defaults (cons org-effort-property org-default-properties))
  14104. nil)))
  14105. (org-with-wide-buffer
  14106. (goto-char (point-min))
  14107. (while (re-search-forward org-property-start-re nil t)
  14108. (catch :skip
  14109. (let ((range (org-get-property-block)))
  14110. (unless range (throw :skip nil))
  14111. (goto-char (car range))
  14112. (let ((begin (car range))
  14113. (end (cdr range)))
  14114. ;; Make sure that found property block is not located
  14115. ;; before current point, as it would generate an infloop.
  14116. ;; It can happen, for example, in the following
  14117. ;; situation:
  14118. ;;
  14119. ;; * Headline
  14120. ;; :PROPERTIES:
  14121. ;; ...
  14122. ;; :END:
  14123. ;; *************** Inlinetask
  14124. ;; #+BEGIN_EXAMPLE
  14125. ;; :PROPERTIES:
  14126. ;; #+END_EXAMPLE
  14127. ;;
  14128. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  14129. (while (< (point) end)
  14130. (let ((p (progn (looking-at org-property-re)
  14131. (match-string-no-properties 2))))
  14132. ;; Only add true property name, not extension symbol.
  14133. (push (if (not (string-match-p "\\+\\'" p)) p
  14134. (substring p 0 -1))
  14135. props))
  14136. (forward-line))))
  14137. (outline-next-heading)))
  14138. (when columns
  14139. (goto-char (point-min))
  14140. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14141. (let ((element (org-element-at-point)))
  14142. (when (memq (org-element-type element) '(keyword node-property))
  14143. (let ((value (org-element-property :value element))
  14144. (start 0))
  14145. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  14146. \\(?:{[^}]+}\\)?"
  14147. value start)
  14148. (setq start (match-end 0))
  14149. (let ((p (match-string-no-properties 1 value)))
  14150. (unless (member-ignore-case p org-special-properties)
  14151. (push p props))))))))))
  14152. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14153. (defun org-property-values (key)
  14154. "List all non-nil values of property KEY in current buffer."
  14155. (org-with-wide-buffer
  14156. (goto-char (point-min))
  14157. (let ((case-fold-search t)
  14158. (re (org-re-property key))
  14159. values)
  14160. (while (re-search-forward re nil t)
  14161. (push (org-entry-get (point) key) values))
  14162. (delete-dups values))))
  14163. (defun org-insert-property-drawer ()
  14164. "Insert a property drawer into the current entry."
  14165. (org-with-wide-buffer
  14166. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14167. (org-back-to-heading t)
  14168. (org-with-limited-levels (org-back-to-heading t)))
  14169. (forward-line)
  14170. (when (looking-at-p org-planning-line-re) (forward-line))
  14171. (unless (looking-at-p org-property-drawer-re)
  14172. ;; Make sure we start editing a line from current entry, not from
  14173. ;; next one. It prevents extending text properties or overlays
  14174. ;; belonging to the latter.
  14175. (when (bolp) (backward-char))
  14176. (let ((begin (1+ (point)))
  14177. (inhibit-read-only t))
  14178. (insert "\n:PROPERTIES:\n:END:")
  14179. (when (eobp) (insert "\n"))
  14180. (org-indent-region begin (point))))))
  14181. (defun org-insert-drawer (&optional arg drawer)
  14182. "Insert a drawer at point.
  14183. When optional argument ARG is non-nil, insert a property drawer.
  14184. Optional argument DRAWER, when non-nil, is a string representing
  14185. drawer's name. Otherwise, the user is prompted for a name.
  14186. If a region is active, insert the drawer around that region
  14187. instead.
  14188. Point is left between drawer's boundaries."
  14189. (interactive "P")
  14190. (let* ((drawer (if arg "PROPERTIES"
  14191. (or drawer (read-from-minibuffer "Drawer: ")))))
  14192. (cond
  14193. ;; With C-u, fall back on `org-insert-property-drawer'
  14194. (arg (org-insert-property-drawer))
  14195. ;; Check validity of suggested drawer's name.
  14196. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14197. (user-error "Invalid drawer name"))
  14198. ;; With an active region, insert a drawer at point.
  14199. ((not (org-region-active-p))
  14200. (progn
  14201. (unless (bolp) (insert "\n"))
  14202. (insert (format ":%s:\n\n:END:\n" drawer))
  14203. (forward-line -2)))
  14204. ;; Otherwise, insert the drawer at point
  14205. (t
  14206. (let ((rbeg (region-beginning))
  14207. (rend (copy-marker (region-end))))
  14208. (unwind-protect
  14209. (progn
  14210. (goto-char rbeg)
  14211. (beginning-of-line)
  14212. (when (save-excursion
  14213. (re-search-forward org-outline-regexp-bol rend t))
  14214. (user-error "Drawers cannot contain headlines"))
  14215. ;; Position point at the beginning of the first
  14216. ;; non-blank line in region. Insert drawer's opening
  14217. ;; there, then indent it.
  14218. (org-skip-whitespace)
  14219. (beginning-of-line)
  14220. (insert ":" drawer ":\n")
  14221. (forward-line -1)
  14222. (indent-for-tab-command)
  14223. ;; Move point to the beginning of the first blank line
  14224. ;; after the last non-blank line in region. Insert
  14225. ;; drawer's closing, then indent it.
  14226. (goto-char rend)
  14227. (skip-chars-backward " \r\t\n")
  14228. (insert "\n:END:")
  14229. (deactivate-mark t)
  14230. (indent-for-tab-command)
  14231. (unless (eolp) (insert "\n")))
  14232. ;; Clear marker, whatever the outcome of insertion is.
  14233. (set-marker rend nil)))))))
  14234. (defvar org-property-set-functions-alist nil
  14235. "Property set function alist.
  14236. Each entry should have the following format:
  14237. (PROPERTY . READ-FUNCTION)
  14238. The read function will be called with the same argument as
  14239. `org-completing-read'.")
  14240. (defun org-set-property-function (property)
  14241. "Get the function that should be used to set PROPERTY.
  14242. This is computed according to `org-property-set-functions-alist'."
  14243. (or (cdr (assoc property org-property-set-functions-alist))
  14244. 'org-completing-read))
  14245. (defun org-read-property-value (property)
  14246. "Read PROPERTY value from user."
  14247. (let* ((completion-ignore-case t)
  14248. (allowed (org-property-get-allowed-values nil property 'table))
  14249. (cur (org-entry-get nil property))
  14250. (prompt (concat property " value"
  14251. (if (and cur (string-match "\\S-" cur))
  14252. (concat " [" cur "]") "") ": "))
  14253. (set-function (org-set-property-function property))
  14254. (val (if allowed
  14255. (funcall set-function prompt allowed nil
  14256. (not (get-text-property 0 'org-unrestricted
  14257. (caar allowed))))
  14258. (funcall set-function prompt
  14259. (mapcar 'list (org-property-values property))
  14260. nil nil "" nil cur))))
  14261. (org-trim val)))
  14262. (defvar org-last-set-property nil)
  14263. (defvar org-last-set-property-value nil)
  14264. (defun org-read-property-name ()
  14265. "Read a property name."
  14266. (let ((completion-ignore-case t)
  14267. (default-prop (or (and (org-at-property-p)
  14268. (match-string-no-properties 2))
  14269. org-last-set-property)))
  14270. (org-completing-read
  14271. (concat "Property"
  14272. (if default-prop (concat " [" default-prop "]") "")
  14273. ": ")
  14274. (mapcar #'list (org-buffer-property-keys nil t t))
  14275. nil nil nil nil default-prop)))
  14276. (defun org-set-property-and-value (use-last)
  14277. "Allow to set [PROPERTY]: [value] direction from prompt.
  14278. When use-default, don't even ask, just use the last
  14279. \"[PROPERTY]: [value]\" string from the history."
  14280. (interactive "P")
  14281. (let* ((completion-ignore-case t)
  14282. (pv (or (and use-last org-last-set-property-value)
  14283. (org-completing-read
  14284. "Enter a \"[Property]: [value]\" pair: "
  14285. nil nil nil nil nil
  14286. org-last-set-property-value)))
  14287. prop val)
  14288. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14289. (setq prop (match-string 1 pv)
  14290. val (match-string 2 pv))
  14291. (org-set-property prop val))))
  14292. (defun org-set-property (property value)
  14293. "In the current entry, set PROPERTY to VALUE.
  14294. When called interactively, this will prompt for a property name, offering
  14295. completion on existing and default properties. And then it will prompt
  14296. for a value, offering completion either on allowed values (via an inherited
  14297. xxx_ALL property) or on existing values in other instances of this property
  14298. in the current file.
  14299. Throw an error when trying to set a property with an invalid name."
  14300. (interactive (list nil nil))
  14301. (let ((property (or property (org-read-property-name))))
  14302. ;; `org-entry-put' also makes the following check, but this one
  14303. ;; avoids polluting `org-last-set-property' and
  14304. ;; `org-last-set-property-value' needlessly.
  14305. (unless (org--valid-property-p property)
  14306. (user-error "Invalid property name: \"%s\"" property))
  14307. (let ((value (or value (org-read-property-value property)))
  14308. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14309. (setq org-last-set-property property)
  14310. (setq org-last-set-property-value (concat property ": " value))
  14311. ;; Possibly postprocess the inserted value:
  14312. (when fn (setq value (funcall fn value)))
  14313. (unless (equal (org-entry-get nil property) value)
  14314. (org-entry-put nil property value)))))
  14315. (defun org-find-property (property &optional value)
  14316. "Find first entry in buffer that sets PROPERTY.
  14317. When optional argument VALUE is non-nil, only consider an entry
  14318. if it contains PROPERTY set to this value. If PROPERTY should be
  14319. explicitly set to nil, use string \"nil\" for VALUE.
  14320. Return position where the entry begins, or nil if there is no
  14321. such entry. If narrowing is in effect, only search the visible
  14322. part of the buffer."
  14323. (save-excursion
  14324. (goto-char (point-min))
  14325. (let ((case-fold-search t)
  14326. (re (org-re-property property nil (not value) value)))
  14327. (catch 'exit
  14328. (while (re-search-forward re nil t)
  14329. (when (if value (org-at-property-p)
  14330. (org-entry-get (point) property nil t))
  14331. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14332. (defun org-delete-property (property)
  14333. "In the current entry, delete PROPERTY."
  14334. (interactive
  14335. (let* ((completion-ignore-case t)
  14336. (cat (org-entry-get (point) "CATEGORY"))
  14337. (props0 (org-entry-properties nil 'standard))
  14338. (props (if cat props0
  14339. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14340. (prop (if (< 1 (length props))
  14341. (completing-read "Property: " props nil t)
  14342. (caar props))))
  14343. (list prop)))
  14344. (if (not property)
  14345. (message "No property to delete in this entry")
  14346. (org-entry-delete nil property)
  14347. (message "Property \"%s\" deleted" property)))
  14348. (defun org-delete-property-globally (property)
  14349. "Remove PROPERTY globally, from all entries.
  14350. This function ignores narrowing, if any."
  14351. (interactive
  14352. (let* ((completion-ignore-case t)
  14353. (prop (completing-read
  14354. "Globally remove property: "
  14355. (mapcar #'list (org-buffer-property-keys)))))
  14356. (list prop)))
  14357. (org-with-wide-buffer
  14358. (goto-char (point-min))
  14359. (let ((count 0)
  14360. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14361. (while (re-search-forward re nil t)
  14362. (when (org-entry-delete (point) property) (cl-incf count)))
  14363. (message "Property \"%s\" removed from %d entries" property count))))
  14364. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14365. (defun org-compute-property-at-point ()
  14366. "Compute the property at point.
  14367. This looks for an enclosing column format, extracts the operator and
  14368. then applies it to the property in the column format's scope."
  14369. (interactive)
  14370. (unless (org-at-property-p)
  14371. (user-error "Not at a property"))
  14372. (let ((prop (match-string-no-properties 2)))
  14373. (org-columns-get-format-and-top-level)
  14374. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14375. (user-error "No operator defined for property %s" prop))
  14376. (org-columns-compute prop)))
  14377. (defvar org-property-allowed-value-functions nil
  14378. "Hook for functions supplying allowed values for a specific property.
  14379. The functions must take a single argument, the name of the property, and
  14380. return a flat list of allowed values. If \":ETC\" is one of
  14381. the values, this means that these values are intended as defaults for
  14382. completion, but that other values should be allowed too.
  14383. The functions must return nil if they are not responsible for this
  14384. property.")
  14385. (defun org-property-get-allowed-values (pom property &optional table)
  14386. "Get allowed values for the property PROPERTY.
  14387. When TABLE is non-nil, return an alist that can directly be used for
  14388. completion."
  14389. (let (vals)
  14390. (cond
  14391. ((equal property "TODO")
  14392. (setq vals (org-with-point-at pom
  14393. (append org-todo-keywords-1 '("")))))
  14394. ((equal property "PRIORITY")
  14395. (let ((n org-lowest-priority))
  14396. (while (>= n org-highest-priority)
  14397. (push (char-to-string n) vals)
  14398. (setq n (1- n)))))
  14399. ((equal property "CATEGORY"))
  14400. ((member property org-special-properties))
  14401. ((setq vals (run-hook-with-args-until-success
  14402. 'org-property-allowed-value-functions property)))
  14403. (t
  14404. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14405. (when (and vals (string-match "\\S-" vals))
  14406. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14407. (setq vals (mapcar (lambda (x)
  14408. (cond ((stringp x) x)
  14409. ((numberp x) (number-to-string x))
  14410. ((symbolp x) (symbol-name x))
  14411. (t "???")))
  14412. vals)))))
  14413. (when (member ":ETC" vals)
  14414. (setq vals (remove ":ETC" vals))
  14415. (org-add-props (car vals) '(org-unrestricted t)))
  14416. (if table (mapcar 'list vals) vals)))
  14417. (defun org-property-previous-allowed-value (&optional _previous)
  14418. "Switch to the next allowed value for this property."
  14419. (interactive)
  14420. (org-property-next-allowed-value t))
  14421. (defun org-property-next-allowed-value (&optional previous)
  14422. "Switch to the next allowed value for this property."
  14423. (interactive)
  14424. (unless (org-at-property-p)
  14425. (user-error "Not at a property"))
  14426. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14427. (key (match-string 2))
  14428. (value (match-string 3))
  14429. (allowed (or (org-property-get-allowed-values (point) key)
  14430. (and (member value '("[ ]" "[-]" "[X]"))
  14431. '("[ ]" "[X]"))))
  14432. (heading (save-match-data (nth 4 (org-heading-components))))
  14433. nval)
  14434. (unless allowed
  14435. (user-error "Allowed values for this property have not been defined"))
  14436. (when previous (setq allowed (reverse allowed)))
  14437. (when (member value allowed)
  14438. (setq nval (car (cdr (member value allowed)))))
  14439. (setq nval (or nval (car allowed)))
  14440. (when (equal nval value)
  14441. (user-error "Only one allowed value for this property"))
  14442. (org-at-property-p)
  14443. (replace-match (concat " :" key ": " nval) t t)
  14444. (org-indent-line)
  14445. (beginning-of-line 1)
  14446. (skip-chars-forward " \t")
  14447. (when (equal prop org-effort-property)
  14448. (org-refresh-property
  14449. '((effort . identity)
  14450. (effort-minutes . org-duration-to-minutes))
  14451. nval)
  14452. (when (string= org-clock-current-task heading)
  14453. (setq org-clock-effort nval)
  14454. (org-clock-update-mode-line)))
  14455. (run-hook-with-args 'org-property-changed-functions key nval)))
  14456. (defun org-find-olp (path &optional this-buffer)
  14457. "Return a marker pointing to the entry at outline path OLP.
  14458. If anything goes wrong, throw an error.
  14459. You can wrap this call to catch the error like this:
  14460. (condition-case msg
  14461. (org-mobile-locate-entry (match-string 4))
  14462. (error (nth 1 msg)))
  14463. The return value will then be either a string with the error message,
  14464. or a marker if everything is OK.
  14465. If THIS-BUFFER is set, the outline path does not contain a file,
  14466. only headings."
  14467. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14468. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14469. (level 1)
  14470. (lmin 1)
  14471. (lmax 1)
  14472. end found flevel)
  14473. (unless buffer (error "File not found :%s" file))
  14474. (with-current-buffer buffer
  14475. (unless (derived-mode-p 'org-mode)
  14476. (error "Buffer %s needs to be in Org mode" buffer))
  14477. (org-with-wide-buffer
  14478. (goto-char (point-min))
  14479. (dolist (heading path)
  14480. (let ((re (format org-complex-heading-regexp-format
  14481. (regexp-quote heading)))
  14482. (cnt 0))
  14483. (while (re-search-forward re end t)
  14484. (setq level (- (match-end 1) (match-beginning 1)))
  14485. (when (and (>= level lmin) (<= level lmax))
  14486. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14487. (when (= cnt 0)
  14488. (error "Heading not found on level %d: %s" lmax heading))
  14489. (when (> cnt 1)
  14490. (error "Heading not unique on level %d: %s" lmax heading))
  14491. (goto-char found)
  14492. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14493. (setq end (save-excursion (org-end-of-subtree t t)))))
  14494. (when (org-at-heading-p)
  14495. (point-marker))))))
  14496. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14497. "Find node HEADING in BUFFER.
  14498. Return a marker to the heading if it was found, or nil if not.
  14499. If POS-ONLY is set, return just the position instead of a marker.
  14500. The heading text must match exact, but it may have a TODO keyword,
  14501. a priority cookie and tags in the standard locations."
  14502. (with-current-buffer (or buffer (current-buffer))
  14503. (org-with-wide-buffer
  14504. (goto-char (point-min))
  14505. (let (case-fold-search)
  14506. (when (re-search-forward
  14507. (format org-complex-heading-regexp-format
  14508. (regexp-quote heading)) nil t)
  14509. (if pos-only
  14510. (match-beginning 0)
  14511. (move-marker (make-marker) (match-beginning 0))))))))
  14512. (defun org-find-exact-heading-in-directory (heading &optional dir)
  14513. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  14514. When the target headline is found, return a marker to this location."
  14515. (let ((files (directory-files (or dir default-directory)
  14516. t "\\`[^.#].*\\.org\\'"))
  14517. visiting m buffer)
  14518. (catch 'found
  14519. (dolist (file files)
  14520. (message "trying %s" file)
  14521. (setq visiting (org-find-base-buffer-visiting file))
  14522. (setq buffer (or visiting (find-file-noselect file)))
  14523. (setq m (org-find-exact-headline-in-buffer
  14524. heading buffer))
  14525. (when (and (not m) (not visiting)) (kill-buffer buffer))
  14526. (and m (throw 'found m))))))
  14527. (defun org-find-entry-with-id (ident)
  14528. "Locate the entry that contains the ID property with exact value IDENT.
  14529. IDENT can be a string, a symbol or a number, this function will search for
  14530. the string representation of it.
  14531. Return the position where this entry starts, or nil if there is no such entry."
  14532. (interactive "sID: ")
  14533. (let ((id (cond
  14534. ((stringp ident) ident)
  14535. ((symbolp ident) (symbol-name ident))
  14536. ((numberp ident) (number-to-string ident))
  14537. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  14538. (org-with-wide-buffer (org-find-property "ID" id))))
  14539. ;;;; Timestamps
  14540. (defvar org-last-changed-timestamp nil)
  14541. (defvar org-last-inserted-timestamp nil
  14542. "The last time stamp inserted with `org-insert-time-stamp'.")
  14543. (defun org-time-stamp (arg &optional inactive)
  14544. "Prompt for a date/time and insert a time stamp.
  14545. If the user specifies a time like HH:MM or if this command is
  14546. called with at least one prefix argument, the time stamp contains
  14547. the date and the time. Otherwise, only the date is included.
  14548. All parts of a date not specified by the user are filled in from
  14549. the timestamp at point, if any, or the current date/time
  14550. otherwise.
  14551. If there is already a timestamp at the cursor, it is replaced.
  14552. With two universal prefix arguments, insert an active timestamp
  14553. with the current time without prompting the user.
  14554. When called from lisp, the timestamp is inactive if INACTIVE is
  14555. non-nil."
  14556. (interactive "P")
  14557. (let* ((ts (cond
  14558. ((org-at-date-range-p t)
  14559. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  14560. ((org-at-timestamp-p 'lax) (match-string 0))))
  14561. ;; Default time is either the timestamp at point or today.
  14562. ;; When entering a range, only the range start is considered.
  14563. (default-time (if (not ts) (current-time)
  14564. (apply #'encode-time (org-parse-time-string ts))))
  14565. (default-input (and ts (org-get-compact-tod ts)))
  14566. (repeater (and ts
  14567. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  14568. (match-string 0 ts)))
  14569. org-time-was-given
  14570. org-end-time-was-given
  14571. (time
  14572. (and (if (equal arg '(16)) (current-time)
  14573. ;; Preserve `this-command' and `last-command'.
  14574. (let ((this-command this-command)
  14575. (last-command last-command))
  14576. (org-read-date
  14577. arg 'totime nil nil default-time default-input
  14578. inactive))))))
  14579. (cond
  14580. ((and ts
  14581. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  14582. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  14583. (insert "--")
  14584. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  14585. (ts
  14586. ;; Make sure we're on a timestamp. When in the middle of a date
  14587. ;; range, move arbitrarily to range end.
  14588. (unless (org-at-timestamp-p 'lax)
  14589. (skip-chars-forward "-")
  14590. (org-at-timestamp-p 'lax))
  14591. (replace-match "")
  14592. (setq org-last-changed-timestamp
  14593. (org-insert-time-stamp
  14594. time (or org-time-was-given arg)
  14595. inactive nil nil (list org-end-time-was-given)))
  14596. (when repeater
  14597. (backward-char)
  14598. (insert " " repeater)
  14599. (setq org-last-changed-timestamp
  14600. (concat (substring org-last-inserted-timestamp 0 -1)
  14601. " " repeater ">")))
  14602. (message "Timestamp updated"))
  14603. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  14604. (t (org-insert-time-stamp
  14605. time (or org-time-was-given arg) inactive nil nil
  14606. (list org-end-time-was-given))))))
  14607. ;; FIXME: can we use this for something else, like computing time differences?
  14608. (defun org-get-compact-tod (s)
  14609. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  14610. (let* ((t1 (match-string 1 s))
  14611. (h1 (string-to-number (match-string 2 s)))
  14612. (m1 (string-to-number (match-string 3 s)))
  14613. (t2 (and (match-end 4) (match-string 5 s)))
  14614. (h2 (and t2 (string-to-number (match-string 6 s))))
  14615. (m2 (and t2 (string-to-number (match-string 7 s))))
  14616. dh dm)
  14617. (if (not t2)
  14618. t1
  14619. (setq dh (- h2 h1) dm (- m2 m1))
  14620. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  14621. (concat t1 "+" (number-to-string dh)
  14622. (and (/= 0 dm) (format ":%02d" dm)))))))
  14623. (defun org-time-stamp-inactive (&optional arg)
  14624. "Insert an inactive time stamp.
  14625. An inactive time stamp is enclosed in square brackets instead of angle
  14626. brackets. It is inactive in the sense that it does not trigger agenda entries,
  14627. does not link to the calendar and cannot be changed with the S-cursor keys.
  14628. So these are more for recording a certain time/date.
  14629. If the user specifies a time like HH:MM or if this command is called with
  14630. at least one prefix argument, the time stamp contains the date and the time.
  14631. Otherwise, only the date is included.
  14632. When called with two universal prefix arguments, insert an active time stamp
  14633. with the current time without prompting the user."
  14634. (interactive "P")
  14635. (org-time-stamp arg 'inactive))
  14636. (defvar org-date-ovl (make-overlay 1 1))
  14637. (overlay-put org-date-ovl 'face 'org-date-selected)
  14638. (delete-overlay org-date-ovl)
  14639. (defvar org-ans1) ; dynamically scoped parameter
  14640. (defvar org-ans2) ; dynamically scoped parameter
  14641. (defvar org-plain-time-of-day-regexp) ; defined below
  14642. (defvar org-overriding-default-time nil) ; dynamically scoped
  14643. (defvar org-read-date-overlay nil)
  14644. (defvar org-dcst nil) ; dynamically scoped
  14645. (defvar org-read-date-history nil)
  14646. (defvar org-read-date-final-answer nil)
  14647. (defvar org-read-date-analyze-futurep nil)
  14648. (defvar org-read-date-analyze-forced-year nil)
  14649. (defvar org-read-date-inactive)
  14650. (defvar org-read-date-minibuffer-local-map
  14651. (let* ((map (make-sparse-keymap)))
  14652. (set-keymap-parent map minibuffer-local-map)
  14653. (org-defkey map (kbd ".")
  14654. (lambda () (interactive)
  14655. ;; Are we at the beginning of the prompt?
  14656. (if (looking-back "^[^:]+: "
  14657. (let ((inhibit-field-text-motion t))
  14658. (line-beginning-position)))
  14659. (org-eval-in-calendar '(calendar-goto-today))
  14660. (insert "."))))
  14661. (org-defkey map (kbd "C-.")
  14662. (lambda () (interactive)
  14663. (org-eval-in-calendar '(calendar-goto-today))))
  14664. (org-defkey map (kbd "M-S-<left>")
  14665. (lambda () (interactive)
  14666. (org-eval-in-calendar '(calendar-backward-month 1))))
  14667. (org-defkey map (kbd "ESC S-<left>")
  14668. (lambda () (interactive)
  14669. (org-eval-in-calendar '(calendar-backward-month 1))))
  14670. (org-defkey map (kbd "M-S-<right>")
  14671. (lambda () (interactive)
  14672. (org-eval-in-calendar '(calendar-forward-month 1))))
  14673. (org-defkey map (kbd "ESC S-<right>")
  14674. (lambda () (interactive)
  14675. (org-eval-in-calendar '(calendar-forward-month 1))))
  14676. (org-defkey map (kbd "M-S-<up>")
  14677. (lambda () (interactive)
  14678. (org-eval-in-calendar '(calendar-backward-year 1))))
  14679. (org-defkey map (kbd "ESC S-<up>")
  14680. (lambda () (interactive)
  14681. (org-eval-in-calendar '(calendar-backward-year 1))))
  14682. (org-defkey map (kbd "M-S-<down>")
  14683. (lambda () (interactive)
  14684. (org-eval-in-calendar '(calendar-forward-year 1))))
  14685. (org-defkey map (kbd "ESC S-<down>")
  14686. (lambda () (interactive)
  14687. (org-eval-in-calendar '(calendar-forward-year 1))))
  14688. (org-defkey map (kbd "S-<up>")
  14689. (lambda () (interactive)
  14690. (org-eval-in-calendar '(calendar-backward-week 1))))
  14691. (org-defkey map (kbd "S-<down>")
  14692. (lambda () (interactive)
  14693. (org-eval-in-calendar '(calendar-forward-week 1))))
  14694. (org-defkey map (kbd "S-<left>")
  14695. (lambda () (interactive)
  14696. (org-eval-in-calendar '(calendar-backward-day 1))))
  14697. (org-defkey map (kbd "S-<right>")
  14698. (lambda () (interactive)
  14699. (org-eval-in-calendar '(calendar-forward-day 1))))
  14700. (org-defkey map (kbd "!")
  14701. (lambda () (interactive)
  14702. (org-eval-in-calendar '(diary-view-entries))
  14703. (message "")))
  14704. (org-defkey map (kbd ">")
  14705. (lambda () (interactive)
  14706. (org-eval-in-calendar '(calendar-scroll-left 1))))
  14707. (org-defkey map (kbd "<")
  14708. (lambda () (interactive)
  14709. (org-eval-in-calendar '(calendar-scroll-right 1))))
  14710. (org-defkey map (kbd "C-v")
  14711. (lambda () (interactive)
  14712. (org-eval-in-calendar
  14713. '(calendar-scroll-left-three-months 1))))
  14714. (org-defkey map (kbd "M-v")
  14715. (lambda () (interactive)
  14716. (org-eval-in-calendar
  14717. '(calendar-scroll-right-three-months 1))))
  14718. map)
  14719. "Keymap for minibuffer commands when using `org-read-date'.")
  14720. (defvar org-def)
  14721. (defvar org-defdecode)
  14722. (defvar org-with-time)
  14723. (defvar calendar-setup) ; Dynamically scoped.
  14724. (defun org-read-date (&optional with-time to-time from-string prompt
  14725. default-time default-input inactive)
  14726. "Read a date, possibly a time, and make things smooth for the user.
  14727. The prompt will suggest to enter an ISO date, but you can also enter anything
  14728. which will at least partially be understood by `parse-time-string'.
  14729. Unrecognized parts of the date will default to the current day, month, year,
  14730. hour and minute. If this command is called to replace a timestamp at point,
  14731. or to enter the second timestamp of a range, the default time is taken
  14732. from the existing stamp. Furthermore, the command prefers the future,
  14733. so if you are giving a date where the year is not given, and the day-month
  14734. combination is already past in the current year, it will assume you
  14735. mean next year. For details, see the manual. A few examples:
  14736. 3-2-5 --> 2003-02-05
  14737. feb 15 --> currentyear-02-15
  14738. 2/15 --> currentyear-02-15
  14739. sep 12 9 --> 2009-09-12
  14740. 12:45 --> today 12:45
  14741. 22 sept 0:34 --> currentyear-09-22 0:34
  14742. 12 --> currentyear-currentmonth-12
  14743. Fri --> nearest Friday after today
  14744. -Tue --> last Tuesday
  14745. etc.
  14746. Furthermore you can specify a relative date by giving, as the *first* thing
  14747. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  14748. change in days weeks, months, years.
  14749. With a single plus or minus, the date is relative to today. With a double
  14750. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  14751. +4d --> four days from today
  14752. +4 --> same as above
  14753. +2w --> two weeks from today
  14754. ++5 --> five days from default date
  14755. The function understands only English month and weekday abbreviations.
  14756. While prompting, a calendar is popped up - you can also select the
  14757. date with the mouse (button 1). The calendar shows a period of three
  14758. months. To scroll it to other months, use the keys `>' and `<'.
  14759. If you don't like the calendar, turn it off with
  14760. (setq org-read-date-popup-calendar nil)
  14761. With optional argument TO-TIME, the date will immediately be converted
  14762. to an internal time.
  14763. With an optional argument WITH-TIME, the prompt will suggest to
  14764. also insert a time. Note that when WITH-TIME is not set, you can
  14765. still enter a time, and this function will inform the calling routine
  14766. about this change. The calling routine may then choose to change the
  14767. format used to insert the time stamp into the buffer to include the time.
  14768. With optional argument FROM-STRING, read from this string instead from
  14769. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  14770. the time/date that is used for everything that is not specified by the
  14771. user."
  14772. (require 'parse-time)
  14773. (let* ((org-with-time with-time)
  14774. (org-time-stamp-rounding-minutes
  14775. (if (equal org-with-time '(16))
  14776. '(0 0)
  14777. org-time-stamp-rounding-minutes))
  14778. (org-dcst org-display-custom-times)
  14779. (ct (org-current-time))
  14780. (org-def (or org-overriding-default-time default-time ct))
  14781. (org-defdecode (decode-time org-def))
  14782. (cur-frame (selected-frame))
  14783. (mouse-autoselect-window nil) ; Don't let the mouse jump
  14784. (calendar-setup
  14785. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  14786. (calendar-move-hook nil)
  14787. (calendar-view-diary-initially-flag nil)
  14788. (calendar-view-holidays-initially-flag nil)
  14789. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  14790. ;; Rationalize `org-def' and `org-defdecode', if required.
  14791. (when (< (nth 2 org-defdecode) org-extend-today-until)
  14792. (setf (nth 2 org-defdecode) -1)
  14793. (setf (nth 1 org-defdecode) 59)
  14794. (setq org-def (apply #'encode-time org-defdecode))
  14795. (setq org-defdecode (decode-time org-def)))
  14796. (let* ((timestr (format-time-string
  14797. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  14798. org-def))
  14799. (prompt (concat (if prompt (concat prompt " ") "")
  14800. (format "Date+time [%s]: " timestr))))
  14801. (cond
  14802. (from-string (setq ans from-string))
  14803. (org-read-date-popup-calendar
  14804. (save-excursion
  14805. (save-window-excursion
  14806. (calendar)
  14807. (when (eq calendar-setup 'calendar-only)
  14808. (setq cal-frame
  14809. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  14810. (select-frame cal-frame))
  14811. (org-eval-in-calendar '(setq cursor-type nil) t)
  14812. (unwind-protect
  14813. (progn
  14814. (calendar-forward-day (- (time-to-days org-def)
  14815. (calendar-absolute-from-gregorian
  14816. (calendar-current-date))))
  14817. (org-eval-in-calendar nil t)
  14818. (let* ((old-map (current-local-map))
  14819. (map (copy-keymap calendar-mode-map))
  14820. (minibuffer-local-map
  14821. (copy-keymap org-read-date-minibuffer-local-map)))
  14822. (org-defkey map (kbd "RET") 'org-calendar-select)
  14823. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  14824. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  14825. (unwind-protect
  14826. (progn
  14827. (use-local-map map)
  14828. (setq org-read-date-inactive inactive)
  14829. (add-hook 'post-command-hook 'org-read-date-display)
  14830. (setq org-ans0
  14831. (read-string prompt
  14832. default-input
  14833. 'org-read-date-history
  14834. nil))
  14835. ;; org-ans0: from prompt
  14836. ;; org-ans1: from mouse click
  14837. ;; org-ans2: from calendar motion
  14838. (setq ans
  14839. (concat org-ans0 " " (or org-ans1 org-ans2))))
  14840. (remove-hook 'post-command-hook 'org-read-date-display)
  14841. (use-local-map old-map)
  14842. (when org-read-date-overlay
  14843. (delete-overlay org-read-date-overlay)
  14844. (setq org-read-date-overlay nil)))))
  14845. (bury-buffer "*Calendar*")
  14846. (when cal-frame
  14847. (delete-frame cal-frame)
  14848. (select-frame-set-input-focus cur-frame))))))
  14849. (t ; Naked prompt only
  14850. (unwind-protect
  14851. (setq ans (read-string prompt default-input
  14852. 'org-read-date-history timestr))
  14853. (when org-read-date-overlay
  14854. (delete-overlay org-read-date-overlay)
  14855. (setq org-read-date-overlay nil))))))
  14856. (setq final (org-read-date-analyze ans org-def org-defdecode))
  14857. (when org-read-date-analyze-forced-year
  14858. (message "Year was forced into %s"
  14859. (if org-read-date-force-compatible-dates
  14860. "compatible range (1970-2037)"
  14861. "range representable on this machine"))
  14862. (ding))
  14863. ;; One round trip to get rid of 34th of August and stuff like that....
  14864. (setq final (decode-time (apply 'encode-time final)))
  14865. (setq org-read-date-final-answer ans)
  14866. (if to-time
  14867. (apply 'encode-time final)
  14868. (if (and (boundp 'org-time-was-given) org-time-was-given)
  14869. (format "%04d-%02d-%02d %02d:%02d"
  14870. (nth 5 final) (nth 4 final) (nth 3 final)
  14871. (nth 2 final) (nth 1 final))
  14872. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  14873. (defun org-read-date-display ()
  14874. "Display the current date prompt interpretation in the minibuffer."
  14875. (when org-read-date-display-live
  14876. (when org-read-date-overlay
  14877. (delete-overlay org-read-date-overlay))
  14878. (when (minibufferp (current-buffer))
  14879. (save-excursion
  14880. (end-of-line 1)
  14881. (while (not (equal (buffer-substring
  14882. (max (point-min) (- (point) 4)) (point))
  14883. " "))
  14884. (insert " ")))
  14885. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  14886. " " (or org-ans1 org-ans2)))
  14887. (org-end-time-was-given nil)
  14888. (f (org-read-date-analyze ans org-def org-defdecode))
  14889. (fmts (if org-dcst
  14890. org-time-stamp-custom-formats
  14891. org-time-stamp-formats))
  14892. (fmt (if (or org-with-time
  14893. (and (boundp 'org-time-was-given) org-time-was-given))
  14894. (cdr fmts)
  14895. (car fmts)))
  14896. (txt (format-time-string fmt (apply 'encode-time f)))
  14897. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  14898. (txt (concat "=> " txt)))
  14899. (when (and org-end-time-was-given
  14900. (string-match org-plain-time-of-day-regexp txt))
  14901. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  14902. org-end-time-was-given
  14903. (substring txt (match-end 0)))))
  14904. (when org-read-date-analyze-futurep
  14905. (setq txt (concat txt " (=>F)")))
  14906. (setq org-read-date-overlay
  14907. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  14908. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  14909. (defun org-read-date-analyze (ans def defdecode)
  14910. "Analyze the combined answer of the date prompt."
  14911. ;; FIXME: cleanup and comment
  14912. ;; Pass `current-time' result to `decode-time' (instead of calling
  14913. ;; without arguments) so that only `current-time' has to be
  14914. ;; overridden in tests.
  14915. (let ((org-def def)
  14916. (org-defdecode defdecode)
  14917. (nowdecode (decode-time (current-time)))
  14918. delta deltan deltaw deltadef year month day
  14919. hour minute second wday pm h2 m2 tl wday1
  14920. iso-year iso-weekday iso-week iso-date futurep kill-year)
  14921. (setq org-read-date-analyze-futurep nil
  14922. org-read-date-analyze-forced-year nil)
  14923. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  14924. (setq ans "+0"))
  14925. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  14926. (setq ans (replace-match "" t t ans)
  14927. deltan (car delta)
  14928. deltaw (nth 1 delta)
  14929. deltadef (nth 2 delta)))
  14930. ;; Check if there is an iso week date in there. If yes, store the
  14931. ;; info and postpone interpreting it until the rest of the parsing
  14932. ;; is done.
  14933. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  14934. (setq iso-year (when (match-end 1)
  14935. (org-small-year-to-year
  14936. (string-to-number (match-string 1 ans))))
  14937. iso-weekday (when (match-end 3)
  14938. (string-to-number (match-string 3 ans)))
  14939. iso-week (string-to-number (match-string 2 ans)))
  14940. (setq ans (replace-match "" t t ans)))
  14941. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  14942. (when (string-match
  14943. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  14944. (setq year (if (match-end 2)
  14945. (string-to-number (match-string 2 ans))
  14946. (progn (setq kill-year t)
  14947. (string-to-number (format-time-string "%Y"))))
  14948. month (string-to-number (match-string 3 ans))
  14949. day (string-to-number (match-string 4 ans)))
  14950. (setq year (org-small-year-to-year year))
  14951. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14952. t nil ans)))
  14953. ;; Help matching dotted european dates
  14954. (when (string-match
  14955. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  14956. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  14957. (setq kill-year t)
  14958. (string-to-number (format-time-string "%Y")))
  14959. day (string-to-number (match-string 1 ans))
  14960. month (string-to-number (match-string 2 ans))
  14961. ans (replace-match (format "%04d-%02d-%02d" year month day)
  14962. t nil ans)))
  14963. ;; Help matching american dates, like 5/30 or 5/30/7
  14964. (when (string-match
  14965. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  14966. (setq year (if (match-end 4)
  14967. (string-to-number (match-string 4 ans))
  14968. (progn (setq kill-year t)
  14969. (string-to-number (format-time-string "%Y"))))
  14970. month (string-to-number (match-string 1 ans))
  14971. day (string-to-number (match-string 2 ans)))
  14972. (setq year (org-small-year-to-year year))
  14973. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14974. t nil ans)))
  14975. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  14976. ;; If there is a time with am/pm, and *no* time without it, we convert
  14977. ;; so that matching will be successful.
  14978. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  14979. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  14980. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  14981. (setq hour (string-to-number (match-string 1 ans))
  14982. minute (if (match-end 3)
  14983. (string-to-number (match-string 3 ans))
  14984. 0)
  14985. pm (equal ?p
  14986. (string-to-char (downcase (match-string 4 ans)))))
  14987. (if (and (= hour 12) (not pm))
  14988. (setq hour 0)
  14989. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  14990. (setq ans (replace-match (format "%02d:%02d" hour minute)
  14991. t t ans))))
  14992. ;; Check if a time range is given as a duration
  14993. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  14994. (setq hour (string-to-number (match-string 1 ans))
  14995. h2 (+ hour (string-to-number (match-string 3 ans)))
  14996. minute (string-to-number (match-string 2 ans))
  14997. m2 (+ minute (if (match-end 5) (string-to-number
  14998. (match-string 5 ans))0)))
  14999. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15000. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15001. t t ans)))
  15002. ;; Check if there is a time range
  15003. (when (boundp 'org-end-time-was-given)
  15004. (setq org-time-was-given nil)
  15005. (when (and (string-match org-plain-time-of-day-regexp ans)
  15006. (match-end 8))
  15007. (setq org-end-time-was-given (match-string 8 ans))
  15008. (setq ans (concat (substring ans 0 (match-beginning 7))
  15009. (substring ans (match-end 7))))))
  15010. (setq tl (parse-time-string ans)
  15011. day (or (nth 3 tl) (nth 3 org-defdecode))
  15012. month
  15013. (cond ((nth 4 tl))
  15014. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15015. ;; Day was specified. Make sure DAY+MONTH
  15016. ;; combination happens in the future.
  15017. ((nth 3 tl)
  15018. (setq futurep t)
  15019. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15020. (nth 4 nowdecode)))
  15021. (t (nth 4 org-defdecode)))
  15022. year
  15023. (cond ((and (not kill-year) (nth 5 tl)))
  15024. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15025. ;; Month was guessed in the future and is at least
  15026. ;; equal to NOWDECODE's. Fix year accordingly.
  15027. (futurep
  15028. (if (or (> month (nth 4 nowdecode))
  15029. (>= day (nth 3 nowdecode)))
  15030. (nth 5 nowdecode)
  15031. (1+ (nth 5 nowdecode))))
  15032. ;; Month was specified. Make sure MONTH+YEAR
  15033. ;; combination happens in the future.
  15034. ((nth 4 tl)
  15035. (setq futurep t)
  15036. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15037. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15038. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15039. (t (nth 5 nowdecode))))
  15040. (t (nth 5 org-defdecode)))
  15041. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15042. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15043. second (or (nth 0 tl) 0)
  15044. wday (nth 6 tl))
  15045. (when (and (eq org-read-date-prefer-future 'time)
  15046. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15047. (equal day (nth 3 nowdecode))
  15048. (equal month (nth 4 nowdecode))
  15049. (equal year (nth 5 nowdecode))
  15050. (nth 2 tl)
  15051. (or (< (nth 2 tl) (nth 2 nowdecode))
  15052. (and (= (nth 2 tl) (nth 2 nowdecode))
  15053. (nth 1 tl)
  15054. (< (nth 1 tl) (nth 1 nowdecode)))))
  15055. (setq day (1+ day)
  15056. futurep t))
  15057. ;; Special date definitions below
  15058. (cond
  15059. (iso-week
  15060. ;; There was an iso week
  15061. (require 'cal-iso)
  15062. (setq futurep nil)
  15063. (setq year (or iso-year year)
  15064. day (or iso-weekday wday 1)
  15065. wday nil ; to make sure that the trigger below does not match
  15066. iso-date (calendar-gregorian-from-absolute
  15067. (calendar-iso-to-absolute
  15068. (list iso-week day year))))
  15069. ; FIXME: Should we also push ISO weeks into the future?
  15070. ; (when (and org-read-date-prefer-future
  15071. ; (not iso-year)
  15072. ; (< (calendar-absolute-from-gregorian iso-date)
  15073. ; (time-to-days (current-time))))
  15074. ; (setq year (1+ year)
  15075. ; iso-date (calendar-gregorian-from-absolute
  15076. ; (calendar-iso-to-absolute
  15077. ; (list iso-week day year)))))
  15078. (setq month (car iso-date)
  15079. year (nth 2 iso-date)
  15080. day (nth 1 iso-date)))
  15081. (deltan
  15082. (setq futurep nil)
  15083. (unless deltadef
  15084. ;; Pass `current-time' result to `decode-time' (instead of
  15085. ;; calling without arguments) so that only `current-time' has
  15086. ;; to be overridden in tests.
  15087. (let ((now (decode-time (current-time))))
  15088. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15089. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15090. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15091. ((equal deltaw "m") (setq month (+ month deltan)))
  15092. ((equal deltaw "y") (setq year (+ year deltan)))))
  15093. ((and wday (not (nth 3 tl)))
  15094. ;; Weekday was given, but no day, so pick that day in the week
  15095. ;; on or after the derived date.
  15096. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15097. (unless (equal wday wday1)
  15098. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15099. (when (and (boundp 'org-time-was-given)
  15100. (nth 2 tl))
  15101. (setq org-time-was-given t))
  15102. (when (< year 100) (setq year (+ 2000 year)))
  15103. ;; Check of the date is representable
  15104. (if org-read-date-force-compatible-dates
  15105. (progn
  15106. (when (< year 1970)
  15107. (setq year 1970 org-read-date-analyze-forced-year t))
  15108. (when (> year 2037)
  15109. (setq year 2037 org-read-date-analyze-forced-year t)))
  15110. (condition-case nil
  15111. (ignore (encode-time second minute hour day month year))
  15112. (error
  15113. (setq year (nth 5 org-defdecode))
  15114. (setq org-read-date-analyze-forced-year t))))
  15115. (setq org-read-date-analyze-futurep futurep)
  15116. (list second minute hour day month year)))
  15117. (defvar parse-time-weekdays)
  15118. (defun org-read-date-get-relative (s today default)
  15119. "Check string S for special relative date string.
  15120. TODAY and DEFAULT are internal times, for today and for a default.
  15121. Return shift list (N what def-flag)
  15122. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15123. N is the number of WHATs to shift.
  15124. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15125. the DEFAULT date rather than TODAY."
  15126. (require 'parse-time)
  15127. (when (and
  15128. (string-match
  15129. (concat
  15130. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15131. "\\([0-9]+\\)?"
  15132. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15133. "\\([ \t]\\|$\\)") s)
  15134. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15135. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15136. (string-to-char (substring (match-string 1 s) -1))
  15137. ?+))
  15138. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15139. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15140. (what (if (match-end 3) (match-string 3 s) "d"))
  15141. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15142. (date (if rel default today))
  15143. (wday (nth 6 (decode-time date)))
  15144. delta)
  15145. (if wday1
  15146. (progn
  15147. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15148. (when (= delta 0) (setq delta 7))
  15149. (when (= dir ?-)
  15150. (setq delta (- delta 7))
  15151. (when (= delta 0) (setq delta -7)))
  15152. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15153. (list delta "d" rel))
  15154. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15155. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15156. "Turn a user-specified date into the internal representation.
  15157. The internal representation needed by the calendar is (month day year).
  15158. This is a wrapper to handle the brain-dead convention in calendar that
  15159. user function argument order change dependent on argument order."
  15160. (pcase calendar-date-style
  15161. (`american (list arg1 arg2 arg3))
  15162. (`european (list arg2 arg1 arg3))
  15163. (`iso (list arg2 arg3 arg1))))
  15164. (defun org-eval-in-calendar (form &optional keepdate)
  15165. "Eval FORM in the calendar window and return to current window.
  15166. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15167. (let ((sf (selected-frame))
  15168. (sw (selected-window)))
  15169. (select-window (get-buffer-window "*Calendar*" t))
  15170. (eval form)
  15171. (when (and (not keepdate) (calendar-cursor-to-date))
  15172. (let* ((date (calendar-cursor-to-date))
  15173. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15174. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15175. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15176. (select-window sw)
  15177. (select-frame-set-input-focus sf)))
  15178. (defun org-calendar-select ()
  15179. "Return to `org-read-date' with the date currently selected.
  15180. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15181. (interactive)
  15182. (when (calendar-cursor-to-date)
  15183. (let* ((date (calendar-cursor-to-date))
  15184. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15185. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15186. (when (active-minibuffer-window) (exit-minibuffer))))
  15187. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15188. "Insert a date stamp for the date given by the internal TIME.
  15189. See `format-time-string' for the format of TIME.
  15190. WITH-HM means use the stamp format that includes the time of the day.
  15191. INACTIVE means use square brackets instead of angular ones, so that the
  15192. stamp will not contribute to the agenda.
  15193. PRE and POST are optional strings to be inserted before and after the
  15194. stamp.
  15195. The command returns the inserted time stamp."
  15196. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15197. stamp)
  15198. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15199. (insert-before-markers (or pre ""))
  15200. (when (listp extra)
  15201. (setq extra (car extra))
  15202. (if (and (stringp extra)
  15203. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15204. (setq extra (format "-%02d:%02d"
  15205. (string-to-number (match-string 1 extra))
  15206. (string-to-number (match-string 2 extra))))
  15207. (setq extra nil)))
  15208. (when extra
  15209. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15210. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15211. (insert-before-markers (or post ""))
  15212. (setq org-last-inserted-timestamp stamp)))
  15213. (defun org-toggle-time-stamp-overlays ()
  15214. "Toggle the use of custom time stamp formats."
  15215. (interactive)
  15216. (setq org-display-custom-times (not org-display-custom-times))
  15217. (unless org-display-custom-times
  15218. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15219. (while (setq p (next-single-property-change p 'display))
  15220. (when (and (get-text-property p 'display)
  15221. (eq (get-text-property p 'face) 'org-date))
  15222. (remove-text-properties
  15223. p (setq p (next-single-property-change p 'display))
  15224. '(display t))))
  15225. (set-buffer-modified-p bmp)))
  15226. (org-restart-font-lock)
  15227. (setq org-table-may-need-update t)
  15228. (if org-display-custom-times
  15229. (message "Time stamps are overlaid with custom format")
  15230. (message "Time stamp overlays removed")))
  15231. (defun org-display-custom-time (beg end)
  15232. "Overlay modified time stamp format over timestamp between BEG and END."
  15233. (let* ((ts (buffer-substring beg end))
  15234. t1 with-hm tf time str (off 0))
  15235. (save-match-data
  15236. (setq t1 (org-parse-time-string ts t))
  15237. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15238. (setq off (- (match-end 0) (match-beginning 0)))))
  15239. (setq end (- end off))
  15240. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15241. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15242. time (org-fix-decoded-time t1)
  15243. str (org-add-props
  15244. (format-time-string
  15245. (substring tf 1 -1) (apply 'encode-time time))
  15246. nil 'mouse-face 'highlight))
  15247. (put-text-property beg end 'display str)))
  15248. (defun org-fix-decoded-time (time)
  15249. "Set 0 instead of nil for the first 6 elements of time.
  15250. Don't touch the rest."
  15251. (let ((n 0))
  15252. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15253. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15254. "Difference between TIMESTAMP-STRING and now in days.
  15255. If SECONDS is non-nil, return the difference in seconds."
  15256. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15257. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15258. (funcall fdiff (current-time)))))
  15259. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15260. "Is the time in TIMESTAMP-STRING close to the current date?"
  15261. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15262. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15263. (not (org-entry-is-done-p))))
  15264. (defun org-get-wdays (ts &optional delay zero-delay)
  15265. "Get the deadline lead time appropriate for timestring TS.
  15266. When DELAY is non-nil, get the delay time for scheduled items
  15267. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15268. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15269. don't try to find the delay cookie in the scheduled timestamp."
  15270. (let ((tv (if delay org-scheduled-delay-days
  15271. org-deadline-warning-days)))
  15272. (cond
  15273. ((or (and delay (< tv 0))
  15274. (and delay zero-delay (<= tv 0))
  15275. (and (not delay) (<= tv 0)))
  15276. ;; Enforce this value no matter what
  15277. (- tv))
  15278. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15279. ;; lead time is specified.
  15280. (floor (* (string-to-number (match-string 1 ts))
  15281. (cdr (assoc (match-string 2 ts)
  15282. '(("d" . 1) ("w" . 7)
  15283. ("m" . 30.4) ("y" . 365.25)
  15284. ("h" . 0.041667)))))))
  15285. ;; go for the default.
  15286. (t tv))))
  15287. (defun org-calendar-select-mouse (ev)
  15288. "Return to `org-read-date' with the date currently selected.
  15289. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15290. (interactive "e")
  15291. (mouse-set-point ev)
  15292. (when (calendar-cursor-to-date)
  15293. (let* ((date (calendar-cursor-to-date))
  15294. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15295. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15296. (when (active-minibuffer-window) (exit-minibuffer))))
  15297. (defun org-check-deadlines (ndays)
  15298. "Check if there are any deadlines due or past due.
  15299. A deadline is considered due if it happens within `org-deadline-warning-days'
  15300. days from today's date. If the deadline appears in an entry marked DONE,
  15301. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15302. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15303. are shown."
  15304. (interactive "P")
  15305. (let* ((org-warn-days
  15306. (cond
  15307. ((equal ndays '(4)) 100000)
  15308. (ndays (prefix-numeric-value ndays))
  15309. (t (abs org-deadline-warning-days))))
  15310. (case-fold-search nil)
  15311. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15312. (callback
  15313. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15314. (message "%d deadlines past-due or due within %d days"
  15315. (org-occur regexp nil callback)
  15316. org-warn-days)))
  15317. (defsubst org-re-timestamp (type)
  15318. "Return a regexp for timestamp TYPE.
  15319. Allowed values for TYPE are:
  15320. all: all timestamps
  15321. active: only active timestamps (<...>)
  15322. inactive: only inactive timestamps ([...])
  15323. scheduled: only scheduled timestamps
  15324. deadline: only deadline timestamps
  15325. closed: only closed time-stamps
  15326. When TYPE is nil, fall back on returning a regexp that matches
  15327. both scheduled and deadline timestamps."
  15328. (cl-case type
  15329. (all org-ts-regexp-both)
  15330. (active org-ts-regexp)
  15331. (inactive org-ts-regexp-inactive)
  15332. (scheduled org-scheduled-time-regexp)
  15333. (deadline org-deadline-time-regexp)
  15334. (closed org-closed-time-regexp)
  15335. (otherwise
  15336. (concat "\\<"
  15337. (regexp-opt (list org-deadline-string org-scheduled-string))
  15338. " *<\\([^>]+\\)>"))))
  15339. (defun org-check-before-date (d)
  15340. "Check if there are deadlines or scheduled entries before date D."
  15341. (interactive (list (org-read-date)))
  15342. (let* ((case-fold-search nil)
  15343. (regexp (org-re-timestamp org-ts-type))
  15344. (ts-type org-ts-type)
  15345. (callback
  15346. (lambda ()
  15347. (let ((match (match-string 1)))
  15348. (and (if (memq ts-type '(active inactive all))
  15349. (eq (org-element-type (save-excursion
  15350. (backward-char)
  15351. (org-element-context)))
  15352. 'timestamp)
  15353. (org-at-planning-p))
  15354. (time-less-p
  15355. (org-time-string-to-time match)
  15356. (org-time-string-to-time d)))))))
  15357. (message "%d entries before %s"
  15358. (org-occur regexp nil callback)
  15359. d)))
  15360. (defun org-check-after-date (d)
  15361. "Check if there are deadlines or scheduled entries after date D."
  15362. (interactive (list (org-read-date)))
  15363. (let* ((case-fold-search nil)
  15364. (regexp (org-re-timestamp org-ts-type))
  15365. (ts-type org-ts-type)
  15366. (callback
  15367. (lambda ()
  15368. (let ((match (match-string 1)))
  15369. (and (if (memq ts-type '(active inactive all))
  15370. (eq (org-element-type (save-excursion
  15371. (backward-char)
  15372. (org-element-context)))
  15373. 'timestamp)
  15374. (org-at-planning-p))
  15375. (not (time-less-p
  15376. (org-time-string-to-time match)
  15377. (org-time-string-to-time d))))))))
  15378. (message "%d entries after %s"
  15379. (org-occur regexp nil callback)
  15380. d)))
  15381. (defun org-check-dates-range (start-date end-date)
  15382. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15383. (interactive (list (org-read-date nil nil nil "Range starts")
  15384. (org-read-date nil nil nil "Range end")))
  15385. (let ((case-fold-search nil)
  15386. (regexp (org-re-timestamp org-ts-type))
  15387. (callback
  15388. (let ((type org-ts-type))
  15389. (lambda ()
  15390. (let ((match (match-string 1)))
  15391. (and
  15392. (if (memq type '(active inactive all))
  15393. (eq (org-element-type (save-excursion
  15394. (backward-char)
  15395. (org-element-context)))
  15396. 'timestamp)
  15397. (org-at-planning-p))
  15398. (not (time-less-p
  15399. (org-time-string-to-time match)
  15400. (org-time-string-to-time start-date)))
  15401. (time-less-p
  15402. (org-time-string-to-time match)
  15403. (org-time-string-to-time end-date))))))))
  15404. (message "%d entries between %s and %s"
  15405. (org-occur regexp nil callback) start-date end-date)))
  15406. (defun org-evaluate-time-range (&optional to-buffer)
  15407. "Evaluate a time range by computing the difference between start and end.
  15408. Normally the result is just printed in the echo area, but with prefix arg
  15409. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15410. If the time range is actually in a table, the result is inserted into the
  15411. next column.
  15412. For time difference computation, a year is assumed to be exactly 365
  15413. days in order to avoid rounding problems."
  15414. (interactive "P")
  15415. (or
  15416. (org-clock-update-time-maybe)
  15417. (save-excursion
  15418. (unless (org-at-date-range-p t)
  15419. (goto-char (point-at-bol))
  15420. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15421. (unless (org-at-date-range-p t)
  15422. (user-error "Not at a time-stamp range, and none found in current line")))
  15423. (let* ((ts1 (match-string 1))
  15424. (ts2 (match-string 2))
  15425. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15426. (match-end (match-end 0))
  15427. (time1 (org-time-string-to-time ts1))
  15428. (time2 (org-time-string-to-time ts2))
  15429. (t1 (float-time time1))
  15430. (t2 (float-time time2))
  15431. (diff (abs (- t2 t1)))
  15432. (negative (< (- t2 t1) 0))
  15433. ;; (ys (floor (* 365 24 60 60)))
  15434. (ds (* 24 60 60))
  15435. (hs (* 60 60))
  15436. (fy "%dy %dd %02d:%02d")
  15437. (fy1 "%dy %dd")
  15438. (fd "%dd %02d:%02d")
  15439. (fd1 "%dd")
  15440. (fh "%02d:%02d")
  15441. y d h m align)
  15442. (if havetime
  15443. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15444. y 0
  15445. d (floor (/ diff ds)) diff (mod diff ds)
  15446. h (floor (/ diff hs)) diff (mod diff hs)
  15447. m (floor (/ diff 60)))
  15448. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15449. y 0
  15450. d (floor (+ (/ diff ds) 0.5))
  15451. h 0 m 0))
  15452. (if (not to-buffer)
  15453. (message "%s" (org-make-tdiff-string y d h m))
  15454. (if (org-at-table-p)
  15455. (progn
  15456. (goto-char match-end)
  15457. (setq align t)
  15458. (and (looking-at " *|") (goto-char (match-end 0))))
  15459. (goto-char match-end))
  15460. (when (looking-at
  15461. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15462. (replace-match ""))
  15463. (when negative (insert " -"))
  15464. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15465. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15466. (insert " " (format fh h m))))
  15467. (when align (org-table-align))
  15468. (message "Time difference inserted")))))
  15469. (defun org-make-tdiff-string (y d h m)
  15470. (let ((fmt "")
  15471. (l nil))
  15472. (when (> y 0)
  15473. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15474. (push y l))
  15475. (when (> d 0)
  15476. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15477. (push d l))
  15478. (when (> h 0)
  15479. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15480. (push h l))
  15481. (when (> m 0)
  15482. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15483. (push m l))
  15484. (apply 'format fmt (nreverse l))))
  15485. (defun org-time-string-to-time (s)
  15486. "Convert timestamp string S into internal time."
  15487. (apply #'encode-time (org-parse-time-string s)))
  15488. (defun org-time-string-to-seconds (s)
  15489. "Convert a timestamp string S into a number of seconds."
  15490. (float-time (org-time-string-to-time s)))
  15491. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15492. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15493. "Convert time stamp S to an absolute day number.
  15494. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15495. stamp, get the closest date to DAYNR. If PREFER is
  15496. `past' (respectively `future') return a date past (respectively
  15497. after) or equal to DAYNR.
  15498. POS is the location of time stamp S, as a buffer position in
  15499. BUFFER.
  15500. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15501. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15502. signaled."
  15503. (cond
  15504. ((string-match "\\`%%\\((.*)\\)" s)
  15505. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  15506. ;; only able to match individual dates. If it fails, raise an
  15507. ;; error.
  15508. (if (and daynr
  15509. (org-diary-sexp-entry
  15510. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  15511. daynr
  15512. (signal 'org-diary-sexp-no-match (list s))))
  15513. (daynr (org-closest-date s daynr prefer))
  15514. (t (time-to-days
  15515. (condition-case errdata
  15516. (apply #'encode-time (org-parse-time-string s))
  15517. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15518. s
  15519. (if (not (and buffer pos)) ""
  15520. (format-message " at %d in buffer `%s'" pos buffer))
  15521. (cdr errdata))))))))
  15522. (defun org-days-to-iso-week (days)
  15523. "Return the iso week number."
  15524. (require 'cal-iso)
  15525. (car (calendar-iso-from-absolute days)))
  15526. (defun org-small-year-to-year (year)
  15527. "Convert 2-digit years into 4-digit years.
  15528. YEAR is expanded into one of the 30 next years, if possible, or
  15529. into a past one. Any year larger than 99 is returned unchanged."
  15530. (if (>= year 100) year
  15531. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  15532. (century (/ current 100))
  15533. (offset (- year (% current 100))))
  15534. (cond ((> offset 30) (+ (* (1- century) 100) year))
  15535. ((> offset -70) (+ (* century 100) year))
  15536. (t (+ (* (1+ century) 100) year))))))
  15537. (defun org-time-from-absolute (d)
  15538. "Return the time corresponding to date D.
  15539. D may be an absolute day number, or a calendar-type list (month day year)."
  15540. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  15541. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  15542. (defvar org-agenda-current-date)
  15543. (defun org-calendar-holiday ()
  15544. "List of holidays, for Diary display in Org mode."
  15545. (require 'holidays)
  15546. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  15547. (and hl (mapconcat #'identity hl "; "))))
  15548. (defun org-diary-sexp-entry (sexp entry d)
  15549. "Process a SEXP diary ENTRY for date D."
  15550. (require 'diary-lib)
  15551. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  15552. ;; dynamically.
  15553. (let* ((sexp `(let ((entry ,entry)
  15554. (date ',d))
  15555. ,(car (read-from-string sexp))))
  15556. (result (if calendar-debug-sexp (eval sexp)
  15557. (condition-case nil
  15558. (eval sexp)
  15559. (error
  15560. (beep)
  15561. (message "Bad sexp at line %d in %s: %s"
  15562. (org-current-line)
  15563. (buffer-file-name) sexp)
  15564. (sleep-for 2))))))
  15565. (cond ((stringp result) (split-string result "; "))
  15566. ((and (consp result)
  15567. (not (consp (cdr result)))
  15568. (stringp (cdr result))) (cdr result))
  15569. ((and (consp result)
  15570. (stringp (car result))) result)
  15571. (result entry))))
  15572. (defun org-diary-to-ical-string (frombuf)
  15573. "Get iCalendar entries from diary entries in buffer FROMBUF.
  15574. This uses the icalendar.el library."
  15575. (let* ((tmpdir temporary-file-directory)
  15576. (tmpfile (make-temp-name
  15577. (expand-file-name "orgics" tmpdir)))
  15578. buf rtn b e)
  15579. (with-current-buffer frombuf
  15580. (icalendar-export-region (point-min) (point-max) tmpfile)
  15581. (setq buf (find-buffer-visiting tmpfile))
  15582. (set-buffer buf)
  15583. (goto-char (point-min))
  15584. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  15585. (setq b (match-beginning 0)))
  15586. (goto-char (point-max))
  15587. (when (re-search-backward "^END:VEVENT" nil t)
  15588. (setq e (match-end 0)))
  15589. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  15590. (kill-buffer buf)
  15591. (delete-file tmpfile)
  15592. rtn))
  15593. (defun org-closest-date (start current prefer)
  15594. "Return closest date to CURRENT starting from START.
  15595. CURRENT and START are both time stamps.
  15596. When PREFER is `past', return a date that is either CURRENT or
  15597. past. When PREFER is `future', return a date that is either
  15598. CURRENT or future.
  15599. Only time stamps with a repeater are modified. Any other time
  15600. stamp stay unchanged. In any case, return value is an absolute
  15601. day number."
  15602. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  15603. ;; No repeater. Do not shift time stamp.
  15604. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15605. (let ((value (string-to-number (match-string 1 start)))
  15606. (type (match-string 2 start)))
  15607. (if (= 0 value)
  15608. ;; Repeater with a 0-value is considered as void.
  15609. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15610. (let* ((base (org-date-to-gregorian start))
  15611. (target (org-date-to-gregorian current))
  15612. (sday (calendar-absolute-from-gregorian base))
  15613. (cday (calendar-absolute-from-gregorian target))
  15614. n1 n2)
  15615. ;; If START is already past CURRENT, just return START.
  15616. (if (<= cday sday) sday
  15617. ;; Compute closest date before (N1) and closest date past
  15618. ;; (N2) CURRENT.
  15619. (pcase type
  15620. ("h"
  15621. (let ((missing-hours
  15622. (mod (+ (- (* 24 (- cday sday))
  15623. (nth 2 (org-parse-time-string start)))
  15624. org-extend-today-until)
  15625. value)))
  15626. (setf n1 (if (= missing-hours 0) cday
  15627. (- cday (1+ (/ missing-hours 24)))))
  15628. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  15629. ((or "d" "w")
  15630. (let ((value (if (equal type "w") (* 7 value) value)))
  15631. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  15632. (setf n2 (+ n1 value))))
  15633. ("m"
  15634. (let* ((add-months
  15635. (lambda (d n)
  15636. ;; Add N months to gregorian date D, i.e.,
  15637. ;; a list (MONTH DAY YEAR). Return a valid
  15638. ;; gregorian date.
  15639. (let ((m (+ (nth 0 d) n)))
  15640. (list (mod m 12)
  15641. (nth 1 d)
  15642. (+ (/ m 12) (nth 2 d))))))
  15643. (months ; Complete months to TARGET.
  15644. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  15645. (- (nth 0 target) (nth 0 base))
  15646. ;; If START's day is greater than
  15647. ;; TARGET's, remove incomplete month.
  15648. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  15649. value)
  15650. value))
  15651. (before (funcall add-months base months)))
  15652. (setf n1 (calendar-absolute-from-gregorian before))
  15653. (setf n2
  15654. (calendar-absolute-from-gregorian
  15655. (funcall add-months before value)))))
  15656. (_
  15657. (let* ((d (nth 1 base))
  15658. (m (nth 0 base))
  15659. (y (nth 2 base))
  15660. (years ; Complete years to TARGET.
  15661. (* (/ (- (nth 2 target)
  15662. y
  15663. ;; If START's month and day are
  15664. ;; greater than TARGET's, remove
  15665. ;; incomplete year.
  15666. (if (or (> (nth 0 target) m)
  15667. (and (= (nth 0 target) m)
  15668. (> (nth 1 target) d)))
  15669. 0
  15670. 1))
  15671. value)
  15672. value))
  15673. (before (list m d (+ y years))))
  15674. (setf n1 (calendar-absolute-from-gregorian before))
  15675. (setf n2 (calendar-absolute-from-gregorian
  15676. (list m d (+ (nth 2 before) value)))))))
  15677. ;; Handle PREFER parameter, if any.
  15678. (cond
  15679. ((eq prefer 'past) (if (= cday n2) n2 n1))
  15680. ((eq prefer 'future) (if (= cday n1) n1 n2))
  15681. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  15682. (defun org-date-to-gregorian (d)
  15683. "Turn any specification of date D into a Gregorian date for the calendar."
  15684. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  15685. ((and (listp d) (= (length d) 3)) d)
  15686. ((stringp d)
  15687. (let ((d (org-parse-time-string d)))
  15688. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  15689. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  15690. (defun org-timestamp-up (&optional arg)
  15691. "Increase the date item at the cursor by one.
  15692. If the cursor is on the year, change the year. If it is on the month,
  15693. the day or the time, change that. If the cursor is on the enclosing
  15694. bracket, change the timestamp type.
  15695. With prefix ARG, change by that many units."
  15696. (interactive "p")
  15697. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  15698. (defun org-timestamp-down (&optional arg)
  15699. "Decrease the date item at the cursor by one.
  15700. If the cursor is on the year, change the year. If it is on the month,
  15701. the day or the time, change that. If the cursor is on the enclosing
  15702. bracket, change the timestamp type.
  15703. With prefix ARG, change by that many units."
  15704. (interactive "p")
  15705. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  15706. (defun org-timestamp-up-day (&optional arg)
  15707. "Increase the date in the time stamp by one day.
  15708. With prefix ARG, change that many days."
  15709. (interactive "p")
  15710. (if (and (not (org-at-timestamp-p 'lax))
  15711. (org-at-heading-p))
  15712. (org-todo 'up)
  15713. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  15714. (defun org-timestamp-down-day (&optional arg)
  15715. "Decrease the date in the time stamp by one day.
  15716. With prefix ARG, change that many days."
  15717. (interactive "p")
  15718. (if (and (not (org-at-timestamp-p 'lax))
  15719. (org-at-heading-p))
  15720. (org-todo 'down)
  15721. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  15722. (defun org-at-timestamp-p (&optional extended)
  15723. "Non-nil if point is inside a timestamp.
  15724. By default, the function only consider syntactically valid active
  15725. timestamps. However, the caller may have a broader definition
  15726. for timestamps. As a consequence, optional argument EXTENDED can
  15727. be set to the following values
  15728. `inactive'
  15729. Include also syntactically valid inactive timestamps.
  15730. `agenda'
  15731. Include timestamps allowed in Agenda, i.e., those in
  15732. properties drawers, planning lines and clock lines.
  15733. `lax'
  15734. Ignore context. The function matches any part of the
  15735. document looking like a timestamp. This includes comments,
  15736. example blocks...
  15737. For backward-compatibility with Org 9.0, every other non-nil
  15738. value is equivalent to `inactive'.
  15739. When at a timestamp, return the position of the point as a symbol
  15740. among `bracket', `after', `year', `month', `hour', `minute',
  15741. `day' or a number of character from the last know part of the
  15742. time stamp.
  15743. When matching, the match groups are the following:
  15744. group 1: year
  15745. group 2: month
  15746. group 3: day number
  15747. group 4: day name
  15748. group 5: hours, if any
  15749. group 6: minutes, if any"
  15750. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  15751. (pos (point))
  15752. (match?
  15753. (let ((boundaries (org-in-regexp regexp)))
  15754. (save-match-data
  15755. (cond ((null boundaries) nil)
  15756. ((eq extended 'lax) t)
  15757. (t
  15758. (or (and (eq extended 'agenda)
  15759. (or (org-at-planning-p)
  15760. (org-at-property-p)
  15761. (and (bound-and-true-p
  15762. org-agenda-include-inactive-timestamps)
  15763. (org-at-clock-log-p))))
  15764. (eq 'timestamp
  15765. (save-excursion
  15766. (when (= pos (cdr boundaries)) (forward-char -1))
  15767. (org-element-type (org-element-context)))))))))))
  15768. (cond
  15769. ((not match?) nil)
  15770. ((= pos (match-beginning 0)) 'bracket)
  15771. ;; Distinguish location right before the closing bracket from
  15772. ;; right after it.
  15773. ((= pos (1- (match-end 0))) 'bracket)
  15774. ((= pos (match-end 0)) 'after)
  15775. ((org-pos-in-match-range pos 2) 'year)
  15776. ((org-pos-in-match-range pos 3) 'month)
  15777. ((org-pos-in-match-range pos 7) 'hour)
  15778. ((org-pos-in-match-range pos 8) 'minute)
  15779. ((or (org-pos-in-match-range pos 4)
  15780. (org-pos-in-match-range pos 5)) 'day)
  15781. ((and (> pos (or (match-end 8) (match-end 5)))
  15782. (< pos (match-end 0)))
  15783. (- pos (or (match-end 8) (match-end 5))))
  15784. (t 'day))))
  15785. (defun org-toggle-timestamp-type ()
  15786. "Toggle the type (<active> or [inactive]) of a time stamp."
  15787. (interactive)
  15788. (when (org-at-timestamp-p 'lax)
  15789. (let ((beg (match-beginning 0)) (end (match-end 0))
  15790. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  15791. (save-excursion
  15792. (goto-char beg)
  15793. (while (re-search-forward "[][<>]" end t)
  15794. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  15795. t t)))
  15796. (message "Timestamp is now %sactive"
  15797. (if (equal (char-after beg) ?<) "" "in")))))
  15798. (defun org-at-clock-log-p ()
  15799. "Non-nil if point is on a clock log line."
  15800. (and (org-match-line org-clock-line-re)
  15801. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  15802. (defvar org-clock-history) ; defined in org-clock.el
  15803. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  15804. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  15805. "Change the date in the time stamp at point.
  15806. The date will be changed by N times WHAT. WHAT can be `day', `month',
  15807. `year', `minute', `second'. If WHAT is not given, the cursor position
  15808. in the timestamp determines what will be changed.
  15809. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  15810. (let ((origin (point))
  15811. (timestamp? (org-at-timestamp-p 'lax))
  15812. origin-cat
  15813. with-hm inactive
  15814. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  15815. extra rem
  15816. ts time time0 fixnext clrgx)
  15817. (unless timestamp? (user-error "Not at a timestamp"))
  15818. (if (and (not what) (eq timestamp? 'bracket))
  15819. (org-toggle-timestamp-type)
  15820. ;; Point isn't on brackets. Remember the part of the time-stamp
  15821. ;; the point was in. Indeed, size of time-stamps may change,
  15822. ;; but point must be kept in the same category nonetheless.
  15823. (setq origin-cat timestamp?)
  15824. (when (and (not what) (not (eq timestamp? 'day))
  15825. org-display-custom-times
  15826. (get-text-property (point) 'display)
  15827. (not (get-text-property (1- (point)) 'display)))
  15828. (setq timestamp? 'day))
  15829. (setq timestamp? (or what timestamp?)
  15830. inactive (= (char-after (match-beginning 0)) ?\[)
  15831. ts (match-string 0))
  15832. (replace-match "")
  15833. (when (string-match
  15834. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  15835. ts)
  15836. (setq extra (match-string 1 ts))
  15837. (when suppress-tmp-delay
  15838. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  15839. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  15840. (setq with-hm t))
  15841. (setq time0 (org-parse-time-string ts))
  15842. (when (and updown
  15843. (eq timestamp? 'minute)
  15844. (not current-prefix-arg))
  15845. ;; This looks like s-up and s-down. Change by one rounding step.
  15846. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  15847. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  15848. (setcar (cdr time0) (+ (nth 1 time0)
  15849. (if (> n 0) (- rem) (- dm rem))))))
  15850. (setq time
  15851. (apply #'encode-time
  15852. (or (car time0) 0)
  15853. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  15854. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  15855. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  15856. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  15857. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  15858. (nthcdr 6 time0)))
  15859. (when (and (memq timestamp? '(hour minute))
  15860. extra
  15861. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  15862. (setq extra (org-modify-ts-extra
  15863. extra
  15864. (if (eq timestamp? 'hour) 2 5)
  15865. n dm)))
  15866. (when (integerp timestamp?)
  15867. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  15868. (when (eq what 'calendar)
  15869. (let ((cal-date (org-get-date-from-calendar)))
  15870. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  15871. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  15872. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  15873. (setcar time0 (or (car time0) 0))
  15874. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  15875. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  15876. (setq time (apply 'encode-time time0))))
  15877. ;; Insert the new time-stamp, and ensure point stays in the same
  15878. ;; category as before (i.e. not after the last position in that
  15879. ;; category).
  15880. (let ((pos (point)))
  15881. ;; Stay before inserted string. `save-excursion' is of no use.
  15882. (setq org-last-changed-timestamp
  15883. (org-insert-time-stamp time with-hm inactive nil nil extra))
  15884. (goto-char pos))
  15885. (save-match-data
  15886. (looking-at org-ts-regexp3)
  15887. (goto-char
  15888. (pcase origin-cat
  15889. ;; `day' category ends before `hour' if any, or at the end
  15890. ;; of the day name.
  15891. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  15892. (`hour (min (match-end 7) origin))
  15893. (`minute (min (1- (match-end 8)) origin))
  15894. ((pred integerp) (min (1- (match-end 0)) origin))
  15895. ;; Point was right after the time-stamp. However, the
  15896. ;; time-stamp length might have changed, so refer to
  15897. ;; (match-end 0) instead.
  15898. (`after (match-end 0))
  15899. ;; `year' and `month' have both fixed size: point couldn't
  15900. ;; have moved into another part.
  15901. (_ origin))))
  15902. ;; Update clock if on a CLOCK line.
  15903. (org-clock-update-time-maybe)
  15904. ;; Maybe adjust the closest clock in `org-clock-history'
  15905. (when org-clock-adjust-closest
  15906. (if (not (and (org-at-clock-log-p)
  15907. (< 1 (length (delq nil (mapcar 'marker-position
  15908. org-clock-history))))))
  15909. (message "No clock to adjust")
  15910. (cond ((save-excursion ; fix previous clock?
  15911. (re-search-backward org-ts-regexp0 nil t)
  15912. (looking-back (concat org-clock-string " \\[")
  15913. (line-beginning-position)))
  15914. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  15915. ((save-excursion ; fix next clock?
  15916. (re-search-backward org-ts-regexp0 nil t)
  15917. (looking-at (concat org-ts-regexp0 "\\] =>")))
  15918. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  15919. (save-window-excursion
  15920. ;; Find closest clock to point, adjust the previous/next one in history
  15921. (let* ((p (save-excursion (org-back-to-heading t)))
  15922. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  15923. (clfixnth
  15924. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  15925. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  15926. (if (not clfixpos)
  15927. (message "No clock to adjust")
  15928. (save-excursion
  15929. (org-goto-marker-or-bmk clfixpos)
  15930. (org-show-subtree)
  15931. (when (re-search-forward clrgx nil t)
  15932. (goto-char (match-beginning 1))
  15933. (let (org-clock-adjust-closest)
  15934. (org-timestamp-change n timestamp? updown))
  15935. (message "Clock adjusted in %s for heading: %s"
  15936. (file-name-nondirectory (buffer-file-name))
  15937. (org-get-heading t t)))))))))
  15938. ;; Try to recenter the calendar window, if any.
  15939. (when (and org-calendar-follow-timestamp-change
  15940. (get-buffer-window "*Calendar*" t)
  15941. (memq timestamp? '(day month year)))
  15942. (org-recenter-calendar (time-to-days time))))))
  15943. (defun org-modify-ts-extra (s pos n dm)
  15944. "Change the different parts of the lead-time and repeat fields in timestamp."
  15945. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  15946. ng h m new rem)
  15947. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  15948. (cond
  15949. ((or (org-pos-in-match-range pos 2)
  15950. (org-pos-in-match-range pos 3))
  15951. (setq m (string-to-number (match-string 3 s))
  15952. h (string-to-number (match-string 2 s)))
  15953. (if (org-pos-in-match-range pos 2)
  15954. (setq h (+ h n))
  15955. (setq n (* dm (with-no-warnings (signum n))))
  15956. (unless (= 0 (setq rem (% m dm)))
  15957. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  15958. (setq m (+ m n)))
  15959. (when (< m 0) (setq m (+ m 60) h (1- h)))
  15960. (when (> m 59) (setq m (- m 60) h (1+ h)))
  15961. (setq h (mod h 24))
  15962. (setq ng 1 new (format "-%02d:%02d" h m)))
  15963. ((org-pos-in-match-range pos 6)
  15964. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  15965. ((org-pos-in-match-range pos 5)
  15966. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  15967. ((org-pos-in-match-range pos 9)
  15968. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  15969. ((org-pos-in-match-range pos 8)
  15970. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  15971. (when ng
  15972. (setq s (concat
  15973. (substring s 0 (match-beginning ng))
  15974. new
  15975. (substring s (match-end ng))))))
  15976. s))
  15977. (defun org-recenter-calendar (d)
  15978. "If the calendar is visible, recenter it to date D."
  15979. (let ((cwin (get-buffer-window "*Calendar*" t)))
  15980. (when cwin
  15981. (let ((calendar-move-hook nil))
  15982. (with-selected-window cwin
  15983. (calendar-goto-date
  15984. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  15985. (defun org-goto-calendar (&optional arg)
  15986. "Go to the Emacs calendar at the current date.
  15987. If there is a time stamp in the current line, go to that date.
  15988. A prefix ARG can be used to force the current date."
  15989. (interactive "P")
  15990. (let ((calendar-move-hook nil)
  15991. (calendar-view-holidays-initially-flag nil)
  15992. (calendar-view-diary-initially-flag nil)
  15993. diff)
  15994. (when (or (org-at-timestamp-p 'lax)
  15995. (org-match-line (concat ".*" org-ts-regexp)))
  15996. (let ((d1 (time-to-days (current-time)))
  15997. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  15998. (setq diff (- d2 d1))))
  15999. (calendar)
  16000. (calendar-goto-today)
  16001. (when (and diff (not arg)) (calendar-forward-day diff))))
  16002. (defun org-get-date-from-calendar ()
  16003. "Return a list (month day year) of date at point in calendar."
  16004. (with-current-buffer "*Calendar*"
  16005. (save-match-data
  16006. (calendar-cursor-to-date))))
  16007. (defun org-date-from-calendar ()
  16008. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16009. If there is already a time stamp at the cursor position, update it."
  16010. (interactive)
  16011. (if (org-at-timestamp-p 'lax)
  16012. (org-timestamp-change 0 'calendar)
  16013. (let ((cal-date (org-get-date-from-calendar)))
  16014. (org-insert-time-stamp
  16015. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16016. (defcustom org-effort-durations
  16017. `(("min" . 1)
  16018. ("h" . 60)
  16019. ("d" . ,(* 60 8))
  16020. ("w" . ,(* 60 8 5))
  16021. ("m" . ,(* 60 8 5 4))
  16022. ("y" . ,(* 60 8 5 40)))
  16023. "Conversion factor to minutes for an effort modifier.
  16024. Each entry has the form (MODIFIER . MINUTES).
  16025. In an effort string, a number followed by MODIFIER is multiplied
  16026. by the specified number of MINUTES to obtain an effort in
  16027. minutes.
  16028. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16029. effort string \"2hours\" is equivalent to 120 minutes."
  16030. :group 'org-agenda
  16031. :version "26.1"
  16032. :package-version '(Org . "8.3")
  16033. :type '(alist :key-type (string :tag "Modifier")
  16034. :value-type (number :tag "Minutes")))
  16035. (defcustom org-image-actual-width t
  16036. "Should we use the actual width of images when inlining them?
  16037. When set to t, always use the image width.
  16038. When set to a number, use imagemagick (when available) to set
  16039. the image's width to this value.
  16040. When set to a number in a list, try to get the width from any
  16041. #+ATTR.* keyword if it matches a width specification like
  16042. #+ATTR_HTML: :width 300px
  16043. and fall back on that number if none is found.
  16044. When set to nil, try to get the width from an #+ATTR.* keyword
  16045. and fall back on the original width if none is found.
  16046. This requires Emacs >= 24.1, build with imagemagick support."
  16047. :group 'org-appearance
  16048. :version "24.4"
  16049. :package-version '(Org . "8.0")
  16050. :type '(choice
  16051. (const :tag "Use the image width" t)
  16052. (integer :tag "Use a number of pixels")
  16053. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16054. (const :tag "Use #+ATTR* or don't resize" nil)))
  16055. (defcustom org-agenda-inhibit-startup nil
  16056. "Inhibit startup when preparing agenda buffers.
  16057. When this variable is t, the initialization of the Org agenda
  16058. buffers is inhibited: e.g. the visibility state is not set, the
  16059. tables are not re-aligned, etc."
  16060. :type 'boolean
  16061. :version "24.3"
  16062. :group 'org-agenda)
  16063. (defcustom org-agenda-ignore-properties nil
  16064. "Avoid updating text properties when building the agenda.
  16065. Properties are used to prepare buffers for effort estimates,
  16066. appointments, statistics and subtree-local categories.
  16067. If you don't use these in the agenda, you can add them to this
  16068. list and agenda building will be a bit faster.
  16069. The value is a list, with zero or more of the symbols `effort', `appt',
  16070. `stats' or `category'."
  16071. :type '(set :greedy t
  16072. (const effort)
  16073. (const appt)
  16074. (const stats)
  16075. (const category))
  16076. :version "26.1"
  16077. :package-version '(Org . "8.3")
  16078. :group 'org-agenda)
  16079. ;;;; Files
  16080. (defun org-save-all-org-buffers ()
  16081. "Save all Org buffers without user confirmation."
  16082. (interactive)
  16083. (message "Saving all Org buffers...")
  16084. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16085. (when (featurep 'org-id) (org-id-locations-save))
  16086. (message "Saving all Org buffers... done"))
  16087. (defun org-revert-all-org-buffers ()
  16088. "Revert all Org buffers.
  16089. Prompt for confirmation when there are unsaved changes.
  16090. Be sure you know what you are doing before letting this function
  16091. overwrite your changes.
  16092. This function is useful in a setup where one tracks Org files
  16093. with a version control system, to revert on one machine after pulling
  16094. changes from another. I believe the procedure must be like this:
  16095. 1. M-x org-save-all-org-buffers
  16096. 2. Pull changes from the other machine, resolve conflicts
  16097. 3. M-x org-revert-all-org-buffers"
  16098. (interactive)
  16099. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16100. (user-error "Abort"))
  16101. (save-excursion
  16102. (save-window-excursion
  16103. (dolist (b (buffer-list))
  16104. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16105. (with-current-buffer b buffer-file-name))
  16106. (pop-to-buffer-same-window b)
  16107. (revert-buffer t 'no-confirm)))
  16108. (when (and (featurep 'org-id) org-id-track-globally)
  16109. (org-id-locations-load)))))
  16110. ;;;; Agenda files
  16111. ;;;###autoload
  16112. (defun org-switchb (&optional arg)
  16113. "Switch between Org buffers.
  16114. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16115. With `\\[universal-argument] \\[universal-argument]' \
  16116. prefix, restrict available buffers to agenda files."
  16117. (interactive "P")
  16118. (let ((blist (org-buffer-list
  16119. (cond ((equal arg '(4)) 'files)
  16120. ((equal arg '(16)) 'agenda)))))
  16121. (pop-to-buffer-same-window
  16122. (completing-read "Org buffer: "
  16123. (mapcar #'list (mapcar #'buffer-name blist))
  16124. nil t))))
  16125. (defun org-buffer-list (&optional predicate exclude-tmp)
  16126. "Return a list of Org buffers.
  16127. PREDICATE can be `export', `files' or `agenda'.
  16128. export restrict the list to Export buffers.
  16129. files restrict the list to buffers visiting Org files.
  16130. agenda restrict the list to buffers visiting agenda files.
  16131. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16132. (let* ((bfn nil)
  16133. (agenda-files (and (eq predicate 'agenda)
  16134. (mapcar 'file-truename (org-agenda-files t))))
  16135. (filter
  16136. (cond
  16137. ((eq predicate 'files)
  16138. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16139. ((eq predicate 'export)
  16140. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16141. ((eq predicate 'agenda)
  16142. (lambda (b)
  16143. (with-current-buffer b
  16144. (and (derived-mode-p 'org-mode)
  16145. (setq bfn (buffer-file-name b))
  16146. (member (file-truename bfn) agenda-files)))))
  16147. (t (lambda (b) (with-current-buffer b
  16148. (or (derived-mode-p 'org-mode)
  16149. (string-match "\\*Org .*Export"
  16150. (buffer-name b)))))))))
  16151. (delq nil
  16152. (mapcar
  16153. (lambda(b)
  16154. (if (and (funcall filter b)
  16155. (or (not exclude-tmp)
  16156. (not (string-match "tmp" (buffer-name b)))))
  16157. b
  16158. nil))
  16159. (buffer-list)))))
  16160. (defun org-agenda-files (&optional unrestricted archives)
  16161. "Get the list of agenda files.
  16162. Optional UNRESTRICTED means return the full list even if a restriction
  16163. is currently in place.
  16164. When ARCHIVES is t, include all archive files that are really being
  16165. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16166. `org-agenda-archives-mode' is t."
  16167. (let ((files
  16168. (cond
  16169. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16170. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16171. ((listp org-agenda-files) org-agenda-files)
  16172. (t (error "Invalid value of `org-agenda-files'")))))
  16173. (setq files (apply 'append
  16174. (mapcar (lambda (f)
  16175. (if (file-directory-p f)
  16176. (directory-files
  16177. f t org-agenda-file-regexp)
  16178. (list f)))
  16179. files)))
  16180. (when org-agenda-skip-unavailable-files
  16181. (setq files (delq nil
  16182. (mapcar (function
  16183. (lambda (file)
  16184. (and (file-readable-p file) file)))
  16185. files))))
  16186. (when (or (eq archives t)
  16187. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16188. (setq files (org-add-archive-files files)))
  16189. files))
  16190. (defun org-agenda-file-p (&optional file)
  16191. "Return non-nil, if FILE is an agenda file.
  16192. If FILE is omitted, use the file associated with the current
  16193. buffer."
  16194. (let ((fname (or file (buffer-file-name))))
  16195. (and fname
  16196. (member (file-truename fname)
  16197. (mapcar #'file-truename (org-agenda-files t))))))
  16198. (defun org-edit-agenda-file-list ()
  16199. "Edit the list of agenda files.
  16200. Depending on setup, this either uses customize to edit the variable
  16201. `org-agenda-files', or it visits the file that is holding the list. In the
  16202. latter case, the buffer is set up in a way that saving it automatically kills
  16203. the buffer and restores the previous window configuration."
  16204. (interactive)
  16205. (if (stringp org-agenda-files)
  16206. (let ((cw (current-window-configuration)))
  16207. (find-file org-agenda-files)
  16208. (setq-local org-window-configuration cw)
  16209. (add-hook 'after-save-hook
  16210. (lambda ()
  16211. (set-window-configuration
  16212. (prog1 org-window-configuration
  16213. (kill-buffer (current-buffer))))
  16214. (org-install-agenda-files-menu)
  16215. (message "New agenda file list installed"))
  16216. nil 'local)
  16217. (message "%s" (substitute-command-keys
  16218. "Edit list and finish with \\[save-buffer]")))
  16219. (customize-variable 'org-agenda-files)))
  16220. (defun org-store-new-agenda-file-list (list)
  16221. "Set new value for the agenda file list and save it correctly."
  16222. (if (stringp org-agenda-files)
  16223. (let ((fe (org-read-agenda-file-list t)) b u)
  16224. (while (setq b (find-buffer-visiting org-agenda-files))
  16225. (kill-buffer b))
  16226. (with-temp-file org-agenda-files
  16227. (insert
  16228. (mapconcat
  16229. (lambda (f) ;; Keep un-expanded entries.
  16230. (if (setq u (assoc f fe))
  16231. (cdr u)
  16232. f))
  16233. list "\n")
  16234. "\n")))
  16235. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16236. (org-insert-mode-line-in-empty-file nil))
  16237. (setq org-agenda-files list)
  16238. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16239. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16240. "Read the list of agenda files from a file.
  16241. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16242. filenames, used by `org-store-new-agenda-file-list' to write back
  16243. un-expanded file names."
  16244. (when (file-directory-p org-agenda-files)
  16245. (error "`org-agenda-files' cannot be a single directory"))
  16246. (when (stringp org-agenda-files)
  16247. (with-temp-buffer
  16248. (insert-file-contents org-agenda-files)
  16249. (mapcar
  16250. (lambda (f)
  16251. (let ((e (expand-file-name (substitute-in-file-name f)
  16252. org-directory)))
  16253. (if pair-with-expansion
  16254. (cons e f)
  16255. e)))
  16256. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16257. ;;;###autoload
  16258. (defun org-cycle-agenda-files ()
  16259. "Cycle through the files in `org-agenda-files'.
  16260. If the current buffer visits an agenda file, find the next one in the list.
  16261. If the current buffer does not, find the first agenda file."
  16262. (interactive)
  16263. (let* ((fs (or (org-agenda-files t)
  16264. (user-error "No agenda files")))
  16265. (files (copy-sequence fs))
  16266. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16267. file)
  16268. (when tcf
  16269. (while (and (setq file (pop files))
  16270. (not (equal (file-truename file) tcf)))))
  16271. (find-file (car (or files fs)))
  16272. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16273. (defun org-agenda-file-to-front (&optional to-end)
  16274. "Move/add the current file to the top of the agenda file list.
  16275. If the file is not present in the list, it is added to the front. If it is
  16276. present, it is moved there. With optional argument TO-END, add/move to the
  16277. end of the list."
  16278. (interactive "P")
  16279. (let ((org-agenda-skip-unavailable-files nil)
  16280. (file-alist (mapcar (lambda (x)
  16281. (cons (file-truename x) x))
  16282. (org-agenda-files t)))
  16283. (ctf (file-truename
  16284. (or buffer-file-name
  16285. (user-error "Please save the current buffer to a file"))))
  16286. x had)
  16287. (setq x (assoc ctf file-alist) had x)
  16288. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16289. (if to-end
  16290. (setq file-alist (append (delq x file-alist) (list x)))
  16291. (setq file-alist (cons x (delq x file-alist))))
  16292. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16293. (org-install-agenda-files-menu)
  16294. (message "File %s to %s of agenda file list"
  16295. (if had "moved" "added") (if to-end "end" "front"))))
  16296. (defun org-remove-file (&optional file)
  16297. "Remove current file from the list of files in variable `org-agenda-files'.
  16298. These are the files which are being checked for agenda entries.
  16299. Optional argument FILE means use this file instead of the current."
  16300. (interactive)
  16301. (let* ((org-agenda-skip-unavailable-files nil)
  16302. (file (or file buffer-file-name
  16303. (user-error "Current buffer does not visit a file")))
  16304. (true-file (file-truename file))
  16305. (afile (abbreviate-file-name file))
  16306. (files (delq nil (mapcar
  16307. (lambda (x)
  16308. (unless (equal true-file
  16309. (file-truename x))
  16310. x))
  16311. (org-agenda-files t)))))
  16312. (if (not (= (length files) (length (org-agenda-files t))))
  16313. (progn
  16314. (org-store-new-agenda-file-list files)
  16315. (org-install-agenda-files-menu)
  16316. (message "Removed from Org Agenda list: %s" afile))
  16317. (message "File was not in list: %s (not removed)" afile))))
  16318. (defun org-file-menu-entry (file)
  16319. (vector file (list 'find-file file) t))
  16320. (defun org-check-agenda-file (file)
  16321. "Make sure FILE exists. If not, ask user what to do."
  16322. (unless (file-exists-p file)
  16323. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16324. (abbreviate-file-name file))
  16325. (let ((r (downcase (read-char-exclusive))))
  16326. (cond
  16327. ((equal r ?r)
  16328. (org-remove-file file)
  16329. (throw 'nextfile t))
  16330. (t (user-error "Abort"))))))
  16331. (defun org-get-agenda-file-buffer (file)
  16332. "Get an agenda buffer visiting FILE.
  16333. If the buffer needs to be created, add it to the list of buffers
  16334. which might be released later."
  16335. (let ((buf (org-find-base-buffer-visiting file)))
  16336. (if buf
  16337. buf ; just return it
  16338. ;; Make a new buffer and remember it
  16339. (setq buf (find-file-noselect file))
  16340. (when buf (push buf org-agenda-new-buffers))
  16341. buf)))
  16342. (defun org-release-buffers (blist)
  16343. "Release all buffers in list, asking the user for confirmation when needed.
  16344. When a buffer is unmodified, it is just killed. When modified, it is saved
  16345. \(if the user agrees) and then killed."
  16346. (let (file)
  16347. (dolist (buf blist)
  16348. (setq file (buffer-file-name buf))
  16349. (when (and (buffer-modified-p buf)
  16350. file
  16351. (y-or-n-p (format "Save file %s? " file)))
  16352. (with-current-buffer buf (save-buffer)))
  16353. (kill-buffer buf))))
  16354. (defun org-agenda-prepare-buffers (files)
  16355. "Create buffers for all agenda files, protect archived trees and comments."
  16356. (interactive)
  16357. (let ((pa '(:org-archived t))
  16358. (pc '(:org-comment t))
  16359. (pall '(:org-archived t :org-comment t))
  16360. (inhibit-read-only t)
  16361. (org-inhibit-startup org-agenda-inhibit-startup)
  16362. (rea (org-make-tag-string (list org-archive-tag)))
  16363. re pos)
  16364. (setq org-tag-alist-for-agenda nil
  16365. org-tag-groups-alist-for-agenda nil)
  16366. (save-excursion
  16367. (save-restriction
  16368. (dolist (file files)
  16369. (catch 'nextfile
  16370. (if (bufferp file)
  16371. (set-buffer file)
  16372. (org-check-agenda-file file)
  16373. (set-buffer (org-get-agenda-file-buffer file)))
  16374. (widen)
  16375. (org-set-regexps-and-options 'tags-only)
  16376. (setq pos (point))
  16377. (or (memq 'category org-agenda-ignore-properties)
  16378. (org-refresh-category-properties))
  16379. (or (memq 'stats org-agenda-ignore-properties)
  16380. (org-refresh-stats-properties))
  16381. (or (memq 'effort org-agenda-ignore-properties)
  16382. (org-refresh-effort-properties))
  16383. (or (memq 'appt org-agenda-ignore-properties)
  16384. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16385. (setq org-todo-keywords-for-agenda
  16386. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16387. (setq org-done-keywords-for-agenda
  16388. (append org-done-keywords-for-agenda org-done-keywords))
  16389. (setq org-todo-keyword-alist-for-agenda
  16390. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16391. (setq org-tag-alist-for-agenda
  16392. (org--tag-add-to-alist
  16393. org-tag-alist-for-agenda
  16394. org-current-tag-alist))
  16395. ;; Merge current file's tag groups into global
  16396. ;; `org-tag-groups-alist-for-agenda'.
  16397. (when org-group-tags
  16398. (dolist (alist org-tag-groups-alist)
  16399. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16400. (if old
  16401. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16402. (push alist org-tag-groups-alist-for-agenda)))))
  16403. (with-silent-modifications
  16404. (save-excursion
  16405. (remove-text-properties (point-min) (point-max) pall)
  16406. (when org-agenda-skip-archived-trees
  16407. (goto-char (point-min))
  16408. (while (re-search-forward rea nil t)
  16409. (when (org-at-heading-p t)
  16410. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16411. (goto-char (point-min))
  16412. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16413. (while (re-search-forward re nil t)
  16414. (when (save-match-data (org-in-commented-heading-p t))
  16415. (add-text-properties
  16416. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16417. (goto-char pos)))))
  16418. (setq org-todo-keywords-for-agenda
  16419. (org-uniquify org-todo-keywords-for-agenda))
  16420. (setq org-todo-keyword-alist-for-agenda
  16421. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16422. ;;;; CDLaTeX minor mode
  16423. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16424. "Keymap for the minor `org-cdlatex-mode'.")
  16425. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  16426. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  16427. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  16428. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  16429. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  16430. (defvar org-cdlatex-texmathp-advice-is-done nil
  16431. "Flag remembering if we have applied the advice to texmathp already.")
  16432. (define-minor-mode org-cdlatex-mode
  16433. "Toggle the minor `org-cdlatex-mode'.
  16434. This mode supports entering LaTeX environment and math in LaTeX fragments
  16435. in Org mode.
  16436. \\{org-cdlatex-mode-map}"
  16437. nil " OCDL" nil
  16438. (when org-cdlatex-mode
  16439. (require 'cdlatex)
  16440. (run-hooks 'cdlatex-mode-hook)
  16441. (cdlatex-compute-tables))
  16442. (unless org-cdlatex-texmathp-advice-is-done
  16443. (setq org-cdlatex-texmathp-advice-is-done t)
  16444. (defadvice texmathp (around org-math-always-on activate)
  16445. "Always return t in Org buffers.
  16446. This is because we want to insert math symbols without dollars even outside
  16447. the LaTeX math segments. If Org mode thinks that point is actually inside
  16448. an embedded LaTeX fragment, let `texmathp' do its job.
  16449. `\\[org-cdlatex-mode-map]'"
  16450. (interactive)
  16451. (let (p)
  16452. (cond
  16453. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16454. ((eq this-command 'cdlatex-math-symbol)
  16455. (setq ad-return-value t
  16456. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16457. (t
  16458. (let ((p (org-inside-LaTeX-fragment-p)))
  16459. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16460. (setq ad-return-value t
  16461. texmathp-why '("Org mode embedded math" . 0))
  16462. (when p ad-do-it)))))))))
  16463. (defun turn-on-org-cdlatex ()
  16464. "Unconditionally turn on `org-cdlatex-mode'."
  16465. (org-cdlatex-mode 1))
  16466. (defun org-try-cdlatex-tab ()
  16467. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16468. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16469. - inside a LaTeX fragment, or
  16470. - after the first word in a line, where an abbreviation expansion could
  16471. insert a LaTeX environment."
  16472. (when org-cdlatex-mode
  16473. (cond
  16474. ;; Before any word on the line: No expansion possible.
  16475. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16476. ;; Just after first word on the line: Expand it. Make sure it
  16477. ;; cannot happen on headlines, though.
  16478. ((save-excursion
  16479. (skip-chars-backward "a-zA-Z0-9*")
  16480. (skip-chars-backward " \t")
  16481. (and (bolp) (not (org-at-heading-p))))
  16482. (cdlatex-tab) t)
  16483. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16484. (defun org-cdlatex-underscore-caret (&optional _arg)
  16485. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16486. Revert to the normal definition outside of these fragments."
  16487. (interactive "P")
  16488. (if (org-inside-LaTeX-fragment-p)
  16489. (call-interactively 'cdlatex-sub-superscript)
  16490. (let (org-cdlatex-mode)
  16491. (call-interactively (key-binding (vector last-input-event))))))
  16492. (defun org-cdlatex-math-modify (&optional _arg)
  16493. "Execute `cdlatex-math-modify' in LaTeX fragments.
  16494. Revert to the normal definition outside of these fragments."
  16495. (interactive "P")
  16496. (if (org-inside-LaTeX-fragment-p)
  16497. (call-interactively 'cdlatex-math-modify)
  16498. (let (org-cdlatex-mode)
  16499. (call-interactively (key-binding (vector last-input-event))))))
  16500. (defun org-cdlatex-environment-indent (&optional environment item)
  16501. "Execute `cdlatex-environment' and indent the inserted environment.
  16502. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  16503. The inserted environment is indented to current indentation
  16504. unless point is at the beginning of the line, in which the
  16505. environment remains unintended."
  16506. (interactive)
  16507. ;; cdlatex-environment always return nil. Therefore, capture output
  16508. ;; first and determine if an environment was selected.
  16509. (let* ((beg (point-marker))
  16510. (end (copy-marker (point) t))
  16511. (inserted (progn
  16512. (ignore-errors (cdlatex-environment environment item))
  16513. (< beg end)))
  16514. ;; Figure out how many lines to move forward after the
  16515. ;; environment has been inserted.
  16516. (lines (when inserted
  16517. (save-excursion
  16518. (- (cl-loop while (< beg (point))
  16519. with x = 0
  16520. do (forward-line -1)
  16521. (cl-incf x)
  16522. finally return x)
  16523. (if (progn (goto-char beg)
  16524. (and (progn (skip-chars-forward " \t") (eolp))
  16525. (progn (skip-chars-backward " \t") (bolp))))
  16526. 1 0)))))
  16527. (env (org-trim (delete-and-extract-region beg end))))
  16528. (when inserted
  16529. ;; Get indentation of next line unless at column 0.
  16530. (let ((ind (if (bolp) 0
  16531. (save-excursion
  16532. (org-return-indent)
  16533. (prog1 (current-indentation)
  16534. (when (progn (skip-chars-forward " \t") (eolp))
  16535. (delete-region beg (point)))))))
  16536. (bol (progn (skip-chars-backward " \t") (bolp))))
  16537. ;; Insert a newline before environment unless at column zero
  16538. ;; to "escape" the current line. Insert a newline if
  16539. ;; something is one the same line as \end{ENVIRONMENT}.
  16540. (insert
  16541. (concat (unless bol "\n") env
  16542. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  16543. (unless (zerop ind)
  16544. (save-excursion
  16545. (goto-char beg)
  16546. (while (< (point) end)
  16547. (unless (eolp) (indent-line-to ind))
  16548. (forward-line))))
  16549. (goto-char beg)
  16550. (forward-line lines)
  16551. (indent-line-to ind)))
  16552. (set-marker beg nil)
  16553. (set-marker end nil)))
  16554. ;;;; LaTeX fragments
  16555. (defun org-inside-LaTeX-fragment-p ()
  16556. "Test if point is inside a LaTeX fragment.
  16557. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  16558. sequence appearing also before point.
  16559. Even though the matchers for math are configurable, this function assumes
  16560. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  16561. delimiters are skipped when they have been removed by customization.
  16562. The return value is nil, or a cons cell with the delimiter and the
  16563. position of this delimiter.
  16564. This function does a reasonably good job, but can locally be fooled by
  16565. for example currency specifications. For example it will assume being in
  16566. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  16567. fragments that are properly closed, but during editing, we have to live
  16568. with the uncertainty caused by missing closing delimiters. This function
  16569. looks only before point, not after."
  16570. (catch 'exit
  16571. (let ((pos (point))
  16572. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  16573. (lim (save-excursion (org-backward-paragraph) (point)))
  16574. dd-on str (start 0) m re)
  16575. (goto-char pos)
  16576. (when dodollar
  16577. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  16578. re (nth 1 (assoc "$" org-latex-regexps)))
  16579. (while (string-match re str start)
  16580. (cond
  16581. ((= (match-end 0) (length str))
  16582. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  16583. ((= (match-end 0) (- (length str) 5))
  16584. (throw 'exit nil))
  16585. (t (setq start (match-end 0))))))
  16586. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  16587. (goto-char pos)
  16588. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  16589. (and (match-beginning 2) (throw 'exit nil))
  16590. ;; count $$
  16591. (while (re-search-backward "\\$\\$" lim t)
  16592. (setq dd-on (not dd-on)))
  16593. (goto-char pos)
  16594. (when dd-on (cons "$$" m))))))
  16595. (defun org-inside-latex-macro-p ()
  16596. "Is point inside a LaTeX macro or its arguments?"
  16597. (save-match-data
  16598. (org-in-regexp
  16599. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  16600. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  16601. "Build an overlay between BEG and END using IMAGE file.
  16602. Argument IMAGETYPE is the extension of the displayed image,
  16603. as a string. It defaults to \"png\"."
  16604. (let ((ov (make-overlay beg end))
  16605. (imagetype (or (intern imagetype) 'png)))
  16606. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  16607. (overlay-put ov 'evaporate t)
  16608. (overlay-put ov
  16609. 'modification-hooks
  16610. (list (lambda (o _flag _beg _end &optional _l)
  16611. (delete-overlay o))))
  16612. (overlay-put ov
  16613. 'display
  16614. (list 'image :type imagetype :file image :ascent 'center))))
  16615. (defun org--list-latex-overlays (&optional beg end)
  16616. "List all Org LaTeX overlays in current buffer.
  16617. Limit to overlays between BEG and END when those are provided."
  16618. (cl-remove-if-not
  16619. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  16620. (overlays-in (or beg (point-min)) (or end (point-max)))))
  16621. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  16622. "Remove all overlays with LaTeX fragment images in current buffer.
  16623. When optional arguments BEG and END are non-nil, remove all
  16624. overlays between them instead. Return a non-nil value when some
  16625. overlays were removed, nil otherwise."
  16626. (let ((overlays (org--list-latex-overlays beg end)))
  16627. (mapc #'delete-overlay overlays)
  16628. overlays))
  16629. (defun org-toggle-latex-fragment (&optional arg)
  16630. "Preview the LaTeX fragment at point, or all locally or globally.
  16631. If the cursor is on a LaTeX fragment, create the image and overlay
  16632. it over the source code, if there is none. Remove it otherwise.
  16633. If there is no fragment at point, display all fragments in the
  16634. current section.
  16635. With prefix ARG, preview or clear image for all fragments in the
  16636. current subtree or in the whole buffer when used before the first
  16637. headline. With a prefix ARG `\\[universal-argument] \
  16638. \\[universal-argument]' preview or clear images
  16639. for all fragments in the buffer."
  16640. (interactive "P")
  16641. (when (display-graphic-p)
  16642. (catch 'exit
  16643. (save-excursion
  16644. (let (beg end msg)
  16645. (cond
  16646. ((or (equal arg '(16))
  16647. (and (equal arg '(4))
  16648. (org-with-limited-levels (org-before-first-heading-p))))
  16649. (if (org-remove-latex-fragment-image-overlays)
  16650. (progn (message "LaTeX fragments images removed from buffer")
  16651. (throw 'exit nil))
  16652. (setq msg "Creating images for buffer...")))
  16653. ((equal arg '(4))
  16654. (org-with-limited-levels (org-back-to-heading t))
  16655. (setq beg (point))
  16656. (setq end (progn (org-end-of-subtree t) (point)))
  16657. (if (org-remove-latex-fragment-image-overlays beg end)
  16658. (progn
  16659. (message "LaTeX fragment images removed from subtree")
  16660. (throw 'exit nil))
  16661. (setq msg "Creating images for subtree...")))
  16662. ((let ((datum (org-element-context)))
  16663. (when (memq (org-element-type datum)
  16664. '(latex-environment latex-fragment))
  16665. (setq beg (org-element-property :begin datum))
  16666. (setq end (org-element-property :end datum))
  16667. (if (org-remove-latex-fragment-image-overlays beg end)
  16668. (progn (message "LaTeX fragment image removed")
  16669. (throw 'exit nil))
  16670. (setq msg "Creating image...")))))
  16671. (t
  16672. (org-with-limited-levels
  16673. (setq beg (if (org-at-heading-p) (line-beginning-position)
  16674. (outline-previous-heading)
  16675. (point)))
  16676. (setq end (progn (outline-next-heading) (point)))
  16677. (if (org-remove-latex-fragment-image-overlays beg end)
  16678. (progn
  16679. (message "LaTeX fragment images removed from section")
  16680. (throw 'exit nil))
  16681. (setq msg "Creating images for section...")))))
  16682. (let ((file (buffer-file-name (buffer-base-buffer))))
  16683. (org-format-latex
  16684. (concat org-preview-latex-image-directory "org-ltximg")
  16685. beg end
  16686. ;; Emacs cannot overlay images from remote hosts. Create
  16687. ;; it in `temporary-file-directory' instead.
  16688. (if (or (not file) (file-remote-p file))
  16689. temporary-file-directory
  16690. default-directory)
  16691. 'overlays msg 'forbuffer org-preview-latex-default-process))
  16692. (message (concat msg "done")))))))
  16693. (defun org-format-latex
  16694. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  16695. "Replace LaTeX fragments with links to an image.
  16696. The function takes care of creating the replacement image.
  16697. Only consider fragments between BEG and END when those are
  16698. provided.
  16699. When optional argument OVERLAYS is non-nil, display the image on
  16700. top of the fragment instead of replacing it.
  16701. PROCESSING-TYPE is the conversion method to use, as a symbol.
  16702. Some of the options can be changed using the variable
  16703. `org-format-latex-options', which see."
  16704. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  16705. (unless (eq processing-type 'verbatim)
  16706. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  16707. (cnt 0)
  16708. checkdir-flag)
  16709. (goto-char (or beg (point-min)))
  16710. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  16711. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  16712. (overlay-recenter (or end (point-max))))
  16713. (while (re-search-forward math-regexp end t)
  16714. (unless (and overlays
  16715. (eq (get-char-property (point) 'org-overlay-type)
  16716. 'org-latex-overlay))
  16717. (let* ((context (org-element-context))
  16718. (type (org-element-type context)))
  16719. (when (memq type '(latex-environment latex-fragment))
  16720. (let ((block-type (eq type 'latex-environment))
  16721. (value (org-element-property :value context))
  16722. (beg (org-element-property :begin context))
  16723. (end (save-excursion
  16724. (goto-char (org-element-property :end context))
  16725. (skip-chars-backward " \r\t\n")
  16726. (point))))
  16727. (cond
  16728. ((eq processing-type 'mathjax)
  16729. ;; Prepare for MathJax processing.
  16730. (if (not (string-match "\\`\\$\\$?" value))
  16731. (goto-char end)
  16732. (delete-region beg end)
  16733. (if (string= (match-string 0 value) "$$")
  16734. (insert "\\[" (substring value 2 -2) "\\]")
  16735. (insert "\\(" (substring value 1 -1) "\\)"))))
  16736. ((assq processing-type org-preview-latex-process-alist)
  16737. ;; Process to an image.
  16738. (cl-incf cnt)
  16739. (goto-char beg)
  16740. (let* ((processing-info
  16741. (cdr (assq processing-type org-preview-latex-process-alist)))
  16742. (face (face-at-point))
  16743. ;; Get the colors from the face at point.
  16744. (fg
  16745. (let ((color (plist-get org-format-latex-options
  16746. :foreground)))
  16747. (if (and forbuffer (eq color 'auto))
  16748. (face-attribute face :foreground nil 'default)
  16749. color)))
  16750. (bg
  16751. (let ((color (plist-get org-format-latex-options
  16752. :background)))
  16753. (if (and forbuffer (eq color 'auto))
  16754. (face-attribute face :background nil 'default)
  16755. color)))
  16756. (hash (sha1 (prin1-to-string
  16757. (list org-format-latex-header
  16758. org-latex-default-packages-alist
  16759. org-latex-packages-alist
  16760. org-format-latex-options
  16761. forbuffer value fg bg))))
  16762. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  16763. (absprefix (expand-file-name prefix dir))
  16764. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  16765. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  16766. (sep (and block-type "\n\n"))
  16767. (link (concat sep "[[file:" linkfile "]]" sep))
  16768. (options
  16769. (org-combine-plists
  16770. org-format-latex-options
  16771. `(:foreground ,fg :background ,bg))))
  16772. (when msg (message msg cnt))
  16773. (unless checkdir-flag ; Ensure the directory exists.
  16774. (setq checkdir-flag t)
  16775. (let ((todir (file-name-directory absprefix)))
  16776. (unless (file-directory-p todir)
  16777. (make-directory todir t))))
  16778. (unless (file-exists-p movefile)
  16779. (org-create-formula-image
  16780. value movefile options forbuffer processing-type))
  16781. (if overlays
  16782. (progn
  16783. (dolist (o (overlays-in beg end))
  16784. (when (eq (overlay-get o 'org-overlay-type)
  16785. 'org-latex-overlay)
  16786. (delete-overlay o)))
  16787. (org--format-latex-make-overlay beg end movefile imagetype)
  16788. (goto-char end))
  16789. (delete-region beg end)
  16790. (insert
  16791. (org-add-props link
  16792. (list 'org-latex-src
  16793. (replace-regexp-in-string "\"" "" value)
  16794. 'org-latex-src-embed-type
  16795. (if block-type 'paragraph 'character)))))))
  16796. ((eq processing-type 'mathml)
  16797. ;; Process to MathML.
  16798. (unless (org-format-latex-mathml-available-p)
  16799. (user-error "LaTeX to MathML converter not configured"))
  16800. (cl-incf cnt)
  16801. (when msg (message msg cnt))
  16802. (goto-char beg)
  16803. (delete-region beg end)
  16804. (insert (org-format-latex-as-mathml
  16805. value block-type prefix dir)))
  16806. (t
  16807. (error "Unknown conversion process %s for LaTeX fragments"
  16808. processing-type)))))))))))
  16809. (defun org-create-math-formula (latex-frag &optional mathml-file)
  16810. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  16811. Use `org-latex-to-mathml-convert-command'. If the conversion is
  16812. sucessful, return the portion between \"<math...> </math>\"
  16813. elements otherwise return nil. When MATHML-FILE is specified,
  16814. write the results in to that file. When invoked as an
  16815. interactive command, prompt for LATEX-FRAG, with initial value
  16816. set to the current active region and echo the results for user
  16817. inspection."
  16818. (interactive (list (let ((frag (when (org-region-active-p)
  16819. (buffer-substring-no-properties
  16820. (region-beginning) (region-end)))))
  16821. (read-string "LaTeX Fragment: " frag nil frag))))
  16822. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  16823. (let* ((tmp-in-file
  16824. (let ((file (file-relative-name
  16825. (make-temp-name (expand-file-name "ltxmathml-in")))))
  16826. (write-region latex-frag nil file)
  16827. file))
  16828. (tmp-out-file (file-relative-name
  16829. (make-temp-name (expand-file-name "ltxmathml-out"))))
  16830. (cmd (format-spec
  16831. org-latex-to-mathml-convert-command
  16832. `((?j . ,(and org-latex-to-mathml-jar-file
  16833. (shell-quote-argument
  16834. (expand-file-name
  16835. org-latex-to-mathml-jar-file))))
  16836. (?I . ,(shell-quote-argument tmp-in-file))
  16837. (?i . ,latex-frag)
  16838. (?o . ,(shell-quote-argument tmp-out-file)))))
  16839. mathml shell-command-output)
  16840. (when (called-interactively-p 'any)
  16841. (unless (org-format-latex-mathml-available-p)
  16842. (user-error "LaTeX to MathML converter not configured")))
  16843. (message "Running %s" cmd)
  16844. (setq shell-command-output (shell-command-to-string cmd))
  16845. (setq mathml
  16846. (when (file-readable-p tmp-out-file)
  16847. (with-current-buffer (find-file-noselect tmp-out-file t)
  16848. (goto-char (point-min))
  16849. (when (re-search-forward
  16850. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  16851. (regexp-quote
  16852. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  16853. nil t)
  16854. (prog1 (match-string 0) (kill-buffer))))))
  16855. (cond
  16856. (mathml
  16857. (setq mathml
  16858. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  16859. (when mathml-file
  16860. (write-region mathml nil mathml-file))
  16861. (when (called-interactively-p 'any)
  16862. (message mathml)))
  16863. ((message "LaTeX to MathML conversion failed")
  16864. (message shell-command-output)))
  16865. (delete-file tmp-in-file)
  16866. (when (file-exists-p tmp-out-file)
  16867. (delete-file tmp-out-file))
  16868. mathml))
  16869. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  16870. prefix &optional dir)
  16871. "Use `org-create-math-formula' but check local cache first."
  16872. (let* ((absprefix (expand-file-name prefix dir))
  16873. (print-length nil) (print-level nil)
  16874. (formula-id (concat
  16875. "formula-"
  16876. (sha1
  16877. (prin1-to-string
  16878. (list latex-frag
  16879. org-latex-to-mathml-convert-command)))))
  16880. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  16881. (formula-cache-dir (file-name-directory formula-cache)))
  16882. (unless (file-directory-p formula-cache-dir)
  16883. (make-directory formula-cache-dir t))
  16884. (unless (file-exists-p formula-cache)
  16885. (org-create-math-formula latex-frag formula-cache))
  16886. (if (file-exists-p formula-cache)
  16887. ;; Successful conversion. Return the link to MathML file.
  16888. (org-add-props
  16889. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  16890. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  16891. 'org-latex-src-embed-type (if latex-frag-type
  16892. 'paragraph 'character)))
  16893. ;; Failed conversion. Return the LaTeX fragment verbatim
  16894. latex-frag)))
  16895. (defun org--get-display-dpi ()
  16896. "Get the DPI of the display.
  16897. The function assumes that the display has the same pixel width in
  16898. the horizontal and vertical directions."
  16899. (if (display-graphic-p)
  16900. (round (/ (display-pixel-height)
  16901. (/ (display-mm-height) 25.4)))
  16902. (error "Attempt to calculate the dpi of a non-graphic display")))
  16903. (defun org-create-formula-image
  16904. (string tofile options buffer &optional processing-type)
  16905. "Create an image from LaTeX source using external processes.
  16906. The LaTeX STRING is saved to a temporary LaTeX file, then
  16907. converted to an image file by process PROCESSING-TYPE defined in
  16908. `org-preview-latex-process-alist'. A nil value defaults to
  16909. `org-preview-latex-default-process'.
  16910. The generated image file is eventually moved to TOFILE.
  16911. The OPTIONS argument controls the size, foreground color and
  16912. background color of the generated image.
  16913. When BUFFER non-nil, this function is used for LaTeX previewing.
  16914. Otherwise, it is used to deal with LaTeX snippets showed in
  16915. a HTML file."
  16916. (let* ((processing-type (or processing-type
  16917. org-preview-latex-default-process))
  16918. (processing-info
  16919. (cdr (assq processing-type org-preview-latex-process-alist)))
  16920. (programs (plist-get processing-info :programs))
  16921. (error-message (or (plist-get processing-info :message) ""))
  16922. (use-xcolor (plist-get processing-info :use-xcolor))
  16923. (image-input-type (plist-get processing-info :image-input-type))
  16924. (image-output-type (plist-get processing-info :image-output-type))
  16925. (post-clean (or (plist-get processing-info :post-clean)
  16926. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  16927. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  16928. (latex-header
  16929. (or (plist-get processing-info :latex-header)
  16930. (org-latex-make-preamble
  16931. (org-export-get-environment (org-export-get-backend 'latex))
  16932. org-format-latex-header
  16933. 'snippet)))
  16934. (latex-compiler (plist-get processing-info :latex-compiler))
  16935. (image-converter (plist-get processing-info :image-converter))
  16936. (tmpdir temporary-file-directory)
  16937. (texfilebase (make-temp-name
  16938. (expand-file-name "orgtex" tmpdir)))
  16939. (texfile (concat texfilebase ".tex"))
  16940. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  16941. '(1.0 . 1.0)))
  16942. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  16943. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  16944. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  16945. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  16946. "Black"))
  16947. (bg (or (plist-get options (if buffer :background :html-background))
  16948. "Transparent"))
  16949. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  16950. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  16951. (dolist (program programs)
  16952. (org-check-external-command program error-message))
  16953. (if use-xcolor
  16954. (progn (if (eq fg 'default)
  16955. (setq fg (org-latex-color :foreground))
  16956. (setq fg (org-latex-color-format fg)))
  16957. (if (eq bg 'default)
  16958. (setq bg (org-latex-color :background))
  16959. (setq bg (org-latex-color-format
  16960. (if (string= bg "Transparent") "white" bg))))
  16961. (with-temp-file texfile
  16962. (insert latex-header)
  16963. (insert "\n\\begin{document}\n"
  16964. "\\definecolor{fg}{rgb}{" fg "}\n"
  16965. "\\definecolor{bg}{rgb}{" bg "}\n"
  16966. "\n\\pagecolor{bg}\n"
  16967. "\n{\\color{fg}\n"
  16968. string
  16969. "\n}\n"
  16970. "\n\\end{document}\n")))
  16971. (if (eq fg 'default)
  16972. (setq fg (org-dvipng-color :foreground))
  16973. (unless (string= fg "Transparent")
  16974. (setq fg (org-dvipng-color-format fg))))
  16975. (if (eq bg 'default)
  16976. (setq bg (org-dvipng-color :background))
  16977. (unless (string= bg "Transparent")
  16978. (setq bg (org-dvipng-color-format bg))))
  16979. (with-temp-file texfile
  16980. (insert latex-header)
  16981. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  16982. (let* ((err-msg (format "Please adjust `%s' part of \
  16983. `org-preview-latex-process-alist'."
  16984. processing-type))
  16985. (image-input-file
  16986. (org-compile-file
  16987. texfile latex-compiler image-input-type err-msg log-buf))
  16988. (image-output-file
  16989. (org-compile-file
  16990. image-input-file image-converter image-output-type err-msg log-buf
  16991. `((?F . ,(shell-quote-argument fg))
  16992. (?B . ,(shell-quote-argument bg))
  16993. (?D . ,(shell-quote-argument (format "%s" dpi)))
  16994. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  16995. (copy-file image-output-file tofile 'replace)
  16996. (dolist (e post-clean)
  16997. (when (file-exists-p (concat texfilebase e))
  16998. (delete-file (concat texfilebase e))))
  16999. image-output-file)))
  17000. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17001. "Fill a LaTeX header template TPL.
  17002. In the template, the following place holders will be recognized:
  17003. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17004. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17005. [PACKAGES] \\usepackage statements for PKG
  17006. [NO-PACKAGES] do not include PKG
  17007. [EXTRA] the string EXTRA
  17008. [NO-EXTRA] do not include EXTRA
  17009. For backward compatibility, if both the positive and the negative place
  17010. holder is missing, the positive one (without the \"NO-\") will be
  17011. assumed to be present at the end of the template.
  17012. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17013. EXTRA is a string.
  17014. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17015. (let (rpl (end ""))
  17016. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17017. (setq rpl (if (or (match-end 1) (not def-pkg))
  17018. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17019. tpl (replace-match rpl t t tpl))
  17020. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17021. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17022. (setq rpl (if (or (match-end 1) (not pkg))
  17023. "" (org-latex-packages-to-string pkg snippets-p t))
  17024. tpl (replace-match rpl t t tpl))
  17025. (when pkg (setq end
  17026. (concat end "\n"
  17027. (org-latex-packages-to-string pkg snippets-p)))))
  17028. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17029. (setq rpl (if (or (match-end 1) (not extra))
  17030. "" (concat extra "\n"))
  17031. tpl (replace-match rpl t t tpl))
  17032. (when (and extra (string-match "\\S-" extra))
  17033. (setq end (concat end "\n" extra))))
  17034. (if (string-match "\\S-" end)
  17035. (concat tpl "\n" end)
  17036. tpl)))
  17037. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17038. "Turn an alist of packages into a string with the \\usepackage macros."
  17039. (setq pkg (mapconcat (lambda(p)
  17040. (cond
  17041. ((stringp p) p)
  17042. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17043. (format "%% Package %s omitted" (cadr p)))
  17044. ((equal "" (car p))
  17045. (format "\\usepackage{%s}" (cadr p)))
  17046. (t
  17047. (format "\\usepackage[%s]{%s}"
  17048. (car p) (cadr p)))))
  17049. pkg
  17050. "\n"))
  17051. (if newline (concat pkg "\n") pkg))
  17052. (defun org-dvipng-color (attr)
  17053. "Return a RGB color specification for dvipng."
  17054. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17055. (defun org-dvipng-color-format (color-name)
  17056. "Convert COLOR-NAME to a RGB color value for dvipng."
  17057. (apply #'format "rgb %s %s %s"
  17058. (mapcar 'org-normalize-color
  17059. (color-values color-name))))
  17060. (defun org-latex-color (attr)
  17061. "Return a RGB color for the LaTeX color package."
  17062. (org-latex-color-format (face-attribute 'default attr nil)))
  17063. (defun org-latex-color-format (color-name)
  17064. "Convert COLOR-NAME to a RGB color value."
  17065. (apply #'format "%s,%s,%s"
  17066. (mapcar 'org-normalize-color
  17067. (color-values color-name))))
  17068. (defun org-normalize-color (value)
  17069. "Return string to be used as color value for an RGB component."
  17070. (format "%g" (/ value 65535.0)))
  17071. ;; Image display
  17072. (defvar-local org-inline-image-overlays nil)
  17073. (defun org-toggle-inline-images (&optional include-linked)
  17074. "Toggle the display of inline images.
  17075. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17076. (interactive "P")
  17077. (if org-inline-image-overlays
  17078. (progn
  17079. (org-remove-inline-images)
  17080. (when (called-interactively-p 'interactive)
  17081. (message "Inline image display turned off")))
  17082. (org-display-inline-images include-linked)
  17083. (when (called-interactively-p 'interactive)
  17084. (message (if org-inline-image-overlays
  17085. (format "%d images displayed inline"
  17086. (length org-inline-image-overlays))
  17087. "No images to display inline")))))
  17088. (defun org-redisplay-inline-images ()
  17089. "Refresh the display of inline images."
  17090. (interactive)
  17091. (if (not org-inline-image-overlays)
  17092. (org-toggle-inline-images)
  17093. (org-toggle-inline-images)
  17094. (org-toggle-inline-images)))
  17095. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17096. "Display inline images.
  17097. An inline image is a link which follows either of these
  17098. conventions:
  17099. 1. Its path is a file with an extension matching return value
  17100. from `image-file-name-regexp' and it has no contents.
  17101. 2. Its description consists in a single link of the previous
  17102. type.
  17103. When optional argument INCLUDE-LINKED is non-nil, also links with
  17104. a text description part will be inlined. This can be nice for
  17105. a quick look at those images, but it does not reflect what
  17106. exported files will look like.
  17107. When optional argument REFRESH is non-nil, refresh existing
  17108. images between BEG and END. This will create new image displays
  17109. only if necessary. BEG and END default to the buffer
  17110. boundaries."
  17111. (interactive "P")
  17112. (when (display-graphic-p)
  17113. (unless refresh
  17114. (org-remove-inline-images)
  17115. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17116. (org-with-wide-buffer
  17117. (goto-char (or beg (point-min)))
  17118. (let* ((case-fold-search t)
  17119. (file-extension-re (image-file-name-regexp))
  17120. (link-abbrevs (mapcar #'car
  17121. (append org-link-abbrev-alist-local
  17122. org-link-abbrev-alist)))
  17123. ;; Check absolute, relative file names and explicit
  17124. ;; "file:" links. Also check link abbreviations since
  17125. ;; some might expand to "file" links.
  17126. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  17127. (if (not link-abbrevs) ""
  17128. (format "\\|\\(?:%s:\\)"
  17129. (regexp-opt link-abbrevs))))))
  17130. (while (re-search-forward file-types-re end t)
  17131. (let ((link (save-match-data (org-element-context))))
  17132. ;; Check if we're at an inline image, i.e., an image file
  17133. ;; link without a description (unless INCLUDE-LINKED is
  17134. ;; non-nil).
  17135. (when (and (equal "file" (org-element-property :type link))
  17136. (or include-linked
  17137. (null (org-element-contents link)))
  17138. (string-match-p file-extension-re
  17139. (org-element-property :path link)))
  17140. (let ((file (expand-file-name
  17141. (org-link-unescape
  17142. (org-element-property :path link)))))
  17143. (when (file-exists-p file)
  17144. (let ((width
  17145. ;; Apply `org-image-actual-width' specifications.
  17146. (cond
  17147. ((not (image-type-available-p 'imagemagick)) nil)
  17148. ((eq org-image-actual-width t) nil)
  17149. ((listp org-image-actual-width)
  17150. (or
  17151. ;; First try to find a width among
  17152. ;; attributes associated to the paragraph
  17153. ;; containing link.
  17154. (let ((paragraph
  17155. (let ((e link))
  17156. (while (and (setq e (org-element-property
  17157. :parent e))
  17158. (not (eq (org-element-type e)
  17159. 'paragraph))))
  17160. e)))
  17161. (when paragraph
  17162. (save-excursion
  17163. (goto-char (org-element-property :begin paragraph))
  17164. (when
  17165. (re-search-forward
  17166. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17167. (org-element-property
  17168. :post-affiliated paragraph)
  17169. t)
  17170. (string-to-number (match-string 1))))))
  17171. ;; Otherwise, fall-back to provided number.
  17172. (car org-image-actual-width)))
  17173. ((numberp org-image-actual-width)
  17174. org-image-actual-width)))
  17175. (old (get-char-property-and-overlay
  17176. (org-element-property :begin link)
  17177. 'org-image-overlay)))
  17178. (if (and (car-safe old) refresh)
  17179. (image-refresh (overlay-get (cdr old) 'display))
  17180. (let ((image (create-image file
  17181. (and width 'imagemagick)
  17182. nil
  17183. :width width)))
  17184. (when image
  17185. (let ((ov (make-overlay
  17186. (org-element-property :begin link)
  17187. (progn
  17188. (goto-char
  17189. (org-element-property :end link))
  17190. (skip-chars-backward " \t")
  17191. (point)))))
  17192. (overlay-put ov 'display image)
  17193. (overlay-put ov 'face 'default)
  17194. (overlay-put ov 'org-image-overlay t)
  17195. (overlay-put
  17196. ov 'modification-hooks
  17197. (list 'org-display-inline-remove-overlay))
  17198. (push ov org-inline-image-overlays)))))))))))))))
  17199. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17200. "Remove inline-display overlay if a corresponding region is modified."
  17201. (let ((inhibit-modification-hooks t))
  17202. (when (and ov after)
  17203. (delete ov org-inline-image-overlays)
  17204. (delete-overlay ov))))
  17205. (defun org-remove-inline-images ()
  17206. "Remove inline display of images."
  17207. (interactive)
  17208. (mapc #'delete-overlay org-inline-image-overlays)
  17209. (setq org-inline-image-overlays nil))
  17210. ;;; Key bindings
  17211. (defun org-remap (map &rest commands)
  17212. "In MAP, remap the functions given in COMMANDS.
  17213. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  17214. (let (new old)
  17215. (while commands
  17216. (setq old (pop commands) new (pop commands))
  17217. (org-defkey map (vector 'remap old) new))))
  17218. ;;;; Outline functions that can be remapped in Org
  17219. (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
  17220. (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
  17221. (define-key org-mode-map [remap outline-forward-same-level]
  17222. #'org-forward-heading-same-level)
  17223. (define-key org-mode-map [remap outline-backward-same-level]
  17224. #'org-backward-heading-same-level)
  17225. (define-key org-mode-map [remap outline-show-branches]
  17226. #'org-kill-note-or-show-branches)
  17227. (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
  17228. (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
  17229. (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
  17230. (define-key org-mode-map [remap outline-next-visible-heading]
  17231. #'org-next-visible-heading)
  17232. (define-key org-mode-map [remap outline-previous-visible-heading]
  17233. #'org-previous-visible-heading)
  17234. (define-key org-mode-map [remap show-children] #'org-show-children)
  17235. ;;;; Make `C-c C-x' a prefix key
  17236. (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
  17237. ;;;; TAB key with modifiers
  17238. (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
  17239. (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
  17240. (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
  17241. (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
  17242. (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
  17243. (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
  17244. (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
  17245. (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
  17246. ;;;; RET key with modifiers
  17247. (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
  17248. (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
  17249. (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
  17250. (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
  17251. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17252. ;;;; Cursor keys with modifiers
  17253. (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
  17254. (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
  17255. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17256. (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
  17257. (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
  17258. (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
  17259. (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
  17260. (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
  17261. (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
  17262. (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
  17263. (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
  17264. (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
  17265. (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
  17266. (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
  17267. (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
  17268. (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
  17269. (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
  17270. (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
  17271. (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
  17272. (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
  17273. (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
  17274. (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
  17275. (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
  17276. (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
  17277. (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
  17278. ;;;; Babel keys
  17279. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17280. (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
  17281. (define-key org-babel-map key def))
  17282. ;;;; Extra keys for TTY access.
  17283. ;; We only set them when really needed because otherwise the
  17284. ;; menus don't show the simple keys
  17285. (when (or org-use-extra-keys (not window-system))
  17286. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
  17287. (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
  17288. (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
  17289. (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
  17290. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17291. (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
  17292. (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
  17293. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17294. (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
  17295. (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
  17296. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
  17297. (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
  17298. (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
  17299. (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
  17300. (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
  17301. (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
  17302. (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
  17303. (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
  17304. (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
  17305. (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
  17306. (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
  17307. ;;;; Narrow map
  17308. (org-defkey narrow-map "s" #'org-narrow-to-subtree)
  17309. (org-defkey narrow-map "b" #'org-narrow-to-block)
  17310. (org-defkey narrow-map "e" #'org-narrow-to-element)
  17311. ;;;; Remap usual Emacs bindings
  17312. (org-remap org-mode-map
  17313. 'self-insert-command 'org-self-insert-command
  17314. 'delete-char 'org-delete-char
  17315. 'delete-backward-char 'org-delete-backward-char
  17316. 'kill-line 'org-kill-line
  17317. 'open-line 'org-open-line
  17318. 'yank 'org-yank
  17319. 'comment-dwim 'org-comment-dwim
  17320. 'move-beginning-of-line 'org-beginning-of-line
  17321. 'move-end-of-line 'org-end-of-line
  17322. 'forward-paragraph 'org-forward-paragraph
  17323. 'backward-paragraph 'org-backward-paragraph
  17324. 'backward-sentence 'org-backward-sentence
  17325. 'forward-sentence 'org-forward-sentence
  17326. 'fill-paragraph 'org-fill-paragraph
  17327. 'delete-indentation 'org-delete-indentation
  17328. 'transpose-words 'org-transpose-words)
  17329. ;;;; All the other keys
  17330. (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
  17331. (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
  17332. (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
  17333. (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
  17334. (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
  17335. (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
  17336. (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
  17337. (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
  17338. (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
  17339. (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
  17340. (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
  17341. (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
  17342. (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
  17343. (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
  17344. (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
  17345. (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
  17346. (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
  17347. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
  17348. (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
  17349. (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
  17350. (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
  17351. (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
  17352. (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
  17353. (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
  17354. (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
  17355. (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
  17356. (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
  17357. (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
  17358. (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
  17359. (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
  17360. (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
  17361. (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
  17362. (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
  17363. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
  17364. (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
  17365. (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
  17366. (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
  17367. (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
  17368. (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
  17369. (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
  17370. (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
  17371. (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
  17372. (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
  17373. (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
  17374. (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
  17375. (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
  17376. (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
  17377. (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
  17378. (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
  17379. (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
  17380. (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
  17381. (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
  17382. (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
  17383. (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
  17384. (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
  17385. (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
  17386. (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
  17387. (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
  17388. (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
  17389. (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
  17390. (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
  17391. (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
  17392. (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
  17393. (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
  17394. (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
  17395. (org-defkey org-mode-map (kbd "RET") #'org-return)
  17396. (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
  17397. (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
  17398. (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
  17399. (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
  17400. (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
  17401. (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
  17402. (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
  17403. (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
  17404. (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
  17405. (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
  17406. (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
  17407. (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
  17408. (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
  17409. (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
  17410. (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
  17411. (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
  17412. (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
  17413. (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
  17414. (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
  17415. (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
  17416. (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
  17417. (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
  17418. (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
  17419. (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
  17420. (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
  17421. (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
  17422. (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
  17423. (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
  17424. (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
  17425. (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
  17426. (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
  17427. (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
  17428. (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
  17429. (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
  17430. (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
  17431. (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
  17432. (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
  17433. (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
  17434. (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
  17435. (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
  17436. (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
  17437. (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
  17438. (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
  17439. (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
  17440. (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
  17441. (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
  17442. (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
  17443. (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
  17444. (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
  17445. (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
  17446. (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
  17447. (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
  17448. (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
  17449. (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
  17450. (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
  17451. (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
  17452. (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
  17453. (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
  17454. (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
  17455. ;;; Speed commands
  17456. (defconst org-speed-commands-default
  17457. '(
  17458. ("Outline Navigation")
  17459. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17460. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17461. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17462. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17463. ("F" . org-next-block)
  17464. ("B" . org-previous-block)
  17465. ("u" . (org-speed-move-safe 'outline-up-heading))
  17466. ("j" . org-goto)
  17467. ("g" . (org-refile t))
  17468. ("Outline Visibility")
  17469. ("c" . org-cycle)
  17470. ("C" . org-shifttab)
  17471. (" " . org-display-outline-path)
  17472. ("s" . org-toggle-narrow-to-subtree)
  17473. ("k" . org-cut-subtree)
  17474. ("=" . org-columns)
  17475. ("Outline Structure Editing")
  17476. ("U" . org-metaup)
  17477. ("D" . org-metadown)
  17478. ("r" . org-metaright)
  17479. ("l" . org-metaleft)
  17480. ("R" . org-shiftmetaright)
  17481. ("L" . org-shiftmetaleft)
  17482. ("i" . (progn (forward-char 1) (call-interactively
  17483. 'org-insert-heading-respect-content)))
  17484. ("^" . org-sort)
  17485. ("w" . org-refile)
  17486. ("a" . org-archive-subtree-default-with-confirmation)
  17487. ("@" . org-mark-subtree)
  17488. ("#" . org-toggle-comment)
  17489. ("Clock Commands")
  17490. ("I" . org-clock-in)
  17491. ("O" . org-clock-out)
  17492. ("Meta Data Editing")
  17493. ("t" . org-todo)
  17494. ("," . (org-priority))
  17495. ("0" . (org-priority ?\ ))
  17496. ("1" . (org-priority ?A))
  17497. ("2" . (org-priority ?B))
  17498. ("3" . (org-priority ?C))
  17499. (":" . org-set-tags-command)
  17500. ("e" . org-set-effort)
  17501. ("E" . org-inc-effort)
  17502. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  17503. (org-entry-put (point) "APPT_WARNTIME" m)))
  17504. ("Agenda Views etc")
  17505. ("v" . org-agenda)
  17506. ("/" . org-sparse-tree)
  17507. ("Misc")
  17508. ("o" . org-open-at-point)
  17509. ("?" . org-speed-command-help)
  17510. ("<" . (org-agenda-set-restriction-lock 'subtree))
  17511. (">" . (org-agenda-remove-restriction-lock))
  17512. )
  17513. "The default speed commands.")
  17514. (defun org-print-speed-command (e)
  17515. (if (> (length (car e)) 1)
  17516. (progn
  17517. (princ "\n")
  17518. (princ (car e))
  17519. (princ "\n")
  17520. (princ (make-string (length (car e)) ?-))
  17521. (princ "\n"))
  17522. (princ (car e))
  17523. (princ " ")
  17524. (if (symbolp (cdr e))
  17525. (princ (symbol-name (cdr e)))
  17526. (prin1 (cdr e)))
  17527. (princ "\n")))
  17528. (defun org-speed-command-help ()
  17529. "Show the available speed commands."
  17530. (interactive)
  17531. (if (not org-use-speed-commands)
  17532. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  17533. (with-output-to-temp-buffer "*Help*"
  17534. (princ "User-defined Speed commands\n===========================\n")
  17535. (mapc #'org-print-speed-command org-speed-commands-user)
  17536. (princ "\n")
  17537. (princ "Built-in Speed commands\n=======================\n")
  17538. (mapc #'org-print-speed-command org-speed-commands-default))
  17539. (with-current-buffer "*Help*"
  17540. (setq truncate-lines t))))
  17541. (defun org-speed-move-safe (cmd)
  17542. "Execute CMD, but make sure that the cursor always ends up in a headline.
  17543. If not, return to the original position and throw an error."
  17544. (interactive)
  17545. (let ((pos (point)))
  17546. (call-interactively cmd)
  17547. (unless (and (bolp) (org-at-heading-p))
  17548. (goto-char pos)
  17549. (error "Boundary reached while executing %s" cmd))))
  17550. (defvar org-self-insert-command-undo-counter 0)
  17551. (defvar org-table-auto-blank-field) ; defined in org-table.el
  17552. (defvar org-speed-command nil)
  17553. (defun org-speed-command-activate (keys)
  17554. "Hook for activating single-letter speed commands.
  17555. `org-speed-commands-default' specifies a minimal command set.
  17556. Use `org-speed-commands-user' for further customization."
  17557. (when (or (and (bolp) (looking-at org-outline-regexp))
  17558. (and (functionp org-use-speed-commands)
  17559. (funcall org-use-speed-commands)))
  17560. (cdr (assoc keys (append org-speed-commands-user
  17561. org-speed-commands-default)))))
  17562. (defun org-babel-speed-command-activate (keys)
  17563. "Hook for activating single-letter code block commands."
  17564. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  17565. (cdr (assoc keys org-babel-key-bindings))))
  17566. (defcustom org-speed-command-hook
  17567. '(org-speed-command-activate org-babel-speed-command-activate)
  17568. "Hook for activating speed commands at strategic locations.
  17569. Hook functions are called in sequence until a valid handler is
  17570. found.
  17571. Each hook takes a single argument, a user-pressed command key
  17572. which is also a `self-insert-command' from the global map.
  17573. Within the hook, examine the cursor position and the command key
  17574. and return nil or a valid handler as appropriate. Handler could
  17575. be one of an interactive command, a function, or a form.
  17576. Set `org-use-speed-commands' to non-nil value to enable this
  17577. hook. The default setting is `org-speed-command-activate'."
  17578. :group 'org-structure
  17579. :version "24.1"
  17580. :type 'hook)
  17581. (defun org-self-insert-command (N)
  17582. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  17583. If the cursor is in a table looking at whitespace, the whitespace is
  17584. overwritten, and the table is not marked as requiring realignment."
  17585. (interactive "p")
  17586. (org-check-before-invisible-edit 'insert)
  17587. (cond
  17588. ((and org-use-speed-commands
  17589. (let ((kv (this-command-keys-vector)))
  17590. (setq org-speed-command
  17591. (run-hook-with-args-until-success
  17592. 'org-speed-command-hook
  17593. (make-string 1 (aref kv (1- (length kv))))))))
  17594. (cond
  17595. ((commandp org-speed-command)
  17596. (setq this-command org-speed-command)
  17597. (call-interactively org-speed-command))
  17598. ((functionp org-speed-command)
  17599. (funcall org-speed-command))
  17600. ((and org-speed-command (listp org-speed-command))
  17601. (eval org-speed-command))
  17602. (t (let (org-use-speed-commands)
  17603. (call-interactively 'org-self-insert-command)))))
  17604. ((and
  17605. (= N 1)
  17606. (not (org-region-active-p))
  17607. (org-at-table-p)
  17608. (progn
  17609. ;; Check if we blank the field, and if that triggers align.
  17610. (and (featurep 'org-table)
  17611. org-table-auto-blank-field
  17612. (memq last-command
  17613. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  17614. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  17615. ;; Got extra space, this field does not determine
  17616. ;; column width.
  17617. (let (org-table-may-need-update) (org-table-blank-field))
  17618. ;; No extra space, this field may determine column
  17619. ;; width.
  17620. (org-table-blank-field)))
  17621. t)
  17622. (looking-at "[^|\n]* |"))
  17623. ;; There is room for insertion without re-aligning the table.
  17624. (self-insert-command N)
  17625. (org-table-with-shrunk-field
  17626. (save-excursion
  17627. (skip-chars-forward "^|")
  17628. ;; Do not delete last space, which is
  17629. ;; `org-table-separator-space', but the regular space before
  17630. ;; it.
  17631. (delete-region (- (point) 2) (1- (point))))))
  17632. (t
  17633. (setq org-table-may-need-update t)
  17634. (self-insert-command N)
  17635. (org-fix-tags-on-the-fly)
  17636. (when org-self-insert-cluster-for-undo
  17637. (if (not (eq last-command 'org-self-insert-command))
  17638. (setq org-self-insert-command-undo-counter 1)
  17639. (if (>= org-self-insert-command-undo-counter 20)
  17640. (setq org-self-insert-command-undo-counter 1)
  17641. (and (> org-self-insert-command-undo-counter 0)
  17642. buffer-undo-list (listp buffer-undo-list)
  17643. (not (cadr buffer-undo-list)) ; remove nil entry
  17644. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  17645. (setq org-self-insert-command-undo-counter
  17646. (1+ org-self-insert-command-undo-counter))))))))
  17647. (defun org-check-before-invisible-edit (kind)
  17648. "Check is editing if kind KIND would be dangerous with invisible text around.
  17649. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  17650. ;; First, try to get out of here as quickly as possible, to reduce overhead
  17651. (when (and org-catch-invisible-edits
  17652. (or (not (boundp 'visible-mode)) (not visible-mode))
  17653. (or (get-char-property (point) 'invisible)
  17654. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  17655. ;; OK, we need to take a closer look. Do not consider
  17656. ;; invisibility obtained through text properties (e.g., link
  17657. ;; fontification), as it cannot be toggled.
  17658. (let* ((invisible-at-point
  17659. (pcase (get-char-property-and-overlay (point) 'invisible)
  17660. (`(,_ . ,(and (pred overlayp) o)) o)))
  17661. ;; Assume that point cannot land in the middle of an
  17662. ;; overlay, or between two overlays.
  17663. (invisible-before-point
  17664. (and (not invisible-at-point)
  17665. (not (bobp))
  17666. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  17667. (`(,_ . ,(and (pred overlayp) o)) o))))
  17668. (border-and-ok-direction
  17669. (or
  17670. ;; Check if we are acting predictably before invisible
  17671. ;; text.
  17672. (and invisible-at-point
  17673. (memq kind '(insert delete-backward)))
  17674. ;; Check if we are acting predictably after invisible text
  17675. ;; This works not well, and I have turned it off. It seems
  17676. ;; better to always show and stop after invisible text.
  17677. ;; (and (not invisible-at-point) invisible-before-point
  17678. ;; (memq kind '(insert delete)))
  17679. )))
  17680. (when (or invisible-at-point invisible-before-point)
  17681. (when (eq org-catch-invisible-edits 'error)
  17682. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  17683. (if (and org-custom-properties-overlays
  17684. (y-or-n-p "Display invisible properties in this buffer? "))
  17685. (org-toggle-custom-properties-visibility)
  17686. ;; Make the area visible
  17687. (save-excursion
  17688. (when invisible-before-point
  17689. (goto-char
  17690. (previous-single-char-property-change (point) 'invisible)))
  17691. ;; Remove whatever overlay is currently making yet-to-be
  17692. ;; edited text invisible. Also remove nested invisibility
  17693. ;; related overlays.
  17694. (delete-overlay (or invisible-at-point invisible-before-point))
  17695. (let ((origin (if invisible-at-point (point) (1- (point)))))
  17696. (while (pcase (get-char-property-and-overlay origin 'invisible)
  17697. (`(,_ . ,(and (pred overlayp) o))
  17698. (delete-overlay o)
  17699. t)))))
  17700. (cond
  17701. ((eq org-catch-invisible-edits 'show)
  17702. ;; That's it, we do the edit after showing
  17703. (message
  17704. "Unfolding invisible region around point before editing")
  17705. (sit-for 1))
  17706. ((and (eq org-catch-invisible-edits 'smart)
  17707. border-and-ok-direction)
  17708. (message "Unfolding invisible region around point before editing"))
  17709. (t
  17710. ;; Don't do the edit, make the user repeat it in full visibility
  17711. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  17712. (defun org-fix-tags-on-the-fly ()
  17713. "Align tags in headline at point.
  17714. Unlike `org-align-tags', this function does nothing if point is
  17715. either not currently on a tagged headline or on a tag."
  17716. (when (and (org-match-line org-tag-line-re)
  17717. (< (point) (match-beginning 1)))
  17718. (org-align-tags)))
  17719. (defun org-delete-backward-char (N)
  17720. "Like `delete-backward-char', insert whitespace at field end in tables.
  17721. When deleting backwards, in tables this function will insert whitespace in
  17722. front of the next \"|\" separator, to keep the table aligned. The table will
  17723. still be marked for re-alignment if the field did fill the entire column,
  17724. because, in this case the deletion might narrow the column."
  17725. (interactive "p")
  17726. (save-match-data
  17727. (org-check-before-invisible-edit 'delete-backward)
  17728. (if (and (= N 1)
  17729. (not overwrite-mode)
  17730. (not (org-region-active-p))
  17731. (not (eq (char-before) ?|))
  17732. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  17733. (looking-at-p ".*?|")
  17734. (org-at-table-p))
  17735. (progn (forward-char -1) (org-delete-char 1))
  17736. (backward-delete-char N)
  17737. (org-fix-tags-on-the-fly))))
  17738. (defun org-delete-char (N)
  17739. "Like `delete-char', but insert whitespace at field end in tables.
  17740. When deleting characters, in tables this function will insert whitespace in
  17741. front of the next \"|\" separator, to keep the table aligned. The table will
  17742. still be marked for re-alignment if the field did fill the entire column,
  17743. because, in this case the deletion might narrow the column."
  17744. (interactive "p")
  17745. (save-match-data
  17746. (org-check-before-invisible-edit 'delete)
  17747. (cond
  17748. ((or (/= N 1)
  17749. (eq (char-after) ?|)
  17750. (save-excursion (skip-chars-backward " \t") (bolp))
  17751. (not (org-at-table-p)))
  17752. (delete-char N)
  17753. (org-fix-tags-on-the-fly))
  17754. ((looking-at ".\\(.*?\\)|")
  17755. (let* ((update? org-table-may-need-update)
  17756. (noalign (looking-at-p ".*? |")))
  17757. (delete-char 1)
  17758. (org-table-with-shrunk-field
  17759. (save-excursion
  17760. ;; Last space is `org-table-separator-space', so insert
  17761. ;; a regular one before it instead.
  17762. (goto-char (- (match-end 0) 2))
  17763. (insert " ")))
  17764. ;; If there were two spaces at the end, this field does not
  17765. ;; determine the width of the column.
  17766. (when noalign (setq org-table-may-need-update update?))))
  17767. (t
  17768. (delete-char N)))))
  17769. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  17770. (put 'org-self-insert-command 'delete-selection
  17771. (lambda ()
  17772. (not (run-hook-with-args-until-success
  17773. 'self-insert-uses-region-functions))))
  17774. (put 'orgtbl-self-insert-command 'delete-selection
  17775. (lambda ()
  17776. (not (run-hook-with-args-until-success
  17777. 'self-insert-uses-region-functions))))
  17778. (put 'org-delete-char 'delete-selection 'supersede)
  17779. (put 'org-delete-backward-char 'delete-selection 'supersede)
  17780. (put 'org-yank 'delete-selection 'yank)
  17781. ;; Make `flyspell-mode' delay after some commands
  17782. (put 'org-self-insert-command 'flyspell-delayed t)
  17783. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  17784. (put 'org-delete-char 'flyspell-delayed t)
  17785. (put 'org-delete-backward-char 'flyspell-delayed t)
  17786. ;; Make pabbrev-mode expand after Org mode commands
  17787. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  17788. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  17789. (defun org-transpose-words ()
  17790. "Transpose words for Org.
  17791. This uses the `org-mode-transpose-word-syntax-table' syntax
  17792. table, which interprets characters in `org-emphasis-alist' as
  17793. word constituents."
  17794. (interactive)
  17795. (with-syntax-table org-mode-transpose-word-syntax-table
  17796. (call-interactively 'transpose-words)))
  17797. (defvar org-ctrl-c-ctrl-c-hook nil
  17798. "Hook for functions attaching themselves to `C-c C-c'.
  17799. This can be used to add additional functionality to the C-c C-c
  17800. key which executes context-dependent commands. This hook is run
  17801. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  17802. run after the last test.
  17803. Each function will be called with no arguments. The function
  17804. must check if the context is appropriate for it to act. If yes,
  17805. it should do its thing and then return a non-nil value. If the
  17806. context is wrong, just do nothing and return nil.")
  17807. (defvar org-ctrl-c-ctrl-c-final-hook nil
  17808. "Hook for functions attaching themselves to `C-c C-c'.
  17809. This can be used to add additional functionality to the C-c C-c
  17810. key which executes context-dependent commands. This hook is run
  17811. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  17812. before the first test.
  17813. Each function will be called with no arguments. The function
  17814. must check if the context is appropriate for it to act. If yes,
  17815. it should do its thing and then return a non-nil value. If the
  17816. context is wrong, just do nothing and return nil.")
  17817. (defvar org-tab-first-hook nil
  17818. "Hook for functions to attach themselves to TAB.
  17819. See `org-ctrl-c-ctrl-c-hook' for more information.
  17820. This hook runs as the first action when TAB is pressed, even before
  17821. `org-cycle' messes around with the `outline-regexp' to cater for
  17822. inline tasks and plain list item folding.
  17823. If any function in this hook returns t, any other actions that
  17824. would have been caused by TAB (such as table field motion or visibility
  17825. cycling) will not occur.")
  17826. (defvar org-tab-after-check-for-table-hook nil
  17827. "Hook for functions to attach themselves to TAB.
  17828. See `org-ctrl-c-ctrl-c-hook' for more information.
  17829. This hook runs after it has been established that the cursor is not in a
  17830. table, but before checking if the cursor is in a headline or if global cycling
  17831. should be done.
  17832. If any function in this hook returns t, not other actions like visibility
  17833. cycling will be done.")
  17834. (defvar org-tab-after-check-for-cycling-hook nil
  17835. "Hook for functions to attach themselves to TAB.
  17836. See `org-ctrl-c-ctrl-c-hook' for more information.
  17837. This hook runs after it has been established that not table field motion and
  17838. not visibility should be done because of current context. This is probably
  17839. the place where a package like yasnippets can hook in.")
  17840. (defvar org-tab-before-tab-emulation-hook nil
  17841. "Hook for functions to attach themselves to TAB.
  17842. See `org-ctrl-c-ctrl-c-hook' for more information.
  17843. This hook runs after every other options for TAB have been exhausted, but
  17844. before indentation and \t insertion takes place.")
  17845. (defvar org-metaleft-hook nil
  17846. "Hook for functions attaching themselves to `M-left'.
  17847. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17848. (defvar org-metaright-hook nil
  17849. "Hook for functions attaching themselves to `M-right'.
  17850. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17851. (defvar org-metaup-hook nil
  17852. "Hook for functions attaching themselves to `M-up'.
  17853. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17854. (defvar org-metadown-hook nil
  17855. "Hook for functions attaching themselves to `M-down'.
  17856. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17857. (defvar org-shiftmetaleft-hook nil
  17858. "Hook for functions attaching themselves to `M-S-left'.
  17859. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17860. (defvar org-shiftmetaright-hook nil
  17861. "Hook for functions attaching themselves to `M-S-right'.
  17862. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17863. (defvar org-shiftmetaup-hook nil
  17864. "Hook for functions attaching themselves to `M-S-up'.
  17865. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17866. (defvar org-shiftmetadown-hook nil
  17867. "Hook for functions attaching themselves to `M-S-down'.
  17868. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17869. (defvar org-metareturn-hook nil
  17870. "Hook for functions attaching themselves to `M-RET'.
  17871. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17872. (defvar org-shiftup-hook nil
  17873. "Hook for functions attaching themselves to `S-up'.
  17874. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17875. (defvar org-shiftup-final-hook nil
  17876. "Hook for functions attaching themselves to `S-up'.
  17877. This one runs after all other options except shift-select have been excluded.
  17878. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17879. (defvar org-shiftdown-hook nil
  17880. "Hook for functions attaching themselves to `S-down'.
  17881. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17882. (defvar org-shiftdown-final-hook nil
  17883. "Hook for functions attaching themselves to `S-down'.
  17884. This one runs after all other options except shift-select have been excluded.
  17885. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17886. (defvar org-shiftleft-hook nil
  17887. "Hook for functions attaching themselves to `S-left'.
  17888. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17889. (defvar org-shiftleft-final-hook nil
  17890. "Hook for functions attaching themselves to `S-left'.
  17891. This one runs after all other options except shift-select have been excluded.
  17892. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17893. (defvar org-shiftright-hook nil
  17894. "Hook for functions attaching themselves to `S-right'.
  17895. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17896. (defvar org-shiftright-final-hook nil
  17897. "Hook for functions attaching themselves to `S-right'.
  17898. This one runs after all other options except shift-select have been excluded.
  17899. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17900. (defun org-modifier-cursor-error ()
  17901. "Throw an error, a modified cursor command was applied in wrong context."
  17902. (user-error "This command is active in special context like tables, headlines or items"))
  17903. (defun org-shiftselect-error ()
  17904. "Throw an error because Shift-Cursor command was applied in wrong context."
  17905. (if (and (boundp 'shift-select-mode) shift-select-mode)
  17906. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  17907. (user-error "This command works only in special context like headlines or timestamps")))
  17908. (defun org-call-for-shift-select (cmd)
  17909. (let ((this-command-keys-shift-translated t))
  17910. (call-interactively cmd)))
  17911. (defun org-shifttab (&optional arg)
  17912. "Global visibility cycling or move to previous table field.
  17913. Call `org-table-previous-field' within a table.
  17914. When ARG is nil, cycle globally through visibility states.
  17915. When ARG is a numeric prefix, show contents of this level."
  17916. (interactive "P")
  17917. (cond
  17918. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  17919. ((integerp arg)
  17920. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  17921. (message "Content view to level: %d" arg)
  17922. (org-content (prefix-numeric-value arg2))
  17923. (org-cycle-show-empty-lines t)
  17924. (setq org-cycle-global-status 'overview)))
  17925. (t (call-interactively 'org-global-cycle))))
  17926. (defun org-shiftmetaleft ()
  17927. "Promote subtree or delete table column.
  17928. Calls `org-promote-subtree', `org-outdent-item-tree', or
  17929. `org-table-delete-column', depending on context. See the
  17930. individual commands for more information."
  17931. (interactive)
  17932. (cond
  17933. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  17934. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  17935. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  17936. ((if (not (org-region-active-p)) (org-at-item-p)
  17937. (save-excursion (goto-char (region-beginning))
  17938. (org-at-item-p)))
  17939. (call-interactively 'org-outdent-item-tree))
  17940. (t (org-modifier-cursor-error))))
  17941. (defun org-shiftmetaright ()
  17942. "Demote subtree or insert table column.
  17943. Calls `org-demote-subtree', `org-indent-item-tree', or
  17944. `org-table-insert-column', depending on context. See the
  17945. individual commands for more information."
  17946. (interactive)
  17947. (cond
  17948. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  17949. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  17950. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  17951. ((if (not (org-region-active-p)) (org-at-item-p)
  17952. (save-excursion (goto-char (region-beginning))
  17953. (org-at-item-p)))
  17954. (call-interactively 'org-indent-item-tree))
  17955. (t (org-modifier-cursor-error))))
  17956. (defun org-shiftmetaup (&optional _arg)
  17957. "Drag the line at point up.
  17958. In a table, kill the current row.
  17959. On a clock timestamp, update the value of the timestamp like `S-<up>'
  17960. but also adjust the previous clocked item in the clock history.
  17961. Everywhere else, drag the line at point up."
  17962. (interactive "P")
  17963. (cond
  17964. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  17965. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  17966. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17967. (call-interactively 'org-timestamp-up)))
  17968. (t (call-interactively 'org-drag-line-backward))))
  17969. (defun org-shiftmetadown (&optional _arg)
  17970. "Drag the line at point down.
  17971. In a table, insert an empty row at the current line.
  17972. On a clock timestamp, update the value of the timestamp like `S-<down>'
  17973. but also adjust the previous clocked item in the clock history.
  17974. Everywhere else, drag the line at point down."
  17975. (interactive "P")
  17976. (cond
  17977. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  17978. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  17979. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17980. (call-interactively 'org-timestamp-down)))
  17981. (t (call-interactively 'org-drag-line-forward))))
  17982. (defsubst org-hidden-tree-error ()
  17983. (user-error
  17984. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  17985. (defun org-metaleft (&optional _arg)
  17986. "Promote heading, list item at point or move table column left.
  17987. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  17988. depending on context. With no specific context, calls the Emacs
  17989. default `backward-word'. See the individual commands for more
  17990. information.
  17991. This function runs the hook `org-metaleft-hook' as a first step,
  17992. and returns at first non-nil value."
  17993. (interactive "P")
  17994. (cond
  17995. ((run-hook-with-args-until-success 'org-metaleft-hook))
  17996. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  17997. ((org-with-limited-levels
  17998. (or (org-at-heading-p)
  17999. (and (org-region-active-p)
  18000. (save-excursion
  18001. (goto-char (region-beginning))
  18002. (org-at-heading-p)))))
  18003. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18004. (call-interactively 'org-do-promote))
  18005. ;; At an inline task.
  18006. ((org-at-heading-p)
  18007. (call-interactively 'org-inlinetask-promote))
  18008. ((or (org-at-item-p)
  18009. (and (org-region-active-p)
  18010. (save-excursion
  18011. (goto-char (region-beginning))
  18012. (org-at-item-p))))
  18013. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18014. (call-interactively 'org-outdent-item))
  18015. (t (call-interactively 'backward-word))))
  18016. (defun org-metaright (&optional _arg)
  18017. "Demote heading, list item at point or move table column right.
  18018. In front of a drawer or a block keyword, indent it correctly.
  18019. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18020. `org-indent-drawer' or `org-indent-block' depending on context.
  18021. With no specific context, calls the Emacs default `forward-word'.
  18022. See the individual commands for more information.
  18023. This function runs the hook `org-metaright-hook' as a first step,
  18024. and returns at first non-nil value."
  18025. (interactive "P")
  18026. (cond
  18027. ((run-hook-with-args-until-success 'org-metaright-hook))
  18028. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18029. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18030. ((org-at-block-p) (call-interactively 'org-indent-block))
  18031. ((org-with-limited-levels
  18032. (or (org-at-heading-p)
  18033. (and (org-region-active-p)
  18034. (save-excursion
  18035. (goto-char (region-beginning))
  18036. (org-at-heading-p)))))
  18037. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18038. (call-interactively 'org-do-demote))
  18039. ;; At an inline task.
  18040. ((org-at-heading-p)
  18041. (call-interactively 'org-inlinetask-demote))
  18042. ((or (org-at-item-p)
  18043. (and (org-region-active-p)
  18044. (save-excursion
  18045. (goto-char (region-beginning))
  18046. (org-at-item-p))))
  18047. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18048. (call-interactively 'org-indent-item))
  18049. (t (call-interactively 'forward-word))))
  18050. (defun org-check-for-hidden (what)
  18051. "Check if there are hidden headlines/items in the current visual line.
  18052. WHAT can be either `headlines' or `items'. If the current line is
  18053. an outline or item heading and it has a folded subtree below it,
  18054. this function returns t, nil otherwise."
  18055. (let ((re (cond
  18056. ((eq what 'headlines) org-outline-regexp-bol)
  18057. ((eq what 'items) (org-item-beginning-re))
  18058. (t (error "This should not happen"))))
  18059. beg end)
  18060. (save-excursion
  18061. (catch 'exit
  18062. (unless (org-region-active-p)
  18063. (setq beg (point-at-bol))
  18064. (beginning-of-line 2)
  18065. (while (and (not (eobp)) ;; this is like `next-line'
  18066. (get-char-property (1- (point)) 'invisible))
  18067. (beginning-of-line 2))
  18068. (setq end (point))
  18069. (goto-char beg)
  18070. (goto-char (point-at-eol))
  18071. (setq end (max end (point)))
  18072. (while (re-search-forward re end t)
  18073. (when (get-char-property (match-beginning 0) 'invisible)
  18074. (throw 'exit t))))
  18075. nil))))
  18076. (defun org-metaup (&optional _arg)
  18077. "Move subtree up or move table row up.
  18078. Calls `org-move-subtree-up' or `org-table-move-row' or
  18079. `org-move-item-up', depending on context. See the individual commands
  18080. for more information."
  18081. (interactive "P")
  18082. (cond
  18083. ((run-hook-with-args-until-success 'org-metaup-hook))
  18084. ((org-region-active-p)
  18085. (let* ((a (min (region-beginning) (region-end)))
  18086. (b (1- (max (region-beginning) (region-end))))
  18087. (c (save-excursion (goto-char a)
  18088. (move-beginning-of-line 0)))
  18089. (d (save-excursion (goto-char a)
  18090. (move-end-of-line 0) (point))))
  18091. (transpose-regions a b c d)
  18092. (goto-char c)))
  18093. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18094. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18095. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18096. (t (org-drag-element-backward))))
  18097. (defun org-metadown (&optional _arg)
  18098. "Move subtree down or move table row down.
  18099. Calls `org-move-subtree-down' or `org-table-move-row' or
  18100. `org-move-item-down', depending on context. See the individual
  18101. commands for more information."
  18102. (interactive "P")
  18103. (cond
  18104. ((run-hook-with-args-until-success 'org-metadown-hook))
  18105. ((org-region-active-p)
  18106. (let* ((a (min (region-beginning) (region-end)))
  18107. (b (max (region-beginning) (region-end)))
  18108. (c (save-excursion (goto-char b)
  18109. (move-beginning-of-line 1)))
  18110. (d (save-excursion (goto-char b)
  18111. (move-end-of-line 1) (1+ (point)))))
  18112. (transpose-regions a b c d)
  18113. (goto-char d)))
  18114. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18115. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18116. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18117. (t (org-drag-element-forward))))
  18118. (defun org-shiftup (&optional arg)
  18119. "Increase item in timestamp or increase priority of current headline.
  18120. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18121. depending on context. See the individual commands for more information."
  18122. (interactive "P")
  18123. (cond
  18124. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18125. ((and org-support-shift-select (org-region-active-p))
  18126. (org-call-for-shift-select 'previous-line))
  18127. ((org-at-timestamp-p 'lax)
  18128. (call-interactively (if org-edit-timestamp-down-means-later
  18129. 'org-timestamp-down 'org-timestamp-up)))
  18130. ((and (not (eq org-support-shift-select 'always))
  18131. org-enable-priority-commands
  18132. (org-at-heading-p))
  18133. (call-interactively 'org-priority-up))
  18134. ((and (not org-support-shift-select) (org-at-item-p))
  18135. (call-interactively 'org-previous-item))
  18136. ((org-clocktable-try-shift 'up arg))
  18137. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18138. (org-support-shift-select
  18139. (org-call-for-shift-select 'previous-line))
  18140. (t (org-shiftselect-error))))
  18141. (defun org-shiftdown (&optional arg)
  18142. "Decrease item in timestamp or decrease priority of current headline.
  18143. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18144. depending on context. See the individual commands for more information."
  18145. (interactive "P")
  18146. (cond
  18147. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18148. ((and org-support-shift-select (org-region-active-p))
  18149. (org-call-for-shift-select 'next-line))
  18150. ((org-at-timestamp-p 'lax)
  18151. (call-interactively (if org-edit-timestamp-down-means-later
  18152. 'org-timestamp-up 'org-timestamp-down)))
  18153. ((and (not (eq org-support-shift-select 'always))
  18154. org-enable-priority-commands
  18155. (org-at-heading-p))
  18156. (call-interactively 'org-priority-down))
  18157. ((and (not org-support-shift-select) (org-at-item-p))
  18158. (call-interactively 'org-next-item))
  18159. ((org-clocktable-try-shift 'down arg))
  18160. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18161. (org-support-shift-select
  18162. (org-call-for-shift-select 'next-line))
  18163. (t (org-shiftselect-error))))
  18164. (defun org-shiftright (&optional arg)
  18165. "Cycle the thing at point or in the current line, depending on context.
  18166. Depending on context, this does one of the following:
  18167. - switch a timestamp at point one day into the future
  18168. - on a headline, switch to the next TODO keyword.
  18169. - on an item, switch entire list to the next bullet type
  18170. - on a property line, switch to the next allowed value
  18171. - on a clocktable definition line, move time block into the future"
  18172. (interactive "P")
  18173. (cond
  18174. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18175. ((and org-support-shift-select (org-region-active-p))
  18176. (org-call-for-shift-select 'forward-char))
  18177. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18178. ((and (not (eq org-support-shift-select 'always))
  18179. (org-at-heading-p))
  18180. (let ((org-inhibit-logging
  18181. (not org-treat-S-cursor-todo-selection-as-state-change))
  18182. (org-inhibit-blocking
  18183. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18184. (org-call-with-arg 'org-todo 'right)))
  18185. ((or (and org-support-shift-select
  18186. (not (eq org-support-shift-select 'always))
  18187. (org-at-item-bullet-p))
  18188. (and (not org-support-shift-select) (org-at-item-p)))
  18189. (org-call-with-arg 'org-cycle-list-bullet nil))
  18190. ((and (not (eq org-support-shift-select 'always))
  18191. (org-at-property-p))
  18192. (call-interactively 'org-property-next-allowed-value))
  18193. ((org-clocktable-try-shift 'right arg))
  18194. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18195. (org-support-shift-select
  18196. (org-call-for-shift-select 'forward-char))
  18197. (t (org-shiftselect-error))))
  18198. (defun org-shiftleft (&optional arg)
  18199. "Cycle the thing at point or in the current line, depending on context.
  18200. Depending on context, this does one of the following:
  18201. - switch a timestamp at point one day into the past
  18202. - on a headline, switch to the previous TODO keyword.
  18203. - on an item, switch entire list to the previous bullet type
  18204. - on a property line, switch to the previous allowed value
  18205. - on a clocktable definition line, move time block into the past"
  18206. (interactive "P")
  18207. (cond
  18208. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18209. ((and org-support-shift-select (org-region-active-p))
  18210. (org-call-for-shift-select 'backward-char))
  18211. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18212. ((and (not (eq org-support-shift-select 'always))
  18213. (org-at-heading-p))
  18214. (let ((org-inhibit-logging
  18215. (not org-treat-S-cursor-todo-selection-as-state-change))
  18216. (org-inhibit-blocking
  18217. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18218. (org-call-with-arg 'org-todo 'left)))
  18219. ((or (and org-support-shift-select
  18220. (not (eq org-support-shift-select 'always))
  18221. (org-at-item-bullet-p))
  18222. (and (not org-support-shift-select) (org-at-item-p)))
  18223. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18224. ((and (not (eq org-support-shift-select 'always))
  18225. (org-at-property-p))
  18226. (call-interactively 'org-property-previous-allowed-value))
  18227. ((org-clocktable-try-shift 'left arg))
  18228. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18229. (org-support-shift-select
  18230. (org-call-for-shift-select 'backward-char))
  18231. (t (org-shiftselect-error))))
  18232. (defun org-shiftcontrolright ()
  18233. "Switch to next TODO set."
  18234. (interactive)
  18235. (cond
  18236. ((and org-support-shift-select (org-region-active-p))
  18237. (org-call-for-shift-select 'forward-word))
  18238. ((and (not (eq org-support-shift-select 'always))
  18239. (org-at-heading-p))
  18240. (org-call-with-arg 'org-todo 'nextset))
  18241. (org-support-shift-select
  18242. (org-call-for-shift-select 'forward-word))
  18243. (t (org-shiftselect-error))))
  18244. (defun org-shiftcontrolleft ()
  18245. "Switch to previous TODO set."
  18246. (interactive)
  18247. (cond
  18248. ((and org-support-shift-select (org-region-active-p))
  18249. (org-call-for-shift-select 'backward-word))
  18250. ((and (not (eq org-support-shift-select 'always))
  18251. (org-at-heading-p))
  18252. (org-call-with-arg 'org-todo 'previousset))
  18253. (org-support-shift-select
  18254. (org-call-for-shift-select 'backward-word))
  18255. (t (org-shiftselect-error))))
  18256. (defun org-shiftcontrolup (&optional n)
  18257. "Change timestamps synchronously up in CLOCK log lines.
  18258. Optional argument N tells to change by that many units."
  18259. (interactive "P")
  18260. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18261. (let (org-support-shift-select)
  18262. (org-clock-timestamps-up n))
  18263. (user-error "Not at a clock log")))
  18264. (defun org-shiftcontroldown (&optional n)
  18265. "Change timestamps synchronously down in CLOCK log lines.
  18266. Optional argument N tells to change by that many units."
  18267. (interactive "P")
  18268. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18269. (let (org-support-shift-select)
  18270. (org-clock-timestamps-down n))
  18271. (user-error "Not at a clock log")))
  18272. (defun org-increase-number-at-point (&optional inc)
  18273. "Increment the number at point.
  18274. With an optional prefix numeric argument INC, increment using
  18275. this numeric value."
  18276. (interactive "p")
  18277. (if (not (number-at-point))
  18278. (user-error "Not on a number")
  18279. (unless inc (setq inc 1))
  18280. (let ((pos (point))
  18281. (beg (skip-chars-backward "-+^/*0-9eE."))
  18282. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18283. (setq nap (buffer-substring-no-properties
  18284. (+ pos beg) (+ pos beg end)))
  18285. (delete-region (+ pos beg) (+ pos beg end))
  18286. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18287. (when (org-at-table-p)
  18288. (org-table-align)
  18289. (org-table-end-of-field 1))))
  18290. (defun org-decrease-number-at-point (&optional inc)
  18291. "Decrement the number at point.
  18292. With an optional prefix numeric argument INC, decrement using
  18293. this numeric value."
  18294. (interactive "p")
  18295. (org-increase-number-at-point (- (or inc 1))))
  18296. (defun org-ctrl-c-ret ()
  18297. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18298. (interactive)
  18299. (cond
  18300. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18301. (t (call-interactively 'org-insert-heading))))
  18302. (defun org-find-visible ()
  18303. (let ((s (point)))
  18304. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18305. (get-char-property s 'invisible)))
  18306. s))
  18307. (defun org-find-invisible ()
  18308. (let ((s (point)))
  18309. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18310. (not (get-char-property s 'invisible))))
  18311. s))
  18312. (defun org-copy-visible (beg end)
  18313. "Copy the visible parts of the region."
  18314. (interactive "r")
  18315. (let ((result ""))
  18316. (while (/= beg end)
  18317. (when (get-char-property beg 'invisible)
  18318. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  18319. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  18320. (setq result (concat result (buffer-substring beg next)))
  18321. (setq beg next)))
  18322. (kill-new result)
  18323. (message "Visible strings have been copied to the kill ring.")))
  18324. (defun org-copy-special ()
  18325. "Copy region in table or copy current subtree.
  18326. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18327. context. See the individual commands for more information."
  18328. (interactive)
  18329. (call-interactively
  18330. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18331. (defun org-cut-special ()
  18332. "Cut region in table or cut current subtree.
  18333. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18334. context. See the individual commands for more information."
  18335. (interactive)
  18336. (call-interactively
  18337. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18338. (defun org-paste-special (arg)
  18339. "Paste rectangular region into table, or past subtree relative to level.
  18340. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18341. See the individual commands for more information."
  18342. (interactive "P")
  18343. (if (org-at-table-p)
  18344. (org-table-paste-rectangle)
  18345. (org-paste-subtree arg)))
  18346. (defun org-edit-special (&optional arg)
  18347. "Call a special editor for the element at point.
  18348. When at a table, call the formula editor with `org-table-edit-formulas'.
  18349. When in a source code block, call `org-edit-src-code'.
  18350. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18351. When in an export block, call `org-edit-export-block'.
  18352. When in a LaTeX environment, call `org-edit-latex-environment'.
  18353. When at an #+INCLUDE keyword, visit the included file.
  18354. When at a footnote reference, call `org-edit-footnote-reference'
  18355. On a link, call `ffap' to visit the link at point.
  18356. Otherwise, return a user error."
  18357. (interactive "P")
  18358. (let ((element (org-element-at-point)))
  18359. (barf-if-buffer-read-only)
  18360. (pcase (org-element-type element)
  18361. (`src-block
  18362. (if (not arg) (org-edit-src-code)
  18363. (let* ((info (org-babel-get-src-block-info))
  18364. (lang (nth 0 info))
  18365. (params (nth 2 info))
  18366. (session (cdr (assq :session params))))
  18367. (if (not session) (org-edit-src-code)
  18368. ;; At a src-block with a session and function called with
  18369. ;; an ARG: switch to the buffer related to the inferior
  18370. ;; process.
  18371. (switch-to-buffer
  18372. (funcall (intern (concat "org-babel-prep-session:" lang))
  18373. session params))))))
  18374. (`keyword
  18375. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18376. (org-open-link-from-string
  18377. (format "[[%s]]"
  18378. (expand-file-name
  18379. (let ((value (org-element-property :value element)))
  18380. (cond ((org-file-url-p value)
  18381. (user-error "The file is specified as a URL, cannot be edited"))
  18382. ((not (org-string-nw-p value))
  18383. (user-error "No file to edit"))
  18384. ((string-match "\\`\"\\(.*?\\)\"" value)
  18385. (match-string 1 value))
  18386. ((string-match "\\`[^ \t\"]\\S-*" value)
  18387. (match-string 0 value))
  18388. (t (user-error "No valid file specified")))))))
  18389. (user-error "No special environment to edit here")))
  18390. (`table
  18391. (if (eq (org-element-property :type element) 'table.el)
  18392. (org-edit-table.el)
  18393. (call-interactively 'org-table-edit-formulas)))
  18394. ;; Only Org tables contain `table-row' type elements.
  18395. (`table-row (call-interactively 'org-table-edit-formulas))
  18396. (`example-block (org-edit-src-code))
  18397. (`export-block (org-edit-export-block))
  18398. (`fixed-width (org-edit-fixed-width-region))
  18399. (`latex-environment (org-edit-latex-environment))
  18400. (_
  18401. ;; No notable element at point. Though, we may be at a link or
  18402. ;; a footnote reference, which are objects. Thus, scan deeper.
  18403. (let ((context (org-element-context element)))
  18404. (pcase (org-element-type context)
  18405. (`footnote-reference (org-edit-footnote-reference))
  18406. (`inline-src-block (org-edit-inline-src-code))
  18407. (`link (call-interactively #'ffap))
  18408. (_ (user-error "No special environment to edit here"))))))))
  18409. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18410. (defun org-ctrl-c-ctrl-c (&optional arg)
  18411. "Set tags in headline, or update according to changed information at point.
  18412. This command does many different things, depending on context:
  18413. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18414. this is what we do.
  18415. - If the cursor is on a statistics cookie, update it.
  18416. - If the cursor is in a headline, prompt for tags and insert them
  18417. into the current line, aligned to `org-tags-column'. When called
  18418. with prefix arg, realign all tags in the current buffer.
  18419. - If the cursor is in one of the special #+KEYWORD lines, this
  18420. triggers scanning the buffer for these lines and updating the
  18421. information.
  18422. - If the cursor is inside a table, realign the table. This command
  18423. works even if the automatic table editor has been turned off.
  18424. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18425. the entire table.
  18426. - If the cursor is at a footnote reference or definition, jump to
  18427. the corresponding definition or references, respectively.
  18428. - If the cursor is a the beginning of a dynamic block, update it.
  18429. - If the current buffer is a capture buffer, close note and file it.
  18430. - If the cursor is on a <<<target>>>, update radio targets and
  18431. corresponding links in this buffer.
  18432. - If the cursor is on a numbered item in a plain list, renumber the
  18433. ordered list.
  18434. - If the cursor is on a checkbox, toggle it.
  18435. - If the cursor is on a code block, evaluate it. The variable
  18436. `org-confirm-babel-evaluate' can be used to control prompting
  18437. before code block evaluation, by default every code block
  18438. evaluation requires confirmation. Code block evaluation can be
  18439. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18440. (interactive "P")
  18441. (cond
  18442. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18443. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18444. (org-remove-occur-highlights)
  18445. (message "Temporary highlights/overlays removed from current buffer"))
  18446. ((and (local-variable-p 'org-finish-function)
  18447. (fboundp org-finish-function))
  18448. (funcall org-finish-function))
  18449. ((org-babel-hash-at-point))
  18450. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18451. (t
  18452. (let* ((context
  18453. (org-element-lineage
  18454. (org-element-context)
  18455. ;; Limit to supported contexts.
  18456. '(babel-call clock dynamic-block footnote-definition
  18457. footnote-reference inline-babel-call inline-src-block
  18458. inlinetask item keyword node-property paragraph
  18459. plain-list planning property-drawer radio-target
  18460. src-block statistics-cookie table table-cell table-row
  18461. timestamp)
  18462. t))
  18463. (type (org-element-type context)))
  18464. ;; For convenience: at the first line of a paragraph on the same
  18465. ;; line as an item, apply function on that item instead.
  18466. (when (eq type 'paragraph)
  18467. (let ((parent (org-element-property :parent context)))
  18468. (when (and (eq (org-element-type parent) 'item)
  18469. (= (line-beginning-position)
  18470. (org-element-property :begin parent)))
  18471. (setq context parent)
  18472. (setq type 'item))))
  18473. ;; Act according to type of element or object at point.
  18474. ;;
  18475. ;; Do nothing on a blank line, except if it is contained in
  18476. ;; a src block. Hence, we first check if point is in such
  18477. ;; a block and then if it is at a blank line.
  18478. (pcase type
  18479. ((or `inline-src-block `src-block)
  18480. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  18481. (org-babel-eval-wipe-error-buffer)
  18482. (org-babel-execute-src-block
  18483. current-prefix-arg (org-babel-get-src-block-info nil context))))
  18484. ((guard (org-match-line "[ \t]*$"))
  18485. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  18486. (user-error
  18487. (substitute-command-keys
  18488. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  18489. ((or `babel-call `inline-babel-call)
  18490. (let ((info (org-babel-lob-get-info context)))
  18491. (when info (org-babel-execute-src-block nil info))))
  18492. (`clock (org-clock-update-time-maybe))
  18493. (`dynamic-block
  18494. (save-excursion
  18495. (goto-char (org-element-property :post-affiliated context))
  18496. (org-update-dblock)))
  18497. (`footnote-definition
  18498. (goto-char (org-element-property :post-affiliated context))
  18499. (call-interactively 'org-footnote-action))
  18500. (`footnote-reference (call-interactively #'org-footnote-action))
  18501. ((or `headline `inlinetask)
  18502. (save-excursion (goto-char (org-element-property :begin context))
  18503. (call-interactively #'org-set-tags-command)))
  18504. (`item
  18505. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  18506. ;; unconditionally, whereas `C-u' will toggle its presence.
  18507. ;; Without a universal argument, if the item has a checkbox,
  18508. ;; toggle it. Otherwise repair the list.
  18509. (let* ((box (org-element-property :checkbox context))
  18510. (struct (org-element-property :structure context))
  18511. (old-struct (copy-tree struct))
  18512. (parents (org-list-parents-alist struct))
  18513. (prevs (org-list-prevs-alist struct))
  18514. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  18515. (org-list-set-checkbox
  18516. (org-element-property :begin context) struct
  18517. (cond ((equal arg '(16)) "[-]")
  18518. ((and (not box) (equal arg '(4))) "[ ]")
  18519. ((or (not box) (equal arg '(4))) nil)
  18520. ((eq box 'on) "[ ]")
  18521. (t "[X]")))
  18522. ;; Mimic `org-list-write-struct' but with grabbing a return
  18523. ;; value from `org-list-struct-fix-box'.
  18524. (org-list-struct-fix-ind struct parents 2)
  18525. (org-list-struct-fix-item-end struct)
  18526. (org-list-struct-fix-bul struct prevs)
  18527. (org-list-struct-fix-ind struct parents)
  18528. (let ((block-item
  18529. (org-list-struct-fix-box struct parents prevs orderedp)))
  18530. (if (and box (equal struct old-struct))
  18531. (if (equal arg '(16))
  18532. (message "Checkboxes already reset")
  18533. (user-error "Cannot toggle this checkbox: %s"
  18534. (if (eq box 'on)
  18535. "all subitems checked"
  18536. "unchecked subitems")))
  18537. (org-list-struct-apply-struct struct old-struct)
  18538. (org-update-checkbox-count-maybe))
  18539. (when block-item
  18540. (message "Checkboxes were removed due to empty box at line %d"
  18541. (org-current-line block-item))))))
  18542. (`keyword
  18543. (let ((org-inhibit-startup-visibility-stuff t)
  18544. (org-startup-align-all-tables nil))
  18545. (when (boundp 'org-table-coordinate-overlays)
  18546. (mapc #'delete-overlay org-table-coordinate-overlays)
  18547. (setq org-table-coordinate-overlays nil))
  18548. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  18549. (message "Local setup has been refreshed"))
  18550. (`plain-list
  18551. ;; At a plain list, with a double C-u argument, set
  18552. ;; checkboxes of each item to "[-]", whereas a single one
  18553. ;; will toggle their presence according to the state of the
  18554. ;; first item in the list. Without an argument, repair the
  18555. ;; list.
  18556. (let* ((begin (org-element-property :contents-begin context))
  18557. (struct (org-element-property :structure context))
  18558. (old-struct (copy-tree struct))
  18559. (first-box (save-excursion
  18560. (goto-char begin)
  18561. (looking-at org-list-full-item-re)
  18562. (match-string-no-properties 3)))
  18563. (new-box (cond ((equal arg '(16)) "[-]")
  18564. ((equal arg '(4)) (unless first-box "[ ]"))
  18565. ((equal first-box "[X]") "[ ]")
  18566. (t "[X]"))))
  18567. (cond
  18568. (arg
  18569. (dolist (pos
  18570. (org-list-get-all-items
  18571. begin struct (org-list-prevs-alist struct)))
  18572. (org-list-set-checkbox pos struct new-box)))
  18573. ((and first-box (eq (point) begin))
  18574. ;; For convenience, when point is at bol on the first
  18575. ;; item of the list and no argument is provided, simply
  18576. ;; toggle checkbox of that item, if any.
  18577. (org-list-set-checkbox begin struct new-box)))
  18578. (when (equal
  18579. (org-list-write-struct
  18580. struct (org-list-parents-alist struct) old-struct)
  18581. old-struct)
  18582. (message "Cannot update this checkbox"))
  18583. (org-update-checkbox-count-maybe)))
  18584. ((or `property-drawer `node-property)
  18585. (call-interactively #'org-property-action))
  18586. (`radio-target
  18587. (call-interactively #'org-update-radio-target-regexp))
  18588. (`statistics-cookie
  18589. (call-interactively #'org-update-statistics-cookies))
  18590. ((or `table `table-cell `table-row)
  18591. ;; At a table, recalculate every field and align it. Also
  18592. ;; send the table if necessary. If the table has
  18593. ;; a `table.el' type, just give up. At a table row or cell,
  18594. ;; maybe recalculate line but always align table.
  18595. (if (eq (org-element-property :type context) 'table.el)
  18596. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  18597. Use `\\[org-edit-special]' to edit table.el tables"))
  18598. (if (or (eq type 'table)
  18599. ;; Check if point is at a TBLFM line.
  18600. (and (eq type 'table-row)
  18601. (= (point) (org-element-property :end context))))
  18602. (save-excursion
  18603. (if (org-at-TBLFM-p)
  18604. (progn (require 'org-table)
  18605. (org-table-calc-current-TBLFM))
  18606. (goto-char (org-element-property :contents-begin context))
  18607. (org-call-with-arg 'org-table-recalculate (or arg t))
  18608. (orgtbl-send-table 'maybe)))
  18609. (org-table-maybe-eval-formula)
  18610. (cond (arg (call-interactively #'org-table-recalculate))
  18611. ((org-table-maybe-recalculate-line))
  18612. (t (org-table-align))))))
  18613. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  18614. (org-timestamp-change 0 'day))
  18615. ((and `nil (guard (org-at-heading-p)))
  18616. ;; When point is on an unsupported object type, we can miss
  18617. ;; the fact that it also is at a heading. Handle it here.
  18618. (call-interactively #'org-set-tags-command))
  18619. ((guard
  18620. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  18621. (_
  18622. (user-error
  18623. (substitute-command-keys
  18624. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  18625. (defun org-mode-restart ()
  18626. (interactive)
  18627. (let ((indent-status (bound-and-true-p org-indent-mode)))
  18628. (funcall major-mode)
  18629. (hack-local-variables)
  18630. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  18631. (org-indent-mode -1))
  18632. (org-reset-file-cache))
  18633. (message "%s restarted" major-mode))
  18634. (defun org-kill-note-or-show-branches ()
  18635. "Abort storing current note, or call `outline-show-branches'."
  18636. (interactive)
  18637. (if (not org-finish-function)
  18638. (save-excursion
  18639. (save-restriction
  18640. (org-narrow-to-subtree)
  18641. (org-flag-subtree t)
  18642. (call-interactively 'outline-show-branches)
  18643. (org-hide-archived-subtrees (point-min) (point-max))))
  18644. (let ((org-note-abort t))
  18645. (funcall org-finish-function))))
  18646. (defun org-delete-indentation (&optional arg)
  18647. "Join current line to previous and fix whitespace at join.
  18648. If previous line is a headline add to headline title. Otherwise
  18649. the function calls `delete-indentation'.
  18650. With a non-nil optional argument, join it to the following one."
  18651. (interactive "*P")
  18652. (if (save-excursion
  18653. (beginning-of-line (if arg 1 0))
  18654. (let ((case-fold-search nil))
  18655. (looking-at org-complex-heading-regexp)))
  18656. ;; At headline.
  18657. (let ((tags-column (when (match-beginning 5)
  18658. (save-excursion (goto-char (match-beginning 5))
  18659. (current-column))))
  18660. (string (concat " " (progn (when arg (forward-line 1))
  18661. (org-trim (delete-and-extract-region
  18662. (line-beginning-position)
  18663. (line-end-position)))))))
  18664. (unless (bobp) (delete-region (point) (1- (point))))
  18665. (goto-char (or (match-end 4)
  18666. (match-beginning 5)
  18667. (match-end 0)))
  18668. (skip-chars-backward " \t")
  18669. (save-excursion (insert string))
  18670. ;; Adjust alignment of tags.
  18671. (cond
  18672. ((not tags-column)) ;no tags
  18673. (org-auto-align-tags (org-align-tags))
  18674. (t (org--align-tags-here tags-column)))) ;preserve tags column
  18675. (delete-indentation arg)))
  18676. (defun org-open-line (n)
  18677. "Insert a new row in tables, call `open-line' elsewhere.
  18678. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  18679. As a special case, when a document starts with a table, allow to
  18680. call `open-line' on the very first character."
  18681. (interactive "*p")
  18682. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  18683. (org-table-insert-row)
  18684. (open-line n)))
  18685. (defun org-return (&optional indent)
  18686. "Goto next table row or insert a newline.
  18687. Calls `org-table-next-row' or `newline', depending on context.
  18688. When optional INDENT argument is non-nil, call
  18689. `newline-and-indent' instead of `newline'.
  18690. When `org-return-follows-link' is non-nil and point is on
  18691. a timestamp or a link, call `org-open-at-point'. However, it
  18692. will not happen if point is in a table or on a \"dead\"
  18693. object (e.g., within a comment). In these case, you need to use
  18694. `org-open-at-point' directly."
  18695. (interactive)
  18696. (let ((context (if org-return-follows-link (org-element-context)
  18697. (org-element-at-point))))
  18698. (cond
  18699. ;; In a table, call `org-table-next-row'. However, before first
  18700. ;; column or after last one, split the table.
  18701. ((or (and (eq (org-element-type context) 'table)
  18702. (>= (point) (org-element-property :contents-begin context))
  18703. (< (point) (org-element-property :contents-end context)))
  18704. (org-element-lineage context '(table-row table-cell) t))
  18705. (if (or (looking-at-p "[ \t]*$")
  18706. (save-excursion (skip-chars-backward " \t") (bolp)))
  18707. (insert "\n")
  18708. (org-table-justify-field-maybe)
  18709. (call-interactively #'org-table-next-row)))
  18710. ;; On a link or a timestamp, call `org-open-at-point' if
  18711. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  18712. ;; locations, e.g., in a comment, as `org-open-at-point'.
  18713. ((and org-return-follows-link
  18714. (or (and (eq 'link (org-element-type context))
  18715. ;; Ensure point is not on the white spaces after
  18716. ;; the link.
  18717. (let ((origin (point)))
  18718. (org-with-point-at (org-element-property :end context)
  18719. (skip-chars-backward " \t")
  18720. (> (point) origin))))
  18721. (org-in-regexp org-ts-regexp-both nil t)
  18722. (org-in-regexp org-tsr-regexp-both nil t)
  18723. (org-in-regexp org-any-link-re nil t)))
  18724. (call-interactively #'org-open-at-point))
  18725. ;; Insert newline in heading, but preserve tags.
  18726. ((and (not (bolp))
  18727. (save-excursion (beginning-of-line)
  18728. (let ((case-fold-search nil))
  18729. (looking-at org-complex-heading-regexp))))
  18730. ;; At headline. Split line. However, if point is on keyword,
  18731. ;; priority cookie or tags, do not break any of them: add
  18732. ;; a newline after the headline instead.
  18733. (let ((tags-column (and (match-beginning 5)
  18734. (save-excursion (goto-char (match-beginning 5))
  18735. (current-column))))
  18736. (string
  18737. (when (and (match-end 4) (org-point-in-group (point) 4))
  18738. (delete-and-extract-region (point) (match-end 4)))))
  18739. ;; Adjust tag alignment.
  18740. (cond
  18741. ((not (and tags-column string)))
  18742. (org-auto-align-tags (org-align-tags))
  18743. (t (org--align-tags-here tags-column))) ;preserve tags column
  18744. (end-of-line)
  18745. (org-show-entry)
  18746. (if indent (newline-and-indent) (newline))
  18747. (when string (save-excursion (insert (org-trim string))))))
  18748. ;; In a list, make sure indenting keeps trailing text within.
  18749. ((and indent
  18750. (not (eolp))
  18751. (org-element-lineage context '(item)))
  18752. (let ((trailing-data
  18753. (delete-and-extract-region (point) (line-end-position))))
  18754. (newline-and-indent)
  18755. (save-excursion (insert trailing-data))))
  18756. (t
  18757. ;; Do not auto-fill when point is in an Org property drawer.
  18758. (let ((auto-fill-function (and (not (org-at-property-p))
  18759. auto-fill-function)))
  18760. (if indent
  18761. (newline-and-indent)
  18762. (newline)))))))
  18763. (defun org-return-indent ()
  18764. "Goto next table row or insert a newline and indent.
  18765. Calls `org-table-next-row' or `newline-and-indent', depending on
  18766. context. See the individual commands for more information."
  18767. (interactive)
  18768. (org-return t))
  18769. (defun org-ctrl-c-tab (&optional _arg)
  18770. "Toggle columns width in a table, or show children.
  18771. Call `org-table-toggle-column-width' if point is in a table.
  18772. Otherwise, call `org-show-children'."
  18773. (interactive "p")
  18774. (call-interactively
  18775. (if (org-at-table-p) #'org-table-toggle-column-width
  18776. #'org-show-children)))
  18777. (defun org-ctrl-c-star ()
  18778. "Compute table, or change heading status of lines.
  18779. Calls `org-table-recalculate' or `org-toggle-heading',
  18780. depending on context."
  18781. (interactive)
  18782. (cond
  18783. ((org-at-table-p)
  18784. (call-interactively 'org-table-recalculate))
  18785. (t
  18786. ;; Convert all lines in region to list items
  18787. (call-interactively 'org-toggle-heading))))
  18788. (defun org-ctrl-c-minus ()
  18789. "Insert separator line in table or modify bullet status of line.
  18790. Also turns a plain line or a region of lines into list items.
  18791. Calls `org-table-insert-hline', `org-toggle-item', or
  18792. `org-cycle-list-bullet', depending on context."
  18793. (interactive)
  18794. (cond
  18795. ((org-at-table-p)
  18796. (call-interactively 'org-table-insert-hline))
  18797. ((org-region-active-p)
  18798. (call-interactively 'org-toggle-item))
  18799. ((org-in-item-p)
  18800. (call-interactively 'org-cycle-list-bullet))
  18801. (t
  18802. (call-interactively 'org-toggle-item))))
  18803. (defun org-toggle-heading (&optional nstars)
  18804. "Convert headings to normal text, or items or text to headings.
  18805. If there is no active region, only convert the current line.
  18806. With a `\\[universal-argument]' prefix, convert the whole list at
  18807. point into heading.
  18808. In a region:
  18809. - If the first non blank line is a headline, remove the stars
  18810. from all headlines in the region.
  18811. - If it is a normal line, turn each and every normal line (i.e.,
  18812. not an heading or an item) in the region into headings. If you
  18813. want to convert only the first line of this region, use one
  18814. universal prefix argument.
  18815. - If it is a plain list item, turn all plain list items into headings.
  18816. When converting a line into a heading, the number of stars is chosen
  18817. such that the lines become children of the current entry. However,
  18818. when a numeric prefix argument is given, its value determines the
  18819. number of stars to add."
  18820. (interactive "P")
  18821. (let ((skip-blanks
  18822. (function
  18823. ;; Return beginning of first non-blank line, starting from
  18824. ;; line at POS.
  18825. (lambda (pos)
  18826. (save-excursion
  18827. (goto-char pos)
  18828. (while (org-at-comment-p) (forward-line))
  18829. (skip-chars-forward " \r\t\n")
  18830. (point-at-bol)))))
  18831. beg end toggled)
  18832. ;; Determine boundaries of changes. If a universal prefix has
  18833. ;; been given, put the list in a region. If region ends at a bol,
  18834. ;; do not consider the last line to be in the region.
  18835. (when (and current-prefix-arg (org-at-item-p))
  18836. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  18837. (org-mark-element))
  18838. (if (org-region-active-p)
  18839. (setq beg (funcall skip-blanks (region-beginning))
  18840. end (copy-marker (save-excursion
  18841. (goto-char (region-end))
  18842. (if (bolp) (point) (point-at-eol)))))
  18843. (setq beg (funcall skip-blanks (point-at-bol))
  18844. end (copy-marker (point-at-eol))))
  18845. ;; Ensure inline tasks don't count as headings.
  18846. (org-with-limited-levels
  18847. (save-excursion
  18848. (goto-char beg)
  18849. (cond
  18850. ;; Case 1. Started at an heading: de-star headings.
  18851. ((org-at-heading-p)
  18852. (while (< (point) end)
  18853. (when (org-at-heading-p t)
  18854. (looking-at org-outline-regexp) (replace-match "")
  18855. (setq toggled t))
  18856. (forward-line)))
  18857. ;; Case 2. Started at an item: change items into headlines.
  18858. ;; One star will be added by `org-list-to-subtree'.
  18859. ((org-at-item-p)
  18860. (while (< (point) end)
  18861. (when (org-at-item-p)
  18862. ;; Pay attention to cases when region ends before list.
  18863. (let* ((struct (org-list-struct))
  18864. (list-end
  18865. (min (org-list-get-bottom-point struct) (1+ end))))
  18866. (save-restriction
  18867. (narrow-to-region (point) list-end)
  18868. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  18869. (setq toggled t))
  18870. (forward-line)))
  18871. ;; Case 3. Started at normal text: make every line an heading,
  18872. ;; skipping headlines and items.
  18873. (t (let* ((stars
  18874. (make-string
  18875. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  18876. (add-stars
  18877. (cond (nstars "") ; stars from prefix only
  18878. ((equal stars "") "*") ; before first heading
  18879. (org-odd-levels-only "**") ; inside heading, odd
  18880. (t "*"))) ; inside heading, oddeven
  18881. (rpl (concat stars add-stars " "))
  18882. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  18883. (while (< (point) (if (equal nstars '(4)) lend end))
  18884. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  18885. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  18886. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  18887. (forward-line)))))))
  18888. (unless toggled (message "Cannot toggle heading from here"))))
  18889. (defun org-meta-return (&optional arg)
  18890. "Insert a new heading or wrap a region in a table.
  18891. Calls `org-insert-heading', `org-insert-item' or
  18892. `org-table-wrap-region', depending on context. When called with
  18893. an argument, unconditionally call `org-insert-heading'."
  18894. (interactive "P")
  18895. (org-check-before-invisible-edit 'insert)
  18896. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  18897. (call-interactively (cond (arg #'org-insert-heading)
  18898. ((org-at-table-p) #'org-table-wrap-region)
  18899. ((org-in-item-p) #'org-insert-item)
  18900. (t #'org-insert-heading)))))
  18901. ;;; Menu entries
  18902. (defsubst org-in-subtree-not-table-p ()
  18903. "Are we in a subtree and not in a table?"
  18904. (and (not (org-before-first-heading-p))
  18905. (not (org-at-table-p))))
  18906. ;; Define the Org mode menus
  18907. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  18908. '("Tbl"
  18909. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  18910. ["Next Field" org-cycle (org-at-table-p)]
  18911. ["Previous Field" org-shifttab (org-at-table-p)]
  18912. ["Next Row" org-return (org-at-table-p)]
  18913. "--"
  18914. ["Blank Field" org-table-blank-field (org-at-table-p)]
  18915. ["Edit Field" org-table-edit-field (org-at-table-p)]
  18916. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  18917. "--"
  18918. ("Column"
  18919. ["Move Column Left" org-metaleft (org-at-table-p)]
  18920. ["Move Column Right" org-metaright (org-at-table-p)]
  18921. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  18922. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  18923. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  18924. ("Row"
  18925. ["Move Row Up" org-metaup (org-at-table-p)]
  18926. ["Move Row Down" org-metadown (org-at-table-p)]
  18927. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  18928. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  18929. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  18930. "--"
  18931. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  18932. ("Rectangle"
  18933. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  18934. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  18935. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  18936. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  18937. "--"
  18938. ("Calculate"
  18939. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  18940. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  18941. ["Edit Formulas" org-edit-special (org-at-table-p)]
  18942. "--"
  18943. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  18944. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  18945. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  18946. "--"
  18947. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  18948. "--"
  18949. ["Sum Column/Rectangle" org-table-sum
  18950. (or (org-at-table-p) (org-region-active-p))]
  18951. ["Which Column?" org-table-current-column (org-at-table-p)])
  18952. ["Debug Formulas"
  18953. org-table-toggle-formula-debugger
  18954. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  18955. ["Show Col/Row Numbers"
  18956. org-table-toggle-coordinate-overlays
  18957. :style toggle
  18958. :selected (bound-and-true-p org-table-overlay-coordinates)]
  18959. "--"
  18960. ["Create" org-table-create (not (org-at-table-p))]
  18961. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  18962. ["Import from File" org-table-import (not (org-at-table-p))]
  18963. ["Export to File" org-table-export (org-at-table-p)]
  18964. "--"
  18965. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  18966. "--"
  18967. ("Plot"
  18968. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  18969. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  18970. (easy-menu-define org-org-menu org-mode-map "Org menu"
  18971. '("Org"
  18972. ("Show/Hide"
  18973. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  18974. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  18975. ["Sparse Tree..." org-sparse-tree t]
  18976. ["Reveal Context" org-reveal t]
  18977. ["Show All" org-show-all t]
  18978. "--"
  18979. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  18980. "--"
  18981. ["New Heading" org-insert-heading t]
  18982. ("Navigate Headings"
  18983. ["Up" outline-up-heading t]
  18984. ["Next" outline-next-visible-heading t]
  18985. ["Previous" outline-previous-visible-heading t]
  18986. ["Next Same Level" outline-forward-same-level t]
  18987. ["Previous Same Level" outline-backward-same-level t]
  18988. "--"
  18989. ["Jump" org-goto t])
  18990. ("Edit Structure"
  18991. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  18992. "--"
  18993. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  18994. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  18995. "--"
  18996. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  18997. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  18998. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  18999. "--"
  19000. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19001. "--"
  19002. ["Copy visible text" org-copy-visible t]
  19003. "--"
  19004. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19005. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19006. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19007. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19008. "--"
  19009. ["Sort Region/Children" org-sort t]
  19010. "--"
  19011. ["Convert to odd levels" org-convert-to-odd-levels t]
  19012. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19013. ("Editing"
  19014. ["Emphasis..." org-emphasize t]
  19015. ["Edit Source Example" org-edit-special t]
  19016. "--"
  19017. ["Footnote new/jump" org-footnote-action t]
  19018. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19019. ("Archive"
  19020. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19021. "--"
  19022. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19023. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19024. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19025. )
  19026. "--"
  19027. ("Hyperlinks"
  19028. ["Store Link (Global)" org-store-link t]
  19029. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19030. ["Insert Link" org-insert-link t]
  19031. ["Follow Link" org-open-at-point t]
  19032. "--"
  19033. ["Next link" org-next-link t]
  19034. ["Previous link" org-previous-link t]
  19035. "--"
  19036. ["Descriptive Links"
  19037. org-toggle-link-display
  19038. :style radio
  19039. :selected org-descriptive-links
  19040. ]
  19041. ["Literal Links"
  19042. org-toggle-link-display
  19043. :style radio
  19044. :selected (not org-descriptive-links)])
  19045. "--"
  19046. ("TODO Lists"
  19047. ["TODO/DONE/-" org-todo t]
  19048. ("Select keyword"
  19049. ["Next keyword" org-shiftright (org-at-heading-p)]
  19050. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19051. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19052. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19053. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19054. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19055. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  19056. "--"
  19057. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19058. :selected org-enforce-todo-dependencies :style toggle :active t]
  19059. "Settings for tree at point"
  19060. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19061. :selected (org-entry-get nil "ORDERED")
  19062. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19063. ["Do Children parallel" org-toggle-ordered-property :style radio
  19064. :selected (not (org-entry-get nil "ORDERED"))
  19065. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19066. "--"
  19067. ["Set Priority" org-priority t]
  19068. ["Priority Up" org-shiftup t]
  19069. ["Priority Down" org-shiftdown t]
  19070. "--"
  19071. ["Get news from all feeds" org-feed-update-all t]
  19072. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19073. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19074. ("TAGS and Properties"
  19075. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19076. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19077. "--"
  19078. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19079. ["Column view of properties" org-columns t]
  19080. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19081. ("Dates and Scheduling"
  19082. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19083. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19084. ("Change Date"
  19085. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19086. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19087. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19088. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19089. ["Compute Time Range" org-evaluate-time-range t]
  19090. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19091. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19092. "--"
  19093. ["Custom time format" org-toggle-time-stamp-overlays
  19094. :style radio :selected org-display-custom-times]
  19095. "--"
  19096. ["Goto Calendar" org-goto-calendar t]
  19097. ["Date from Calendar" org-date-from-calendar t]
  19098. "--"
  19099. ["Start/Restart Timer" org-timer-start t]
  19100. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19101. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19102. ["Insert Timer String" org-timer t]
  19103. ["Insert Timer Item" org-timer-item t])
  19104. ("Logging work"
  19105. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19106. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19107. ["Clock out" org-clock-out t]
  19108. ["Clock cancel" org-clock-cancel t]
  19109. "--"
  19110. ["Mark as default task" org-clock-mark-default-task t]
  19111. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19112. ["Goto running clock" org-clock-goto t]
  19113. "--"
  19114. ["Display times" org-clock-display t]
  19115. ["Create clock table" org-clock-report t]
  19116. "--"
  19117. ["Record DONE time"
  19118. (progn (setq org-log-done (not org-log-done))
  19119. (message "Switching to %s will %s record a timestamp"
  19120. (car org-done-keywords)
  19121. (if org-log-done "automatically" "not")))
  19122. :style toggle :selected org-log-done])
  19123. "--"
  19124. ["Agenda Command..." org-agenda t]
  19125. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19126. ("File List for Agenda")
  19127. ("Special views current file"
  19128. ["TODO Tree" org-show-todo-tree t]
  19129. ["Check Deadlines" org-check-deadlines t]
  19130. ["Tags/Property tree" org-match-sparse-tree t])
  19131. "--"
  19132. ["Export/Publish..." org-export-dispatch t]
  19133. ("LaTeX"
  19134. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  19135. :style toggle :selected org-cdlatex-mode]
  19136. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19137. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19138. ["Modify math symbol" org-cdlatex-math-modify
  19139. (org-inside-LaTeX-fragment-p)]
  19140. ["Insert citation" org-reftex-citation t])
  19141. "--"
  19142. ("MobileOrg"
  19143. ["Push Files and Views" org-mobile-push t]
  19144. ["Get Captured and Flagged" org-mobile-pull t]
  19145. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  19146. "--"
  19147. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19148. "--"
  19149. ("Documentation"
  19150. ["Show Version" org-version t]
  19151. ["Info Documentation" org-info t]
  19152. ["Browse Org News" org-browse-news t])
  19153. ("Customize"
  19154. ["Browse Org Group" org-customize t]
  19155. "--"
  19156. ["Expand This Menu" org-create-customize-menu
  19157. (fboundp 'customize-menu-create)])
  19158. ["Send bug report" org-submit-bug-report t]
  19159. "--"
  19160. ("Refresh/Reload"
  19161. ["Refresh setup current buffer" org-mode-restart t]
  19162. ["Reload Org (after update)" org-reload t]
  19163. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  19164. (defun org-info (&optional node)
  19165. "Read documentation for Org in the info system.
  19166. With optional NODE, go directly to that node."
  19167. (interactive)
  19168. (info (format "(org)%s" (or node ""))))
  19169. (defun org-browse-news ()
  19170. "Browse the news for the latest major release."
  19171. (interactive)
  19172. (browse-url "https://orgmode.org/Changes.html"))
  19173. ;;;###autoload
  19174. (defun org-submit-bug-report ()
  19175. "Submit a bug report on Org via mail.
  19176. Don't hesitate to report any problems or inaccurate documentation.
  19177. If you don't have setup sending mail from (X)Emacs, please copy the
  19178. output buffer into your mail program, as it gives us important
  19179. information about your Org version and configuration."
  19180. (interactive)
  19181. (require 'reporter)
  19182. (defvar reporter-prompt-for-summary-p)
  19183. (org-load-modules-maybe)
  19184. (org-require-autoloaded-modules)
  19185. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19186. (reporter-submit-bug-report
  19187. "emacs-orgmode@gnu.org"
  19188. (org-version nil 'full)
  19189. (let (list)
  19190. (save-window-excursion
  19191. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19192. (delete-other-windows)
  19193. (erase-buffer)
  19194. (insert "You are about to submit a bug report to the Org mailing list.
  19195. We would like to add your full Org and Outline configuration to the
  19196. bug report. This greatly simplifies the work of the maintainer and
  19197. other experts on the mailing list.
  19198. HOWEVER, some variables you have customized may contain private
  19199. information. The names of customers, colleagues, or friends, might
  19200. appear in the form of file names, tags, todo states, or search strings.
  19201. If you answer yes to the prompt, you might want to check and remove
  19202. such private information before sending the email.")
  19203. (add-text-properties (point-min) (point-max) '(face org-warning))
  19204. (when (yes-or-no-p "Include your Org configuration ")
  19205. (mapatoms
  19206. (lambda (v)
  19207. (and (boundp v)
  19208. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19209. (or (and (symbol-value v)
  19210. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19211. (and
  19212. (get v 'custom-type) (get v 'standard-value)
  19213. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19214. (push v list)))))
  19215. (kill-buffer (get-buffer "*Warn about privacy*"))
  19216. list))
  19217. nil nil
  19218. "Remember to cover the basics, that is, what you expected to happen and
  19219. what in fact did happen. You don't know how to make a good report? See
  19220. https://orgmode.org/manual/Feedback.html#Feedback
  19221. Your bug report will be posted to the Org mailing list.
  19222. ------------------------------------------------------------------------")
  19223. (save-excursion
  19224. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19225. (replace-match "\\1Bug: \\3 [\\2]")))))
  19226. (defun org-install-agenda-files-menu ()
  19227. (let ((bl (buffer-list)))
  19228. (save-excursion
  19229. (while bl
  19230. (set-buffer (pop bl))
  19231. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19232. (when (derived-mode-p 'org-mode)
  19233. (easy-menu-change
  19234. '("Org") "File List for Agenda"
  19235. (append
  19236. (list
  19237. ["Edit File List" (org-edit-agenda-file-list) t]
  19238. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19239. ["Remove Current File from List" org-remove-file t]
  19240. ["Cycle through agenda files" org-cycle-agenda-files t]
  19241. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19242. "--")
  19243. (mapcar 'org-file-menu-entry
  19244. ;; Prevent initialization from failing.
  19245. (ignore-errors (org-agenda-files t)))))))))
  19246. ;;;; Documentation
  19247. (defun org-require-autoloaded-modules ()
  19248. (interactive)
  19249. (mapc #'require
  19250. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19251. org-table org-timer)))
  19252. ;;;###autoload
  19253. (defun org-reload (&optional uncompiled)
  19254. "Reload all Org Lisp files.
  19255. With prefix arg UNCOMPILED, load the uncompiled versions."
  19256. (interactive "P")
  19257. (require 'loadhist)
  19258. (let* ((org-dir (org-find-library-dir "org"))
  19259. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19260. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19261. (remove-re (format "\\`%s\\'"
  19262. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19263. (feats (delete-dups
  19264. (mapcar 'file-name-sans-extension
  19265. (mapcar 'file-name-nondirectory
  19266. (delq nil
  19267. (mapcar 'feature-file
  19268. features))))))
  19269. (lfeat (append
  19270. (sort
  19271. (setq feats
  19272. (delq nil (mapcar
  19273. (lambda (f)
  19274. (if (and (string-match feature-re f)
  19275. (not (string-match remove-re f)))
  19276. f nil))
  19277. feats)))
  19278. 'string-lessp)
  19279. (list "org-version" "org")))
  19280. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19281. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19282. load-uncore load-misses)
  19283. (setq load-misses
  19284. (delq 't
  19285. (mapcar (lambda (f)
  19286. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19287. (and (string= org-dir contrib-dir)
  19288. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19289. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19290. (add-to-list 'load-uncore f 'append)
  19291. 't)
  19292. f))
  19293. lfeat)))
  19294. (when load-uncore
  19295. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19296. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19297. (if load-misses
  19298. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19299. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19300. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19301. ;;;###autoload
  19302. (defun org-customize ()
  19303. "Call the customize function with org as argument."
  19304. (interactive)
  19305. (org-load-modules-maybe)
  19306. (org-require-autoloaded-modules)
  19307. (customize-browse 'org))
  19308. (defun org-create-customize-menu ()
  19309. "Create a full customization menu for Org mode, insert it into the menu."
  19310. (interactive)
  19311. (org-load-modules-maybe)
  19312. (org-require-autoloaded-modules)
  19313. (if (fboundp 'customize-menu-create)
  19314. (progn
  19315. (easy-menu-change
  19316. '("Org") "Customize"
  19317. `(["Browse Org group" org-customize t]
  19318. "--"
  19319. ,(customize-menu-create 'org)
  19320. ["Set" Custom-set t]
  19321. ["Save" Custom-save t]
  19322. ["Reset to Current" Custom-reset-current t]
  19323. ["Reset to Saved" Custom-reset-saved t]
  19324. ["Reset to Standard Settings" Custom-reset-standard t]))
  19325. (message "\"Org\"-menu now contains full customization menu"))
  19326. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19327. ;;;; Miscellaneous stuff
  19328. ;;; Generally useful functions
  19329. (defun org-link-display-format (s)
  19330. "Replace links in string S with their description.
  19331. If there is no description, use the link target."
  19332. (save-match-data
  19333. (replace-regexp-in-string
  19334. org-bracket-link-analytic-regexp
  19335. (lambda (m)
  19336. (if (match-end 5) (match-string 5 m)
  19337. (concat (match-string 1 m) (match-string 3 m))))
  19338. s nil t)))
  19339. (defun org-toggle-link-display ()
  19340. "Toggle the literal or descriptive display of links."
  19341. (interactive)
  19342. (if org-descriptive-links
  19343. (remove-from-invisibility-spec '(org-link))
  19344. (add-to-invisibility-spec '(org-link)))
  19345. (org-restart-font-lock)
  19346. (setq org-descriptive-links (not org-descriptive-links)))
  19347. (defun org-in-clocktable-p ()
  19348. "Check if the cursor is in a clocktable."
  19349. (let ((pos (point)) start)
  19350. (save-excursion
  19351. (end-of-line 1)
  19352. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19353. (setq start (match-beginning 0))
  19354. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19355. (>= (match-end 0) pos)
  19356. start))))
  19357. (defun org-in-verbatim-emphasis ()
  19358. (save-match-data
  19359. (and (org-in-regexp org-verbatim-re 2)
  19360. (>= (point) (match-beginning 3))
  19361. (<= (point) (match-end 4)))))
  19362. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19363. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19364. (if (and marker (marker-buffer marker)
  19365. (buffer-live-p (marker-buffer marker)))
  19366. (progn
  19367. (pop-to-buffer-same-window (marker-buffer marker))
  19368. (when (or (> marker (point-max)) (< marker (point-min)))
  19369. (widen))
  19370. (goto-char marker)
  19371. (org-show-context 'org-goto))
  19372. (if bookmark
  19373. (bookmark-jump bookmark)
  19374. (error "Cannot find location"))))
  19375. (defun org-quote-csv-field (s)
  19376. "Quote field for inclusion in CSV material."
  19377. (if (string-match "[\",]" s)
  19378. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19379. s))
  19380. (defun org-force-self-insert (N)
  19381. "Needed to enforce self-insert under remapping."
  19382. (interactive "p")
  19383. (self-insert-command N))
  19384. (defun org-fill-template (template alist)
  19385. "Find each %key of ALIST in TEMPLATE and replace it."
  19386. (let ((case-fold-search nil))
  19387. (dolist (entry (sort (copy-sequence alist)
  19388. (lambda (a b) (< (length (car a)) (length (car b))))))
  19389. (setq template
  19390. (replace-regexp-in-string
  19391. (concat "%" (regexp-quote (car entry)))
  19392. (or (cdr entry) "") template t t)))
  19393. template))
  19394. (defun org-quote-vert (s)
  19395. "Replace \"|\" with \"\\vert\"."
  19396. (while (string-match "|" s)
  19397. (setq s (replace-match "\\vert" t t s)))
  19398. s)
  19399. (defun org-uuidgen-p (s)
  19400. "Is S an ID created by UUIDGEN?"
  19401. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  19402. (defun org-in-src-block-p (&optional inside)
  19403. "Whether point is in a code source block.
  19404. When INSIDE is non-nil, don't consider we are within a src block
  19405. when point is at #+BEGIN_SRC or #+END_SRC."
  19406. (let ((case-fold-search t))
  19407. (or (and (eq (get-char-property (point) 'src-block) t))
  19408. (and (not inside)
  19409. (save-match-data
  19410. (save-excursion
  19411. (beginning-of-line)
  19412. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  19413. (defun org-context ()
  19414. "Return a list of contexts of the current cursor position.
  19415. If several contexts apply, all are returned.
  19416. Each context entry is a list with a symbol naming the context, and
  19417. two positions indicating start and end of the context. Possible
  19418. contexts are:
  19419. :headline anywhere in a headline
  19420. :headline-stars on the leading stars in a headline
  19421. :todo-keyword on a TODO keyword (including DONE) in a headline
  19422. :tags on the TAGS in a headline
  19423. :priority on the priority cookie in a headline
  19424. :item on the first line of a plain list item
  19425. :item-bullet on the bullet/number of a plain list item
  19426. :checkbox on the checkbox in a plain list item
  19427. :table in an Org table
  19428. :table-special on a special filed in a table
  19429. :table-table in a table.el table
  19430. :clocktable in a clocktable
  19431. :src-block in a source block
  19432. :link on a hyperlink
  19433. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  19434. :target on a <<target>>
  19435. :radio-target on a <<<radio-target>>>
  19436. :latex-fragment on a LaTeX fragment
  19437. :latex-preview on a LaTeX fragment with overlaid preview image
  19438. This function expects the position to be visible because it uses font-lock
  19439. faces as a help to recognize the following contexts: :table-special, :link,
  19440. and :keyword."
  19441. (let* ((f (get-text-property (point) 'face))
  19442. (faces (if (listp f) f (list f)))
  19443. (case-fold-search t)
  19444. (p (point)) clist o)
  19445. ;; First the large context
  19446. (cond
  19447. ((org-at-heading-p t)
  19448. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  19449. (when (progn
  19450. (beginning-of-line 1)
  19451. (looking-at org-todo-line-tags-regexp))
  19452. (push (org-point-in-group p 1 :headline-stars) clist)
  19453. (push (org-point-in-group p 2 :todo-keyword) clist)
  19454. (push (org-point-in-group p 4 :tags) clist))
  19455. (goto-char p)
  19456. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  19457. (when (looking-at "\\[#[A-Z0-9]\\]")
  19458. (push (org-point-in-group p 0 :priority) clist)))
  19459. ((org-at-item-p)
  19460. (push (org-point-in-group p 2 :item-bullet) clist)
  19461. (push (list :item (point-at-bol)
  19462. (save-excursion (org-end-of-item) (point)))
  19463. clist)
  19464. (and (org-at-item-checkbox-p)
  19465. (push (org-point-in-group p 0 :checkbox) clist)))
  19466. ((org-at-table-p)
  19467. (push (list :table (org-table-begin) (org-table-end)) clist)
  19468. (when (memq 'org-formula faces)
  19469. (push (list :table-special
  19470. (previous-single-property-change p 'face)
  19471. (next-single-property-change p 'face)) clist)))
  19472. ((org-at-table-p 'any)
  19473. (push (list :table-table) clist)))
  19474. (goto-char p)
  19475. (let ((case-fold-search t))
  19476. ;; New the "medium" contexts: clocktables, source blocks
  19477. (cond ((org-in-clocktable-p)
  19478. (push (list :clocktable
  19479. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  19480. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  19481. (match-beginning 1))
  19482. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  19483. (match-end 0))) clist))
  19484. ((org-in-src-block-p)
  19485. (push (list :src-block
  19486. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  19487. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  19488. (match-beginning 1))
  19489. (and (search-forward "#+END_SRC" nil t)
  19490. (match-beginning 0))) clist))))
  19491. (goto-char p)
  19492. ;; Now the small context
  19493. (cond
  19494. ((org-at-timestamp-p)
  19495. (push (org-point-in-group p 0 :timestamp) clist))
  19496. ((memq 'org-link faces)
  19497. (push (list :link
  19498. (previous-single-property-change p 'face)
  19499. (next-single-property-change p 'face)) clist))
  19500. ((memq 'org-special-keyword faces)
  19501. (push (list :keyword
  19502. (previous-single-property-change p 'face)
  19503. (next-single-property-change p 'face)) clist))
  19504. ((org-at-target-p)
  19505. (push (org-point-in-group p 0 :target) clist)
  19506. (goto-char (1- (match-beginning 0)))
  19507. (when (looking-at org-radio-target-regexp)
  19508. (push (org-point-in-group p 0 :radio-target) clist))
  19509. (goto-char p))
  19510. ((setq o (cl-some
  19511. (lambda (o)
  19512. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  19513. o))
  19514. (overlays-at (point))))
  19515. (push (list :latex-fragment
  19516. (overlay-start o) (overlay-end o)) clist)
  19517. (push (list :latex-preview
  19518. (overlay-start o) (overlay-end o)) clist))
  19519. ((org-inside-LaTeX-fragment-p)
  19520. ;; FIXME: positions wrong.
  19521. (push (list :latex-fragment (point) (point)) clist)))
  19522. (setq clist (nreverse (delq nil clist)))
  19523. clist))
  19524. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  19525. "Non-nil when point is between matches of START-RE and END-RE.
  19526. Also return a non-nil value when point is on one of the matches.
  19527. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  19528. buffer positions. Default values are the positions of headlines
  19529. surrounding the point.
  19530. The functions returns a cons cell whose car (resp. cdr) is the
  19531. position before START-RE (resp. after END-RE)."
  19532. (save-match-data
  19533. (let ((pos (point))
  19534. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  19535. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  19536. beg end)
  19537. (save-excursion
  19538. ;; Point is on a block when on START-RE or if START-RE can be
  19539. ;; found before it...
  19540. (and (or (org-in-regexp start-re)
  19541. (re-search-backward start-re limit-up t))
  19542. (setq beg (match-beginning 0))
  19543. ;; ... and END-RE after it...
  19544. (goto-char (match-end 0))
  19545. (re-search-forward end-re limit-down t)
  19546. (> (setq end (match-end 0)) pos)
  19547. ;; ... without another START-RE in-between.
  19548. (goto-char (match-beginning 0))
  19549. (not (re-search-backward start-re (1+ beg) t))
  19550. ;; Return value.
  19551. (cons beg end))))))
  19552. (defun org-in-block-p (names)
  19553. "Non-nil when point belongs to a block whose name belongs to NAMES.
  19554. NAMES is a list of strings containing names of blocks.
  19555. Return first block name matched, or nil. Beware that in case of
  19556. nested blocks, the returned name may not belong to the closest
  19557. block from point."
  19558. (save-match-data
  19559. (catch 'exit
  19560. (let ((case-fold-search t)
  19561. (lim-up (save-excursion (outline-previous-heading)))
  19562. (lim-down (save-excursion (outline-next-heading))))
  19563. (dolist (name names)
  19564. (let ((n (regexp-quote name)))
  19565. (when (org-between-regexps-p
  19566. (concat "^[ \t]*#\\+begin_" n)
  19567. (concat "^[ \t]*#\\+end_" n)
  19568. lim-up lim-down)
  19569. (throw 'exit n)))))
  19570. nil)))
  19571. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  19572. "Call `multi-occur' with buffers for all agenda files."
  19573. (interactive "sOrg-files matching: ")
  19574. (let* ((files (org-agenda-files))
  19575. (tnames (mapcar #'file-truename files))
  19576. (extra org-agenda-text-search-extra-files))
  19577. (when (eq (car extra) 'agenda-archives)
  19578. (setq extra (cdr extra))
  19579. (setq files (org-add-archive-files files)))
  19580. (dolist (f extra)
  19581. (unless (member (file-truename f) tnames)
  19582. (unless (member f files) (setq files (append files (list f))))
  19583. (setq tnames (append tnames (list (file-truename f))))))
  19584. (multi-occur
  19585. (mapcar (lambda (x)
  19586. (with-current-buffer
  19587. ;; FIXME: Why not just (find-file-noselect x)?
  19588. ;; Is it to avoid the "revert buffer" prompt?
  19589. (or (get-file-buffer x) (find-file-noselect x))
  19590. (widen)
  19591. (current-buffer)))
  19592. files)
  19593. regexp)))
  19594. (add-hook 'occur-mode-find-occurrence-hook
  19595. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  19596. (defun org-occur-link-in-agenda-files ()
  19597. "Create a link and search for it in the agendas.
  19598. The link is not stored in `org-stored-links', it is just created
  19599. for the search purpose."
  19600. (interactive)
  19601. (let ((link (condition-case nil
  19602. (org-store-link nil)
  19603. (error "Unable to create a link to here"))))
  19604. (org-occur-in-agenda-files (regexp-quote link))))
  19605. (defun org-back-over-empty-lines ()
  19606. "Move backwards over whitespace, to the beginning of the first empty line.
  19607. Returns the number of empty lines passed."
  19608. (let ((pos (point)))
  19609. (if (cdr (assq 'heading org-blank-before-new-entry))
  19610. (skip-chars-backward " \t\n\r")
  19611. (unless (eobp)
  19612. (forward-line -1)))
  19613. (beginning-of-line 2)
  19614. (goto-char (min (point) pos))
  19615. (count-lines (point) pos)))
  19616. (defun org-replace-escapes (string table)
  19617. "Replace %-escapes in STRING with values in TABLE.
  19618. TABLE is an association list with keys like \"%a\" and string values.
  19619. The sequences in STRING may contain normal field width and padding information,
  19620. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  19621. so values can contain further %-escapes if they are define later in TABLE."
  19622. (let ((tbl (copy-alist table))
  19623. (case-fold-search nil)
  19624. (pchg 0)
  19625. re rpl)
  19626. (dolist (e tbl)
  19627. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  19628. (when (and (cdr e) (string-match re (cdr e)))
  19629. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  19630. (safe "SREF"))
  19631. (add-text-properties 0 3 (list 'sref sref) safe)
  19632. (setcdr e (replace-match safe t t (cdr e)))))
  19633. (while (string-match re string)
  19634. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  19635. (cdr e)))
  19636. (setq string (replace-match rpl t t string))))
  19637. (while (setq pchg (next-property-change pchg string))
  19638. (let ((sref (get-text-property pchg 'sref string)))
  19639. (when (and sref (string-match "SREF" string pchg))
  19640. (setq string (replace-match sref t t string)))))
  19641. string))
  19642. ;;; TODO: Only called once, from ox-odt which should probably use
  19643. ;;; org-export-inline-image-p or something.
  19644. (defun org-file-image-p (file)
  19645. "Return non-nil if FILE is an image."
  19646. (save-match-data
  19647. (string-match (image-file-name-regexp) file)))
  19648. (defun org-get-cursor-date (&optional with-time)
  19649. "Return the date at cursor in as a time.
  19650. This works in the calendar and in the agenda, anywhere else it just
  19651. returns the current time.
  19652. If WITH-TIME is non-nil, returns the time of the event at point (in
  19653. the agenda) or the current time of the day."
  19654. (let (date day defd tp hod mod)
  19655. (when with-time
  19656. (setq tp (get-text-property (point) 'time))
  19657. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  19658. (setq hod (string-to-number (match-string 1 tp))
  19659. mod (string-to-number (match-string 2 tp))))
  19660. (or tp (let ((now (decode-time)))
  19661. (setq hod (nth 2 now)
  19662. mod (nth 1 now)))))
  19663. (cond
  19664. ((eq major-mode 'calendar-mode)
  19665. (setq date (calendar-cursor-to-date)
  19666. defd (encode-time 0 (or mod 0) (or hod 0)
  19667. (nth 1 date) (nth 0 date) (nth 2 date))))
  19668. ((eq major-mode 'org-agenda-mode)
  19669. (setq day (get-text-property (point) 'day))
  19670. (when day
  19671. (setq date (calendar-gregorian-from-absolute day)
  19672. defd (encode-time 0 (or mod 0) (or hod 0)
  19673. (nth 1 date) (nth 0 date) (nth 2 date))))))
  19674. (or defd (current-time))))
  19675. (defun org-mark-subtree (&optional up)
  19676. "Mark the current subtree.
  19677. This puts point at the start of the current subtree, and mark at
  19678. the end. If a numeric prefix UP is given, move up into the
  19679. hierarchy of headlines by UP levels before marking the subtree."
  19680. (interactive "P")
  19681. (org-with-limited-levels
  19682. (cond ((org-at-heading-p) (beginning-of-line))
  19683. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  19684. (t (outline-previous-visible-heading 1))))
  19685. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  19686. (if (called-interactively-p 'any)
  19687. (call-interactively 'org-mark-element)
  19688. (org-mark-element)))
  19689. ;;; Indentation
  19690. (defvar org-element-greater-elements)
  19691. (defun org--get-expected-indentation (element contentsp)
  19692. "Expected indentation column for current line, according to ELEMENT.
  19693. ELEMENT is an element containing point. CONTENTSP is non-nil
  19694. when indentation is to be computed according to contents of
  19695. ELEMENT."
  19696. (let ((type (org-element-type element))
  19697. (start (org-element-property :begin element))
  19698. (post-affiliated (org-element-property :post-affiliated element)))
  19699. (org-with-wide-buffer
  19700. (cond
  19701. (contentsp
  19702. (cl-case type
  19703. ((diary-sexp footnote-definition) 0)
  19704. ((headline inlinetask nil)
  19705. (if (not org-adapt-indentation) 0
  19706. (let ((level (org-current-level)))
  19707. (if level (1+ level) 0))))
  19708. ((item plain-list) (org-list-item-body-column post-affiliated))
  19709. (t
  19710. (goto-char start)
  19711. (current-indentation))))
  19712. ((memq type '(headline inlinetask nil))
  19713. (if (org-match-line "[ \t]*$")
  19714. (org--get-expected-indentation element t)
  19715. 0))
  19716. ((memq type '(diary-sexp footnote-definition)) 0)
  19717. ;; First paragraph of a footnote definition or an item.
  19718. ;; Indent like parent.
  19719. ((< (line-beginning-position) start)
  19720. (org--get-expected-indentation
  19721. (org-element-property :parent element) t))
  19722. ;; At first line: indent according to previous sibling, if any,
  19723. ;; ignoring footnote definitions and inline tasks, or parent's
  19724. ;; contents.
  19725. ((= (line-beginning-position) start)
  19726. (catch 'exit
  19727. (while t
  19728. (if (= (point-min) start) (throw 'exit 0)
  19729. (goto-char (1- start))
  19730. (let* ((previous (org-element-at-point))
  19731. (parent previous))
  19732. (while (and parent (<= (org-element-property :end parent) start))
  19733. (setq previous parent
  19734. parent (org-element-property :parent parent)))
  19735. (cond
  19736. ((not previous) (throw 'exit 0))
  19737. ((> (org-element-property :end previous) start)
  19738. (throw 'exit (org--get-expected-indentation previous t)))
  19739. ((memq (org-element-type previous)
  19740. '(footnote-definition inlinetask))
  19741. (setq start (org-element-property :begin previous)))
  19742. (t (goto-char (org-element-property :begin previous))
  19743. (throw 'exit
  19744. (if (bolp) (current-indentation)
  19745. ;; At first paragraph in an item or
  19746. ;; a footnote definition.
  19747. (org--get-expected-indentation
  19748. (org-element-property :parent previous) t))))))))))
  19749. ;; Otherwise, move to the first non-blank line above.
  19750. (t
  19751. (beginning-of-line)
  19752. (let ((pos (point)))
  19753. (skip-chars-backward " \r\t\n")
  19754. (cond
  19755. ;; Two blank lines end a footnote definition or a plain
  19756. ;; list. When we indent an empty line after them, the
  19757. ;; containing list or footnote definition is over, so it
  19758. ;; qualifies as a previous sibling. Therefore, we indent
  19759. ;; like its first line.
  19760. ((and (memq type '(footnote-definition plain-list))
  19761. (> (count-lines (point) pos) 2))
  19762. (goto-char start)
  19763. (current-indentation))
  19764. ;; Line above is the first one of a paragraph at the
  19765. ;; beginning of an item or a footnote definition. Indent
  19766. ;; like parent.
  19767. ((< (line-beginning-position) start)
  19768. (org--get-expected-indentation
  19769. (org-element-property :parent element) t))
  19770. ;; Line above is the beginning of an element, i.e., point
  19771. ;; was originally on the blank lines between element's start
  19772. ;; and contents.
  19773. ((= (line-beginning-position) post-affiliated)
  19774. (org--get-expected-indentation element t))
  19775. ;; POS is after contents in a greater element. Indent like
  19776. ;; the beginning of the element.
  19777. ((and (memq type org-element-greater-elements)
  19778. (let ((cend (org-element-property :contents-end element)))
  19779. (and cend (<= cend pos))))
  19780. ;; As a special case, if point is at the end of a footnote
  19781. ;; definition or an item, indent like the very last element
  19782. ;; within. If that last element is an item, indent like
  19783. ;; its contents.
  19784. (if (memq type '(footnote-definition item plain-list))
  19785. (let ((last (org-element-at-point)))
  19786. (goto-char pos)
  19787. (org--get-expected-indentation
  19788. last (eq (org-element-type last) 'item)))
  19789. (goto-char start)
  19790. (current-indentation)))
  19791. ;; In any other case, indent like the current line.
  19792. (t (current-indentation)))))))))
  19793. (defun org--align-node-property ()
  19794. "Align node property at point.
  19795. Alignment is done according to `org-property-format', which see."
  19796. (when (save-excursion
  19797. (beginning-of-line)
  19798. (looking-at org-property-re))
  19799. (replace-match
  19800. (concat (match-string 4)
  19801. (org-trim
  19802. (format org-property-format (match-string 1) (match-string 3))))
  19803. t t)))
  19804. (defun org-indent-line ()
  19805. "Indent line depending on context.
  19806. Indentation is done according to the following rules:
  19807. - Footnote definitions, diary sexps, headlines and inline tasks
  19808. have to start at column 0.
  19809. - On the very first line of an element, consider, in order, the
  19810. next rules until one matches:
  19811. 1. If there's a sibling element before, ignoring footnote
  19812. definitions and inline tasks, indent like its first line.
  19813. 2. If element has a parent, indent like its contents. More
  19814. precisely, if parent is an item, indent after the
  19815. description part, if any, or the bullet (see
  19816. `org-list-description-max-indent'). Else, indent like
  19817. parent's first line.
  19818. 3. Otherwise, indent relatively to current level, if
  19819. `org-adapt-indentation' is non-nil, or to left margin.
  19820. - On a blank line at the end of an element, indent according to
  19821. the type of the element. More precisely
  19822. 1. If element is a plain list, an item, or a footnote
  19823. definition, indent like the very last element within.
  19824. 2. If element is a paragraph, indent like its last non blank
  19825. line.
  19826. 3. Otherwise, indent like its very first line.
  19827. - In the code part of a source block, use language major mode
  19828. to indent current line if `org-src-tab-acts-natively' is
  19829. non-nil. If it is nil, do nothing.
  19830. - Otherwise, indent like the first non-blank line above.
  19831. The function doesn't indent an item as it could break the whole
  19832. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  19833. `\\[org-shiftmetaright]'.
  19834. Also align node properties according to `org-property-format'."
  19835. (interactive)
  19836. (cond
  19837. ((org-at-heading-p) 'noindent)
  19838. (t
  19839. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  19840. (type (org-element-type element)))
  19841. (cond ((and (memq type '(plain-list item))
  19842. (= (line-beginning-position)
  19843. (org-element-property :post-affiliated element)))
  19844. 'noindent)
  19845. ((and (eq type 'latex-environment)
  19846. (>= (point) (org-element-property :post-affiliated element))
  19847. (< (point) (org-with-wide-buffer
  19848. (goto-char (org-element-property :end element))
  19849. (skip-chars-backward " \r\t\n")
  19850. (line-beginning-position 2))))
  19851. 'noindent)
  19852. ((and (eq type 'src-block)
  19853. org-src-tab-acts-natively
  19854. (> (line-beginning-position)
  19855. (org-element-property :post-affiliated element))
  19856. (< (line-beginning-position)
  19857. (org-with-wide-buffer
  19858. (goto-char (org-element-property :end element))
  19859. (skip-chars-backward " \r\t\n")
  19860. (line-beginning-position))))
  19861. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  19862. (t
  19863. (let ((column (org--get-expected-indentation element nil)))
  19864. ;; Preserve current column.
  19865. (if (<= (current-column) (current-indentation))
  19866. (indent-line-to column)
  19867. (save-excursion (indent-line-to column))))
  19868. ;; Align node property. Also preserve current column.
  19869. (when (eq type 'node-property)
  19870. (let ((column (current-column)))
  19871. (org--align-node-property)
  19872. (org-move-to-column column)))))))))
  19873. (defun org-indent-region (start end)
  19874. "Indent each non-blank line in the region.
  19875. Called from a program, START and END specify the region to
  19876. indent. The function will not indent contents of example blocks,
  19877. verse blocks and export blocks as leading white spaces are
  19878. assumed to be significant there."
  19879. (interactive "r")
  19880. (save-excursion
  19881. (goto-char start)
  19882. (skip-chars-forward " \r\t\n")
  19883. (unless (eobp) (beginning-of-line))
  19884. (let ((indent-to
  19885. (lambda (ind pos)
  19886. ;; Set IND as indentation for all lines between point and
  19887. ;; POS. Blank lines are ignored. Leave point after POS
  19888. ;; once done.
  19889. (let ((limit (copy-marker pos)))
  19890. (while (< (point) limit)
  19891. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  19892. (forward-line))
  19893. (set-marker limit nil))))
  19894. (end (copy-marker end)))
  19895. (while (< (point) end)
  19896. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  19897. (let* ((element (org-element-at-point))
  19898. (type (org-element-type element))
  19899. (element-end (copy-marker (org-element-property :end element)))
  19900. (ind (org--get-expected-indentation element nil)))
  19901. (cond
  19902. ;; Element indented as a single block. Example blocks
  19903. ;; preserving indentation are a special case since the
  19904. ;; "contents" must not be indented whereas the block
  19905. ;; boundaries can.
  19906. ((or (memq type '(export-block latex-environment))
  19907. (and (eq type 'example-block)
  19908. (not
  19909. (or org-src-preserve-indentation
  19910. (org-element-property :preserve-indent element)))))
  19911. (let ((offset (- ind (current-indentation))))
  19912. (unless (zerop offset)
  19913. (indent-rigidly (org-element-property :begin element)
  19914. (org-element-property :end element)
  19915. offset)))
  19916. (goto-char element-end))
  19917. ;; Elements indented line wise. Be sure to exclude
  19918. ;; example blocks (preserving indentation) and source
  19919. ;; blocks from this category as they are treated
  19920. ;; specially later.
  19921. ((or (memq type '(paragraph table table-row))
  19922. (not (or (org-element-property :contents-begin element)
  19923. (memq type '(example-block src-block)))))
  19924. (when (eq type 'node-property)
  19925. (org--align-node-property)
  19926. (beginning-of-line))
  19927. (funcall indent-to ind (min element-end end)))
  19928. ;; Elements consisting of three parts: before the
  19929. ;; contents, the contents, and after the contents. The
  19930. ;; contents are treated specially, according to the
  19931. ;; element type, or not indented at all. Other parts are
  19932. ;; indented as a single block.
  19933. (t
  19934. (let* ((post (copy-marker
  19935. (org-element-property :post-affiliated element)))
  19936. (cbeg
  19937. (copy-marker
  19938. (cond
  19939. ((not (org-element-property :contents-begin element))
  19940. ;; Fake contents for source blocks.
  19941. (org-with-wide-buffer
  19942. (goto-char post)
  19943. (line-beginning-position 2)))
  19944. ((memq type '(footnote-definition item plain-list))
  19945. ;; Contents in these elements could start on
  19946. ;; the same line as the beginning of the
  19947. ;; element. Make sure we start indenting
  19948. ;; from the second line.
  19949. (org-with-wide-buffer
  19950. (goto-char post)
  19951. (end-of-line)
  19952. (skip-chars-forward " \r\t\n")
  19953. (if (eobp) (point) (line-beginning-position))))
  19954. (t (org-element-property :contents-begin element)))))
  19955. (cend (copy-marker
  19956. (or (org-element-property :contents-end element)
  19957. ;; Fake contents for source blocks.
  19958. (org-with-wide-buffer
  19959. (goto-char element-end)
  19960. (skip-chars-backward " \r\t\n")
  19961. (line-beginning-position)))
  19962. t)))
  19963. ;; Do not change items indentation individually as it
  19964. ;; might break the list as a whole. On the other
  19965. ;; hand, when at a plain list, indent it as a whole.
  19966. (cond ((eq type 'plain-list)
  19967. (let ((offset (- ind (current-indentation))))
  19968. (unless (zerop offset)
  19969. (indent-rigidly (org-element-property :begin element)
  19970. (org-element-property :end element)
  19971. offset))
  19972. (goto-char cbeg)))
  19973. ((eq type 'item) (goto-char cbeg))
  19974. (t (funcall indent-to ind (min cbeg end))))
  19975. (when (< (point) end)
  19976. (cl-case type
  19977. ((example-block verse-block))
  19978. (src-block
  19979. ;; In a source block, indent source code
  19980. ;; according to language major mode, but only if
  19981. ;; `org-src-tab-acts-natively' is non-nil.
  19982. (when (and (< (point) end) org-src-tab-acts-natively)
  19983. (ignore-errors
  19984. (org-babel-do-in-edit-buffer
  19985. (indent-region (point-min) (point-max))))))
  19986. (t (org-indent-region (point) (min cend end))))
  19987. (goto-char (min cend end))
  19988. (when (< (point) end)
  19989. (funcall indent-to ind (min element-end end))))
  19990. (set-marker post nil)
  19991. (set-marker cbeg nil)
  19992. (set-marker cend nil))))
  19993. (set-marker element-end nil))))
  19994. (set-marker end nil))))
  19995. (defun org-indent-drawer ()
  19996. "Indent the drawer at point."
  19997. (interactive)
  19998. (unless (save-excursion
  19999. (beginning-of-line)
  20000. (looking-at-p org-drawer-regexp))
  20001. (user-error "Not at a drawer"))
  20002. (let ((element (org-element-at-point)))
  20003. (unless (memq (org-element-type element) '(drawer property-drawer))
  20004. (user-error "Not at a drawer"))
  20005. (org-with-wide-buffer
  20006. (org-indent-region (org-element-property :begin element)
  20007. (org-element-property :end element))))
  20008. (message "Drawer at point indented"))
  20009. (defun org-indent-block ()
  20010. "Indent the block at point."
  20011. (interactive)
  20012. (unless (save-excursion
  20013. (beginning-of-line)
  20014. (let ((case-fold-search t))
  20015. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  20016. (user-error "Not at a block"))
  20017. (let ((element (org-element-at-point)))
  20018. (unless (memq (org-element-type element)
  20019. '(comment-block center-block dynamic-block example-block
  20020. export-block quote-block special-block
  20021. src-block verse-block))
  20022. (user-error "Not at a block"))
  20023. (org-with-wide-buffer
  20024. (org-indent-region (org-element-property :begin element)
  20025. (org-element-property :end element))))
  20026. (message "Block at point indented"))
  20027. ;;; Filling
  20028. ;; We use our own fill-paragraph and auto-fill functions.
  20029. ;; `org-fill-paragraph' relies on adaptive filling and context
  20030. ;; checking. Appropriate `fill-prefix' is computed with
  20031. ;; `org-adaptive-fill-function'.
  20032. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20033. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20034. ;; `org-adaptive-fill-function' value. Internally,
  20035. ;; `org-comment-line-break-function' breaks the line.
  20036. ;; `org-setup-filling' installs filling and auto-filling related
  20037. ;; variables during `org-mode' initialization.
  20038. (defun org-setup-filling ()
  20039. (require 'org-element)
  20040. ;; Prevent auto-fill from inserting unwanted new items.
  20041. (when (boundp 'fill-nobreak-predicate)
  20042. (setq-local
  20043. fill-nobreak-predicate
  20044. (org-uniquify
  20045. (append fill-nobreak-predicate
  20046. '(org-fill-line-break-nobreak-p
  20047. org-fill-n-macro-as-item-nobreak-p
  20048. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20049. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20050. (setq-local paragraph-start paragraph-ending)
  20051. (setq-local paragraph-separate paragraph-ending))
  20052. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20053. (setq-local auto-fill-inhibit-regexp nil)
  20054. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20055. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20056. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20057. (defun org-fill-line-break-nobreak-p ()
  20058. "Non-nil when a new line at point would create an Org line break."
  20059. (save-excursion
  20060. (skip-chars-backward "[ \t]")
  20061. (skip-chars-backward "\\\\")
  20062. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20063. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20064. "Non-nil when a new line at point would split a timestamp."
  20065. (and (org-at-timestamp-p 'lax)
  20066. (not (looking-at org-ts-regexp-both))))
  20067. (defun org-fill-n-macro-as-item-nobreak-p ()
  20068. "Non-nil when a new line at point would create a new list."
  20069. ;; During export, a "n" macro followed by a dot or a closing
  20070. ;; parenthesis can end up being parsed as a new list item.
  20071. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20072. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20073. (defun org-adaptive-fill-function ()
  20074. "Compute a fill prefix for the current line.
  20075. Return fill prefix, as a string, or nil if current line isn't
  20076. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20077. matches in paragraphs or comments, use it."
  20078. (org-with-wide-buffer
  20079. (unless (org-at-heading-p)
  20080. (let* ((p (line-beginning-position))
  20081. (element (save-excursion
  20082. (beginning-of-line)
  20083. (org-element-at-point)))
  20084. (type (org-element-type element))
  20085. (post-affiliated (org-element-property :post-affiliated element)))
  20086. (unless (< p post-affiliated)
  20087. (cl-case type
  20088. (comment
  20089. (save-excursion
  20090. (beginning-of-line)
  20091. (looking-at "[ \t]*")
  20092. (concat (match-string 0) "# ")))
  20093. (footnote-definition "")
  20094. ((item plain-list)
  20095. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20096. (paragraph
  20097. ;; Fill prefix is usually the same as the current line,
  20098. ;; unless the paragraph is at the beginning of an item.
  20099. (let ((parent (org-element-property :parent element)))
  20100. (save-excursion
  20101. (beginning-of-line)
  20102. (cond ((eq (org-element-type parent) 'item)
  20103. (make-string (org-list-item-body-column
  20104. (org-element-property :begin parent))
  20105. ?\s))
  20106. ((and adaptive-fill-regexp
  20107. ;; Locally disable
  20108. ;; `adaptive-fill-function' to let
  20109. ;; `fill-context-prefix' handle
  20110. ;; `adaptive-fill-regexp' variable.
  20111. (let (adaptive-fill-function)
  20112. (fill-context-prefix
  20113. post-affiliated
  20114. (org-element-property :end element)))))
  20115. ((looking-at "[ \t]+") (match-string 0))
  20116. (t "")))))
  20117. (comment-block
  20118. ;; Only fill contents if P is within block boundaries.
  20119. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20120. (forward-line)
  20121. (point)))
  20122. (cend (save-excursion
  20123. (goto-char (org-element-property :end element))
  20124. (skip-chars-backward " \r\t\n")
  20125. (line-beginning-position))))
  20126. (when (and (>= p cbeg) (< p cend))
  20127. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20128. (match-string 0)
  20129. ""))))))))))
  20130. (defun org-fill-element (&optional justify)
  20131. "Fill element at point, when applicable.
  20132. This function only applies to comment blocks, comments, example
  20133. blocks and paragraphs. Also, as a special case, re-align table
  20134. when point is at one.
  20135. If JUSTIFY is non-nil (interactively, with prefix argument),
  20136. justify as well. If `sentence-end-double-space' is non-nil, then
  20137. period followed by one space does not end a sentence, so don't
  20138. break a line there. The variable `fill-column' controls the
  20139. width for filling.
  20140. For convenience, when point is at a plain list, an item or
  20141. a footnote definition, try to fill the first paragraph within."
  20142. (with-syntax-table org-mode-transpose-word-syntax-table
  20143. ;; Move to end of line in order to get the first paragraph within
  20144. ;; a plain list or a footnote definition.
  20145. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20146. ;; First check if point is in a blank line at the beginning of
  20147. ;; the buffer. In that case, ignore filling.
  20148. (cl-case (org-element-type element)
  20149. ;; Use major mode filling function is src blocks.
  20150. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20151. ;; Align Org tables, leave table.el tables as-is.
  20152. (table-row (org-table-align) t)
  20153. (table
  20154. (when (eq (org-element-property :type element) 'org)
  20155. (save-excursion
  20156. (goto-char (org-element-property :post-affiliated element))
  20157. (org-table-align)))
  20158. t)
  20159. (paragraph
  20160. ;; Paragraphs may contain `line-break' type objects.
  20161. (let ((beg (max (point-min)
  20162. (org-element-property :contents-begin element)))
  20163. (end (min (point-max)
  20164. (org-element-property :contents-end element))))
  20165. ;; Do nothing if point is at an affiliated keyword.
  20166. (if (< (line-end-position) beg) t
  20167. ;; Fill paragraph, taking line breaks into account.
  20168. (save-excursion
  20169. (goto-char beg)
  20170. (let ((cuts (list beg)))
  20171. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  20172. (when (eq 'line-break
  20173. (org-element-type
  20174. (save-excursion (backward-char)
  20175. (org-element-context))))
  20176. (push (point) cuts)))
  20177. (dolist (c (delq end cuts))
  20178. (fill-region-as-paragraph c end justify)
  20179. (setq end c))))
  20180. t)))
  20181. ;; Contents of `comment-block' type elements should be
  20182. ;; filled as plain text, but only if point is within block
  20183. ;; markers.
  20184. (comment-block
  20185. (let* ((case-fold-search t)
  20186. (beg (save-excursion
  20187. (goto-char (org-element-property :begin element))
  20188. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  20189. (forward-line)
  20190. (point)))
  20191. (end (save-excursion
  20192. (goto-char (org-element-property :end element))
  20193. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  20194. (line-beginning-position))))
  20195. (if (or (< (point) beg) (> (point) end)) t
  20196. (fill-region-as-paragraph
  20197. (save-excursion (end-of-line)
  20198. (re-search-backward "^[ \t]*$" beg 'move)
  20199. (line-beginning-position))
  20200. (save-excursion (beginning-of-line)
  20201. (re-search-forward "^[ \t]*$" end 'move)
  20202. (line-beginning-position))
  20203. justify))))
  20204. ;; Fill comments.
  20205. (comment
  20206. (let ((begin (org-element-property :post-affiliated element))
  20207. (end (org-element-property :end element)))
  20208. (when (and (>= (point) begin) (<= (point) end))
  20209. (let ((begin (save-excursion
  20210. (end-of-line)
  20211. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  20212. (progn (forward-line) (point))
  20213. begin)))
  20214. (end (save-excursion
  20215. (end-of-line)
  20216. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  20217. (1- (line-beginning-position))
  20218. (skip-chars-backward " \r\t\n")
  20219. (line-end-position)))))
  20220. ;; Do not fill comments when at a blank line.
  20221. (when (> end begin)
  20222. (let ((fill-prefix
  20223. (save-excursion
  20224. (beginning-of-line)
  20225. (looking-at "[ \t]*#")
  20226. (let ((comment-prefix (match-string 0)))
  20227. (goto-char (match-end 0))
  20228. (if (looking-at adaptive-fill-regexp)
  20229. (concat comment-prefix (match-string 0))
  20230. (concat comment-prefix " "))))))
  20231. (save-excursion
  20232. (fill-region-as-paragraph begin end justify))))))
  20233. t))
  20234. ;; Ignore every other element.
  20235. (otherwise t)))))
  20236. (defun org-fill-paragraph (&optional justify region)
  20237. "Fill element at point, when applicable.
  20238. This function only applies to comment blocks, comments, example
  20239. blocks and paragraphs. Also, as a special case, re-align table
  20240. when point is at one.
  20241. For convenience, when point is at a plain list, an item or
  20242. a footnote definition, try to fill the first paragraph within.
  20243. If JUSTIFY is non-nil (interactively, with prefix argument),
  20244. justify as well. If `sentence-end-double-space' is non-nil, then
  20245. period followed by one space does not end a sentence, so don't
  20246. break a line there. The variable `fill-column' controls the
  20247. width for filling.
  20248. The REGION argument is non-nil if called interactively; in that
  20249. case, if Transient Mark mode is enabled and the mark is active,
  20250. fill each of the elements in the active region, instead of just
  20251. filling the current element."
  20252. (interactive (progn
  20253. (barf-if-buffer-read-only)
  20254. (list (when current-prefix-arg 'full) t)))
  20255. (cond
  20256. ((and region transient-mark-mode mark-active
  20257. (not (eq (region-beginning) (region-end))))
  20258. (let ((origin (point-marker))
  20259. (start (region-beginning)))
  20260. (unwind-protect
  20261. (progn
  20262. (goto-char (region-end))
  20263. (while (> (point) start)
  20264. (org-backward-paragraph)
  20265. (org-fill-element justify)))
  20266. (goto-char origin)
  20267. (set-marker origin nil))))
  20268. (t (org-fill-element justify))))
  20269. (defun org-auto-fill-function ()
  20270. "Auto-fill function."
  20271. ;; Check if auto-filling is meaningful.
  20272. (let ((fc (current-fill-column)))
  20273. (when (and fc (> (current-column) fc))
  20274. (let* ((fill-prefix (org-adaptive-fill-function))
  20275. ;; Enforce empty fill prefix, if required. Otherwise, it
  20276. ;; will be computed again.
  20277. (adaptive-fill-mode (not (equal fill-prefix ""))))
  20278. (when fill-prefix (do-auto-fill))))))
  20279. (defun org-comment-line-break-function (&optional soft)
  20280. "Break line at point and indent, continuing comment if within one.
  20281. The inserted newline is marked hard if variable
  20282. `use-hard-newlines' is true, unless optional argument SOFT is
  20283. non-nil."
  20284. (if soft (insert-and-inherit ?\n) (newline 1))
  20285. (save-excursion (forward-char -1) (delete-horizontal-space))
  20286. (delete-horizontal-space)
  20287. (indent-to-left-margin)
  20288. (insert-before-markers-and-inherit fill-prefix))
  20289. ;;; Fixed Width Areas
  20290. (defun org-toggle-fixed-width ()
  20291. "Toggle fixed-width markup.
  20292. Add or remove fixed-width markup on current line, whenever it
  20293. makes sense. Return an error otherwise.
  20294. If a region is active and if it contains only fixed-width areas
  20295. or blank lines, remove all fixed-width markup in it. If the
  20296. region contains anything else, convert all non-fixed-width lines
  20297. to fixed-width ones.
  20298. Blank lines at the end of the region are ignored unless the
  20299. region only contains such lines."
  20300. (interactive)
  20301. (if (not (org-region-active-p))
  20302. ;; No region:
  20303. ;;
  20304. ;; Remove fixed width marker only in a fixed-with element.
  20305. ;;
  20306. ;; Add fixed width maker in paragraphs, in blank lines after
  20307. ;; elements or at the beginning of a headline or an inlinetask,
  20308. ;; and before any one-line elements (e.g., a clock).
  20309. (progn
  20310. (beginning-of-line)
  20311. (let* ((element (org-element-at-point))
  20312. (type (org-element-type element)))
  20313. (cond
  20314. ((and (eq type 'fixed-width)
  20315. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  20316. (replace-match
  20317. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  20318. ((and (memq type '(babel-call clock comment diary-sexp headline
  20319. horizontal-rule keyword paragraph
  20320. planning))
  20321. (<= (org-element-property :post-affiliated element) (point)))
  20322. (skip-chars-forward " \t")
  20323. (insert ": "))
  20324. ((and (looking-at-p "[ \t]*$")
  20325. (or (eq type 'inlinetask)
  20326. (save-excursion
  20327. (skip-chars-forward " \r\t\n")
  20328. (<= (org-element-property :end element) (point)))))
  20329. (delete-region (point) (line-end-position))
  20330. (org-indent-line)
  20331. (insert ": "))
  20332. (t (user-error "Cannot insert a fixed-width line here")))))
  20333. ;; Region active.
  20334. (let* ((begin (save-excursion
  20335. (goto-char (region-beginning))
  20336. (line-beginning-position)))
  20337. (end (copy-marker
  20338. (save-excursion
  20339. (goto-char (region-end))
  20340. (unless (eolp) (beginning-of-line))
  20341. (if (save-excursion (re-search-backward "\\S-" begin t))
  20342. (progn (skip-chars-backward " \r\t\n") (point))
  20343. (point)))))
  20344. (all-fixed-width-p
  20345. (catch 'not-all-p
  20346. (save-excursion
  20347. (goto-char begin)
  20348. (skip-chars-forward " \r\t\n")
  20349. (when (eobp) (throw 'not-all-p nil))
  20350. (while (< (point) end)
  20351. (let ((element (org-element-at-point)))
  20352. (if (eq (org-element-type element) 'fixed-width)
  20353. (goto-char (org-element-property :end element))
  20354. (throw 'not-all-p nil))))
  20355. t))))
  20356. (if all-fixed-width-p
  20357. (save-excursion
  20358. (goto-char begin)
  20359. (while (< (point) end)
  20360. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  20361. (replace-match
  20362. "" nil nil nil
  20363. (if (= (line-end-position) (match-end 0)) 0 1)))
  20364. (forward-line)))
  20365. (let ((min-ind (point-max)))
  20366. ;; Find minimum indentation across all lines.
  20367. (save-excursion
  20368. (goto-char begin)
  20369. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  20370. (setq min-ind 0)
  20371. (catch 'zerop
  20372. (while (< (point) end)
  20373. (unless (looking-at-p "[ \t]*$")
  20374. (let ((ind (current-indentation)))
  20375. (setq min-ind (min min-ind ind))
  20376. (when (zerop ind) (throw 'zerop t))))
  20377. (forward-line)))))
  20378. ;; Loop over all lines and add fixed-width markup everywhere
  20379. ;; but in fixed-width lines.
  20380. (save-excursion
  20381. (goto-char begin)
  20382. (while (< (point) end)
  20383. (cond
  20384. ((org-at-heading-p)
  20385. (insert ": ")
  20386. (forward-line)
  20387. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  20388. (insert ":")
  20389. (forward-line)))
  20390. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  20391. (let* ((element (org-element-at-point))
  20392. (element-end (org-element-property :end element)))
  20393. (if (eq (org-element-type element) 'fixed-width)
  20394. (progn (goto-char element-end)
  20395. (skip-chars-backward " \r\t\n")
  20396. (forward-line))
  20397. (let ((limit (min end element-end)))
  20398. (while (< (point) limit)
  20399. (org-move-to-column min-ind t)
  20400. (insert ": ")
  20401. (forward-line))))))
  20402. (t
  20403. (org-move-to-column min-ind t)
  20404. (insert ": ")
  20405. (forward-line)))))))
  20406. (set-marker end nil))))
  20407. ;;; Blocks
  20408. (defun org-block-map (function &optional start end)
  20409. "Call FUNCTION at the head of all source blocks in the current buffer.
  20410. Optional arguments START and END can be used to limit the range."
  20411. (let ((start (or start (point-min)))
  20412. (end (or end (point-max))))
  20413. (save-excursion
  20414. (goto-char start)
  20415. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  20416. (save-excursion
  20417. (save-match-data
  20418. (goto-char (match-beginning 0))
  20419. (funcall function)))))))
  20420. (defun org-next-block (arg &optional backward block-regexp)
  20421. "Jump to the next block.
  20422. With a prefix argument ARG, jump forward ARG many blocks.
  20423. When BACKWARD is non-nil, jump to the previous block.
  20424. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  20425. Match data is set according to this regexp when the function
  20426. returns.
  20427. Return point at beginning of the opening line of found block.
  20428. Throw an error if no block is found."
  20429. (interactive "p")
  20430. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  20431. (case-fold-search t)
  20432. (search-fn (if backward #'re-search-backward #'re-search-forward))
  20433. (count (or arg 1))
  20434. (origin (point))
  20435. last-element)
  20436. (if backward (beginning-of-line) (end-of-line))
  20437. (while (and (> count 0) (funcall search-fn re nil t))
  20438. (let ((element (save-excursion
  20439. (goto-char (match-beginning 0))
  20440. (save-match-data (org-element-at-point)))))
  20441. (when (and (memq (org-element-type element)
  20442. '(center-block comment-block dynamic-block
  20443. example-block export-block quote-block
  20444. special-block src-block verse-block))
  20445. (<= (match-beginning 0)
  20446. (org-element-property :post-affiliated element)))
  20447. (setq last-element element)
  20448. (cl-decf count))))
  20449. (if (= count 0)
  20450. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  20451. (save-match-data (org-show-context)))
  20452. (goto-char origin)
  20453. (user-error "No %s code blocks" (if backward "previous" "further")))))
  20454. (defun org-previous-block (arg &optional block-regexp)
  20455. "Jump to the previous block.
  20456. With a prefix argument ARG, jump backward ARG many source blocks.
  20457. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  20458. (interactive "p")
  20459. (org-next-block arg t block-regexp))
  20460. ;;; Comments
  20461. ;; Org comments syntax is quite complex. It requires the entire line
  20462. ;; to be just a comment. Also, even with the right syntax at the
  20463. ;; beginning of line, some elements (e.g., verse-block or
  20464. ;; example-block) don't accept comments. Usual Emacs comment commands
  20465. ;; cannot cope with those requirements. Therefore, Org replaces them.
  20466. ;; Org still relies on `comment-dwim', but cannot trust
  20467. ;; `comment-only-p'. So, `comment-region-function' and
  20468. ;; `uncomment-region-function' both point
  20469. ;; to`org-comment-or-uncomment-region'. Eventually,
  20470. ;; `org-insert-comment' takes care of insertion of comments at the
  20471. ;; beginning of line.
  20472. ;; `org-setup-comments-handling' install comments related variables
  20473. ;; during `org-mode' initialization.
  20474. (defun org-setup-comments-handling ()
  20475. (interactive)
  20476. (setq-local comment-use-syntax nil)
  20477. (setq-local comment-start "# ")
  20478. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  20479. (setq-local comment-insert-comment-function 'org-insert-comment)
  20480. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  20481. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  20482. (defun org-insert-comment ()
  20483. "Insert an empty comment above current line.
  20484. If the line is empty, insert comment at its beginning. When
  20485. point is within a source block, comment according to the related
  20486. major mode."
  20487. (if (let ((element (org-element-at-point)))
  20488. (and (eq (org-element-type element) 'src-block)
  20489. (< (save-excursion
  20490. (goto-char (org-element-property :post-affiliated element))
  20491. (line-end-position))
  20492. (point))
  20493. (> (save-excursion
  20494. (goto-char (org-element-property :end element))
  20495. (skip-chars-backward " \r\t\n")
  20496. (line-beginning-position))
  20497. (point))))
  20498. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  20499. (beginning-of-line)
  20500. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  20501. (open-line 1))
  20502. (org-indent-line)
  20503. (insert "# ")))
  20504. (defvar comment-empty-lines) ; From newcomment.el.
  20505. (defun org-comment-or-uncomment-region (beg end &rest _)
  20506. "Comment or uncomment each non-blank line in the region.
  20507. Uncomment each non-blank line between BEG and END if it only
  20508. contains commented lines. Otherwise, comment them. If region is
  20509. strictly within a source block, use appropriate comment syntax."
  20510. (if (let ((element (org-element-at-point)))
  20511. (and (eq (org-element-type element) 'src-block)
  20512. (< (save-excursion
  20513. (goto-char (org-element-property :post-affiliated element))
  20514. (line-end-position))
  20515. beg)
  20516. (>= (save-excursion
  20517. (goto-char (org-element-property :end element))
  20518. (skip-chars-backward " \r\t\n")
  20519. (line-beginning-position))
  20520. end)))
  20521. ;; Translate region boundaries for the Org buffer to the source
  20522. ;; buffer.
  20523. (let ((offset (- end beg)))
  20524. (save-excursion
  20525. (goto-char beg)
  20526. (org-babel-do-in-edit-buffer
  20527. (comment-or-uncomment-region (point) (+ offset (point))))))
  20528. (save-restriction
  20529. ;; Restrict region
  20530. (narrow-to-region (save-excursion (goto-char beg)
  20531. (skip-chars-forward " \r\t\n" end)
  20532. (line-beginning-position))
  20533. (save-excursion (goto-char end)
  20534. (skip-chars-backward " \r\t\n" beg)
  20535. (line-end-position)))
  20536. (let ((uncommentp
  20537. ;; UNCOMMENTP is non-nil when every non blank line between
  20538. ;; BEG and END is a comment.
  20539. (save-excursion
  20540. (goto-char (point-min))
  20541. (while (and (not (eobp))
  20542. (let ((element (org-element-at-point)))
  20543. (and (eq (org-element-type element) 'comment)
  20544. (goto-char (min (point-max)
  20545. (org-element-property
  20546. :end element)))))))
  20547. (eobp))))
  20548. (if uncommentp
  20549. ;; Only blank lines and comments in region: uncomment it.
  20550. (save-excursion
  20551. (goto-char (point-min))
  20552. (while (not (eobp))
  20553. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  20554. (replace-match "" nil nil nil 1))
  20555. (forward-line)))
  20556. ;; Comment each line in region.
  20557. (let ((min-indent (point-max)))
  20558. ;; First find the minimum indentation across all lines.
  20559. (save-excursion
  20560. (goto-char (point-min))
  20561. (while (and (not (eobp)) (not (zerop min-indent)))
  20562. (unless (looking-at "[ \t]*$")
  20563. (setq min-indent (min min-indent (current-indentation))))
  20564. (forward-line)))
  20565. ;; Then loop over all lines.
  20566. (save-excursion
  20567. (goto-char (point-min))
  20568. (while (not (eobp))
  20569. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  20570. ;; Don't get fooled by invisible text (e.g. link path)
  20571. ;; when moving to column MIN-INDENT.
  20572. (let ((buffer-invisibility-spec nil))
  20573. (org-move-to-column min-indent t))
  20574. (insert comment-start))
  20575. (forward-line)))))))))
  20576. (defun org-comment-dwim (_arg)
  20577. "Call the comment command you mean.
  20578. Call `org-toggle-comment' if on a heading, otherwise call
  20579. `comment-dwim', within a source edit buffer if needed."
  20580. (interactive "*P")
  20581. (cond ((org-at-heading-p)
  20582. (call-interactively #'org-toggle-comment))
  20583. ((org-in-src-block-p)
  20584. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  20585. (t (call-interactively #'comment-dwim))))
  20586. ;;; Timestamps API
  20587. ;; This section contains tools to operate on, or create, timestamp
  20588. ;; objects, as returned by, e.g. `org-element-context'.
  20589. (defun org-timestamp-from-string (s)
  20590. "Convert Org timestamp S, as a string, into a timestamp object.
  20591. Return nil if S is not a valid timestamp string."
  20592. (when (org-string-nw-p s)
  20593. (with-temp-buffer
  20594. (save-excursion (insert s))
  20595. (org-element-timestamp-parser))))
  20596. (defun org-timestamp-from-time (time &optional with-time inactive)
  20597. "Convert a time value into a timestamp object.
  20598. TIME is an Emacs internal time representation, as returned, e.g.,
  20599. by `current-time'.
  20600. When optional argument WITH-TIME is non-nil, return a timestamp
  20601. object with a time part, i.e., with hours and minutes.
  20602. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  20603. return an active timestamp."
  20604. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  20605. (org-element-create 'timestamp
  20606. (list :type (if inactive 'inactive 'active)
  20607. :year-start year
  20608. :month-start month
  20609. :day-start day
  20610. :hour-start (and with-time hour)
  20611. :minute-start (and with-time minute)))))
  20612. (defun org-timestamp-to-time (timestamp &optional end)
  20613. "Convert TIMESTAMP object into an Emacs internal time value.
  20614. Use end of date range or time range when END is non-nil.
  20615. Otherwise, use its start."
  20616. (apply #'encode-time
  20617. (cons 0
  20618. (mapcar
  20619. (lambda (prop) (or (org-element-property prop timestamp) 0))
  20620. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  20621. '(:minute-start :hour-start :day-start :month-start
  20622. :year-start))))))
  20623. (defun org-timestamp-has-time-p (timestamp)
  20624. "Non-nil when TIMESTAMP has a time specified."
  20625. (org-element-property :hour-start timestamp))
  20626. (defun org-timestamp-format (timestamp format &optional end utc)
  20627. "Format a TIMESTAMP object into a string.
  20628. FORMAT is a format specifier to be passed to
  20629. `format-time-string'.
  20630. When optional argument END is non-nil, use end of date-range or
  20631. time-range, if possible.
  20632. When optional argument UTC is non-nil, time is be expressed as
  20633. Universal Time."
  20634. (format-time-string format (org-timestamp-to-time timestamp end)
  20635. (and utc t)))
  20636. (defun org-timestamp-split-range (timestamp &optional end)
  20637. "Extract a TIMESTAMP object from a date or time range.
  20638. END, when non-nil, means extract the end of the range.
  20639. Otherwise, extract its start.
  20640. Return a new timestamp object."
  20641. (let ((type (org-element-property :type timestamp)))
  20642. (if (memq type '(active inactive diary)) timestamp
  20643. (let ((split-ts (org-element-copy timestamp)))
  20644. ;; Set new type.
  20645. (org-element-put-property
  20646. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  20647. ;; Copy start properties over end properties if END is
  20648. ;; non-nil. Otherwise, copy end properties over `start' ones.
  20649. (let ((p-alist '((:minute-start . :minute-end)
  20650. (:hour-start . :hour-end)
  20651. (:day-start . :day-end)
  20652. (:month-start . :month-end)
  20653. (:year-start . :year-end))))
  20654. (dolist (p-cell p-alist)
  20655. (org-element-put-property
  20656. split-ts
  20657. (funcall (if end #'car #'cdr) p-cell)
  20658. (org-element-property
  20659. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  20660. ;; Eventually refresh `:raw-value'.
  20661. (org-element-put-property split-ts :raw-value nil)
  20662. (org-element-put-property
  20663. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  20664. (defun org-timestamp-translate (timestamp &optional boundary)
  20665. "Translate TIMESTAMP object to custom format.
  20666. Format string is defined in `org-time-stamp-custom-formats',
  20667. which see.
  20668. When optional argument BOUNDARY is non-nil, it is either the
  20669. symbol `start' or `end'. In this case, only translate the
  20670. starting or ending part of TIMESTAMP if it is a date or time
  20671. range. Otherwise, translate both parts.
  20672. Return timestamp as-is if `org-display-custom-times' is nil or if
  20673. it has a `diary' type."
  20674. (let ((type (org-element-property :type timestamp)))
  20675. (if (or (not org-display-custom-times) (eq type 'diary))
  20676. (org-element-interpret-data timestamp)
  20677. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  20678. org-time-stamp-custom-formats)))
  20679. (if (and (not boundary) (memq type '(active-range inactive-range)))
  20680. (concat (org-timestamp-format timestamp fmt)
  20681. "--"
  20682. (org-timestamp-format timestamp fmt t))
  20683. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  20684. ;;; Other stuff
  20685. (defvar reftex-docstruct-symbol)
  20686. (defvar org--rds)
  20687. (defun org-reftex-citation ()
  20688. "Use reftex-citation to insert a citation into the buffer.
  20689. This looks for a line like
  20690. #+BIBLIOGRAPHY: foo plain option:-d
  20691. and derives from it that foo.bib is the bibliography file relevant
  20692. for this document. It then installs the necessary environment for RefTeX
  20693. to work in this buffer and calls `reftex-citation' to insert a citation
  20694. into the buffer.
  20695. Export of such citations to both LaTeX and HTML is handled by the contributed
  20696. package ox-bibtex by Taru Karttunen."
  20697. (interactive)
  20698. (let ((reftex-docstruct-symbol 'org--rds)
  20699. org--rds bib)
  20700. (org-with-wide-buffer
  20701. (let ((case-fold-search t)
  20702. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  20703. (if (not (save-excursion
  20704. (or (re-search-forward re nil t)
  20705. (re-search-backward re nil t))))
  20706. (user-error "No bibliography defined in file")
  20707. (setq bib (concat (match-string 1) ".bib")
  20708. org--rds (list (list 'bib bib))))))
  20709. (call-interactively 'reftex-citation)))
  20710. ;;;; Functions extending outline functionality
  20711. (defun org-beginning-of-line (&optional n)
  20712. "Go to the beginning of the current visible line.
  20713. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20714. symbol `reversed', on the first attempt move to where the
  20715. headline text starts, and only move to beginning of line when the
  20716. cursor is already before the start of the text of the headline.
  20717. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  20718. start of the text on the second attempt.
  20719. With argument N not nil or 1, move forward N - 1 lines first."
  20720. (interactive "^p")
  20721. (let ((origin (point))
  20722. (special (pcase org-special-ctrl-a/e
  20723. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  20724. deactivate-mark)
  20725. ;; First move to a visible line.
  20726. (if (bound-and-true-p visual-line-mode)
  20727. (beginning-of-visual-line n)
  20728. (move-beginning-of-line n)
  20729. ;; `move-beginning-of-line' may leave point after invisible
  20730. ;; characters if line starts with such of these (e.g., with
  20731. ;; a link at column 0). Really move to the beginning of the
  20732. ;; current visible line.
  20733. (beginning-of-line))
  20734. (cond
  20735. ;; No special behavior. Point is already at the beginning of
  20736. ;; a line, logical or visual.
  20737. ((not special))
  20738. ;; `beginning-of-visual-line' left point before logical beginning
  20739. ;; of line: point is at the beginning of a visual line. Bail
  20740. ;; out.
  20741. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  20742. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  20743. ;; At a headline, special position is before the title, but
  20744. ;; after any TODO keyword or priority cookie.
  20745. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  20746. (line-end-position)))
  20747. (bol (point)))
  20748. (if (eq special 'reversed)
  20749. (when (and (= origin bol) (eq last-command this-command))
  20750. (goto-char refpos))
  20751. (when (or (> origin refpos) (= origin bol))
  20752. (goto-char refpos)))))
  20753. ((and (looking-at org-list-full-item-re)
  20754. (memq (org-element-type (save-match-data (org-element-at-point)))
  20755. '(item plain-list)))
  20756. ;; Set special position at first white space character after
  20757. ;; bullet, and check-box, if any.
  20758. (let ((after-bullet
  20759. (let ((box (match-end 3)))
  20760. (cond ((not box) (match-end 1))
  20761. ((eq (char-after box) ?\s) (1+ box))
  20762. (t box)))))
  20763. (if (eq special 'reversed)
  20764. (when (and (= (point) origin) (eq last-command this-command))
  20765. (goto-char after-bullet))
  20766. (when (or (> origin after-bullet) (= (point) origin))
  20767. (goto-char after-bullet)))))
  20768. ;; No special context. Point is already at beginning of line.
  20769. (t nil))))
  20770. (defun org-end-of-line (&optional n)
  20771. "Go to the end of the line, but before ellipsis, if any.
  20772. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20773. symbol `reversed', ignore tags on the first attempt, and only
  20774. move to after the tags when the cursor is already beyond the end
  20775. of the headline.
  20776. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  20777. on the second attempt.
  20778. With argument N not nil or 1, move forward N - 1 lines first."
  20779. (interactive "^p")
  20780. (let ((origin (point))
  20781. (special (pcase org-special-ctrl-a/e
  20782. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  20783. deactivate-mark)
  20784. ;; First move to a visible line.
  20785. (if (bound-and-true-p visual-line-mode)
  20786. (beginning-of-visual-line n)
  20787. (move-beginning-of-line n))
  20788. (cond
  20789. ;; At a headline, with tags.
  20790. ((and special
  20791. (save-excursion
  20792. (beginning-of-line)
  20793. (let ((case-fold-search nil))
  20794. (looking-at org-complex-heading-regexp)))
  20795. (match-end 5))
  20796. (let ((tags (save-excursion
  20797. (goto-char (match-beginning 5))
  20798. (skip-chars-backward " \t")
  20799. (point)))
  20800. (visual-end (and (bound-and-true-p visual-line-mode)
  20801. (save-excursion
  20802. (end-of-visual-line)
  20803. (point)))))
  20804. ;; If `end-of-visual-line' brings us before end of line or
  20805. ;; even tags, i.e., the headline spans over multiple visual
  20806. ;; lines, move there.
  20807. (cond ((and visual-end
  20808. (< visual-end tags)
  20809. (<= origin visual-end))
  20810. (goto-char visual-end))
  20811. ((eq special 'reversed)
  20812. (if (and (= origin (line-end-position))
  20813. (eq this-command last-command))
  20814. (goto-char tags)
  20815. (end-of-line)))
  20816. (t
  20817. (if (or (< origin tags) (= origin (line-end-position)))
  20818. (goto-char tags)
  20819. (end-of-line))))))
  20820. ((bound-and-true-p visual-line-mode)
  20821. (let ((bol (line-beginning-position)))
  20822. (end-of-visual-line)
  20823. ;; If `end-of-visual-line' gets us past the ellipsis at the
  20824. ;; end of a line, backtrack and use `end-of-line' instead.
  20825. (when (/= bol (line-beginning-position))
  20826. (goto-char bol)
  20827. (end-of-line))))
  20828. (t (end-of-line)))))
  20829. (defun org-backward-sentence (&optional _arg)
  20830. "Go to beginning of sentence, or beginning of table field.
  20831. This will call `backward-sentence' or `org-table-beginning-of-field',
  20832. depending on context."
  20833. (interactive)
  20834. (let* ((element (org-element-at-point))
  20835. (contents-begin (org-element-property :contents-begin element))
  20836. (table (org-element-lineage element '(table) t)))
  20837. (if (and table
  20838. (> (point) contents-begin)
  20839. (<= (point) (org-element-property :contents-end table)))
  20840. (call-interactively #'org-table-beginning-of-field)
  20841. (save-restriction
  20842. (when (and contents-begin
  20843. (< (point-min) contents-begin)
  20844. (> (point) contents-begin))
  20845. (narrow-to-region contents-begin
  20846. (org-element-property :contents-end element)))
  20847. (call-interactively #'backward-sentence)))))
  20848. (defun org-forward-sentence (&optional _arg)
  20849. "Go to end of sentence, or end of table field.
  20850. This will call `forward-sentence' or `org-table-end-of-field',
  20851. depending on context."
  20852. (interactive)
  20853. (if (and (org-at-heading-p)
  20854. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  20855. (save-restriction
  20856. (narrow-to-region (line-beginning-position) (line-end-position))
  20857. (call-interactively #'forward-sentence))
  20858. (let* ((element (org-element-at-point))
  20859. (contents-end (org-element-property :contents-end element))
  20860. (table (org-element-lineage element '(table) t)))
  20861. (if (and table
  20862. (>= (point) (org-element-property :contents-begin table))
  20863. (< (point) contents-end))
  20864. (call-interactively #'org-table-end-of-field)
  20865. (save-restriction
  20866. (when (and contents-end
  20867. (> (point-max) contents-end)
  20868. ;; Skip blank lines between elements.
  20869. (< (org-element-property :end element)
  20870. (save-excursion (goto-char contents-end)
  20871. (skip-chars-forward " \r\t\n"))))
  20872. (narrow-to-region (org-element-property :contents-begin element)
  20873. contents-end))
  20874. ;; End of heading is considered as the end of a sentence.
  20875. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  20876. (call-interactively #'forward-sentence)))))))
  20877. (defun org-kill-line (&optional _arg)
  20878. "Kill line, to tags or end of line."
  20879. (interactive)
  20880. (cond
  20881. ((or (not org-special-ctrl-k)
  20882. (bolp)
  20883. (not (org-at-heading-p)))
  20884. (when (and (get-char-property (line-end-position) 'invisible)
  20885. org-ctrl-k-protect-subtree
  20886. (or (eq org-ctrl-k-protect-subtree 'error)
  20887. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  20888. (user-error
  20889. (substitute-command-keys
  20890. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  20891. (call-interactively
  20892. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  20893. ((looking-at org-tag-line-re)
  20894. (let ((end (save-excursion
  20895. (goto-char (match-beginning 1))
  20896. (skip-chars-backward " \t"))))
  20897. (if (<= end (point)) ;on tags part
  20898. (kill-region (point) (line-end-position))
  20899. (kill-region (point) end)))
  20900. (org-align-tags))
  20901. (t (kill-region (point) (line-end-position)))))
  20902. (defun org-yank (&optional arg)
  20903. "Yank. If the kill is a subtree, treat it specially.
  20904. This command will look at the current kill and check if is a single
  20905. subtree, or a series of subtrees[1]. If it passes the test, and if the
  20906. cursor is at the beginning of a line or after the stars of a currently
  20907. empty headline, then the yank is handled specially. How exactly depends
  20908. on the value of the following variables.
  20909. `org-yank-folded-subtrees'
  20910. By default, this variable is non-nil, which results in
  20911. subtree(s) being folded after insertion, except if doing so
  20912. would swallow text after the yanked text.
  20913. `org-yank-adjusted-subtrees'
  20914. When non-nil (the default value is nil), the subtree will be
  20915. promoted or demoted in order to fit into the local outline tree
  20916. structure, which means that the level will be adjusted so that it
  20917. becomes the smaller one of the two *visible* surrounding headings.
  20918. Any prefix to this command will cause `yank' to be called directly with
  20919. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  20920. will just
  20921. plainly yank the text as it is.
  20922. \[1] The test checks if the first non-white line is a heading
  20923. and if there are no other headings with fewer stars."
  20924. (interactive "P")
  20925. (org-yank-generic 'yank arg))
  20926. (defun org-yank-generic (command arg)
  20927. "Perform some yank-like command.
  20928. This function implements the behavior described in the `org-yank'
  20929. documentation. However, it has been generalized to work for any
  20930. interactive command with similar behavior."
  20931. ;; pretend to be command COMMAND
  20932. (setq this-command command)
  20933. (if arg
  20934. (call-interactively command)
  20935. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  20936. (and (org-kill-is-subtree-p)
  20937. (or (bolp)
  20938. (and (looking-at "[ \t]*$")
  20939. (string-match
  20940. "\\`\\*+\\'"
  20941. (buffer-substring (point-at-bol) (point)))))))
  20942. swallowp)
  20943. (cond
  20944. ((and subtreep org-yank-folded-subtrees)
  20945. (let ((beg (point))
  20946. end)
  20947. (if (and subtreep org-yank-adjusted-subtrees)
  20948. (org-paste-subtree nil nil 'for-yank)
  20949. (call-interactively command))
  20950. (setq end (point))
  20951. (goto-char beg)
  20952. (when (and (bolp) subtreep
  20953. (not (setq swallowp
  20954. (org-yank-folding-would-swallow-text beg end))))
  20955. (org-with-limited-levels
  20956. (or (looking-at org-outline-regexp)
  20957. (re-search-forward org-outline-regexp-bol end t))
  20958. (while (and (< (point) end) (looking-at org-outline-regexp))
  20959. (outline-hide-subtree)
  20960. (org-cycle-show-empty-lines 'folded)
  20961. (condition-case nil
  20962. (outline-forward-same-level 1)
  20963. (error (goto-char end))))))
  20964. (when swallowp
  20965. (message
  20966. "Inserted text not folded because that would swallow text"))
  20967. (goto-char end)
  20968. (skip-chars-forward " \t\n\r")
  20969. (beginning-of-line 1)
  20970. (push-mark beg 'nomsg)))
  20971. ((and subtreep org-yank-adjusted-subtrees)
  20972. (let ((beg (point-at-bol)))
  20973. (org-paste-subtree nil nil 'for-yank)
  20974. (push-mark beg 'nomsg)))
  20975. (t
  20976. (call-interactively command))))))
  20977. (defun org-yank-folding-would-swallow-text (beg end)
  20978. "Would hide-subtree at BEG swallow any text after END?"
  20979. (let (level)
  20980. (org-with-limited-levels
  20981. (save-excursion
  20982. (goto-char beg)
  20983. (when (or (looking-at org-outline-regexp)
  20984. (re-search-forward org-outline-regexp-bol end t))
  20985. (setq level (org-outline-level)))
  20986. (goto-char end)
  20987. (skip-chars-forward " \t\r\n\v\f")
  20988. (not (or (eobp)
  20989. (and (bolp) (looking-at-p org-outline-regexp)
  20990. (<= (org-outline-level) level))))))))
  20991. (defun org-back-to-heading (&optional invisible-ok)
  20992. "Call `outline-back-to-heading', but provide a better error message."
  20993. (condition-case nil
  20994. (outline-back-to-heading invisible-ok)
  20995. (error (error "Before first headline at position %d in buffer %s"
  20996. (point) (current-buffer)))))
  20997. (defun org-before-first-heading-p ()
  20998. "Before first heading?"
  20999. (save-excursion
  21000. (end-of-line)
  21001. (null (re-search-backward org-outline-regexp-bol nil t))))
  21002. (defun org-at-heading-p (&optional ignored)
  21003. (outline-on-heading-p t))
  21004. (defun org-in-commented-heading-p (&optional no-inheritance)
  21005. "Non-nil if point is under a commented heading.
  21006. This function also checks ancestors of the current headline,
  21007. unless optional argument NO-INHERITANCE is non-nil."
  21008. (cond
  21009. ((org-before-first-heading-p) nil)
  21010. ((let ((headline (nth 4 (org-heading-components))))
  21011. (and headline
  21012. (let ((case-fold-search nil))
  21013. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  21014. headline)))))
  21015. (no-inheritance nil)
  21016. (t
  21017. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21018. (defun org-at-comment-p nil
  21019. "Is cursor in a commented line?"
  21020. (save-excursion
  21021. (save-match-data
  21022. (beginning-of-line)
  21023. (looking-at "^[ \t]*# "))))
  21024. (defun org-at-drawer-p nil
  21025. "Is cursor at a drawer keyword?"
  21026. (save-excursion
  21027. (move-beginning-of-line 1)
  21028. (looking-at org-drawer-regexp)))
  21029. (defun org-at-block-p nil
  21030. "Is cursor at a block keyword?"
  21031. (save-excursion
  21032. (move-beginning-of-line 1)
  21033. (looking-at org-block-regexp)))
  21034. (defun org-point-at-end-of-empty-headline ()
  21035. "If point is at the end of an empty headline, return t, else nil.
  21036. If the heading only contains a TODO keyword, it is still still considered
  21037. empty."
  21038. (let ((case-fold-search nil))
  21039. (and (looking-at "[ \t]*$")
  21040. org-todo-line-regexp
  21041. (save-excursion
  21042. (beginning-of-line)
  21043. (looking-at org-todo-line-regexp)
  21044. (string= (match-string 3) "")))))
  21045. (defun org-at-heading-or-item-p ()
  21046. (or (org-at-heading-p) (org-at-item-p)))
  21047. (defun org-at-target-p ()
  21048. (or (org-in-regexp org-radio-target-regexp)
  21049. (org-in-regexp org-target-regexp)))
  21050. (defun org-up-heading-all (arg)
  21051. "Move to the heading line of which the present line is a subheading.
  21052. This function considers both visible and invisible heading lines.
  21053. With argument, move up ARG levels."
  21054. (outline-up-heading arg t))
  21055. (defun org-up-heading-safe ()
  21056. "Move to the heading line of which the present line is a subheading.
  21057. This version will not throw an error. It will return the level of the
  21058. headline found, or nil if no higher level is found.
  21059. Also, this function will be a lot faster than `outline-up-heading',
  21060. because it relies on stars being the outline starters. This can really
  21061. make a significant difference in outlines with very many siblings."
  21062. (when (ignore-errors (org-back-to-heading t))
  21063. (let ((level-up (1- (funcall outline-level))))
  21064. (and (> level-up 0)
  21065. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21066. (funcall outline-level)))))
  21067. (defun org-first-sibling-p ()
  21068. "Is this heading the first child of its parents?"
  21069. (interactive)
  21070. (let ((re org-outline-regexp-bol)
  21071. level l)
  21072. (unless (org-at-heading-p t)
  21073. (user-error "Not at a heading"))
  21074. (setq level (funcall outline-level))
  21075. (save-excursion
  21076. (if (not (re-search-backward re nil t))
  21077. t
  21078. (setq l (funcall outline-level))
  21079. (< l level)))))
  21080. (defun org-goto-sibling (&optional previous)
  21081. "Goto the next sibling, even if it is invisible.
  21082. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21083. when a sibling was found. When none is found, return nil and don't
  21084. move point."
  21085. (let ((fun (if previous 're-search-backward 're-search-forward))
  21086. (pos (point))
  21087. (re org-outline-regexp-bol)
  21088. level l)
  21089. (when (ignore-errors (org-back-to-heading t))
  21090. (setq level (funcall outline-level))
  21091. (catch 'exit
  21092. (or previous (forward-char 1))
  21093. (while (funcall fun re nil t)
  21094. (setq l (funcall outline-level))
  21095. (when (< l level) (goto-char pos) (throw 'exit nil))
  21096. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21097. (goto-char pos)
  21098. nil))))
  21099. (defun org-show-siblings ()
  21100. "Show all siblings of the current headline."
  21101. (save-excursion
  21102. (while (org-goto-sibling) (org-flag-heading nil)))
  21103. (save-excursion
  21104. (while (org-goto-sibling 'previous)
  21105. (org-flag-heading nil))))
  21106. (defun org-goto-first-child ()
  21107. "Goto the first child, even if it is invisible.
  21108. Return t when a child was found. Otherwise don't move point and
  21109. return nil."
  21110. (let (level (pos (point)) (re org-outline-regexp-bol))
  21111. (when (ignore-errors (org-back-to-heading t))
  21112. (setq level (outline-level))
  21113. (forward-char 1)
  21114. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21115. (progn (goto-char (match-beginning 0)) t)
  21116. (goto-char pos) nil))))
  21117. (defun org-show-hidden-entry ()
  21118. "Show an entry where even the heading is hidden."
  21119. (save-excursion
  21120. (org-show-entry)))
  21121. (defun org-flag-heading (flag &optional entry)
  21122. "Flag the current heading. FLAG non-nil means make invisible.
  21123. When ENTRY is non-nil, show the entire entry."
  21124. (save-excursion
  21125. (org-back-to-heading t)
  21126. ;; Check if we should show the entire entry
  21127. (if (not entry)
  21128. (org-flag-region
  21129. (line-end-position 0) (line-end-position) flag 'outline)
  21130. (org-show-entry)
  21131. (save-excursion
  21132. (and (outline-next-heading)
  21133. (org-flag-heading nil))))))
  21134. (defun org-get-next-sibling ()
  21135. "Move to next heading of the same level, and return point.
  21136. If there is no such heading, return nil.
  21137. This is like outline-next-sibling, but invisible headings are ok."
  21138. (let ((level (funcall outline-level)))
  21139. (outline-next-heading)
  21140. (while (and (not (eobp)) (> (funcall outline-level) level))
  21141. (outline-next-heading))
  21142. (unless (or (eobp) (< (funcall outline-level) level))
  21143. (point))))
  21144. (defun org-get-last-sibling ()
  21145. "Move to previous heading of the same level, and return point.
  21146. If there is no such heading, return nil."
  21147. (let ((opoint (point))
  21148. (level (funcall outline-level)))
  21149. (outline-previous-heading)
  21150. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21151. (while (and (> (funcall outline-level) level)
  21152. (not (bobp)))
  21153. (outline-previous-heading))
  21154. (unless (< (funcall outline-level) level)
  21155. (point)))))
  21156. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21157. "Goto to the end of a subtree."
  21158. ;; This contains an exact copy of the original function, but it uses
  21159. ;; `org-back-to-heading', to make it work also in invisible
  21160. ;; trees. And is uses an invisible-ok argument.
  21161. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21162. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21163. ;; with many children and grandchildren etc, this can be much faster
  21164. ;; than the outline version.
  21165. (org-back-to-heading invisible-ok)
  21166. (let ((first t)
  21167. (level (funcall outline-level)))
  21168. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21169. ;; A true heading (not a plain list item), in Org
  21170. ;; This means we can easily find the end by looking
  21171. ;; only for the right number of stars. Using a regexp to do
  21172. ;; this is so much faster than using a Lisp loop.
  21173. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21174. (forward-char 1)
  21175. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21176. ;; something else, do it the slow way
  21177. (while (and (not (eobp))
  21178. (or first (> (funcall outline-level) level)))
  21179. (setq first nil)
  21180. (outline-next-heading)))
  21181. (unless to-heading
  21182. (when (memq (preceding-char) '(?\n ?\^M))
  21183. ;; Go to end of line before heading
  21184. (forward-char -1)
  21185. (when (memq (preceding-char) '(?\n ?\^M))
  21186. ;; leave blank line before heading
  21187. (forward-char -1)))))
  21188. (point))
  21189. (defun org-end-of-meta-data (&optional full)
  21190. "Skip planning line and properties drawer in current entry.
  21191. When optional argument FULL is non-nil, also skip empty lines,
  21192. clocking lines and regular drawers at the beginning of the
  21193. entry."
  21194. (org-back-to-heading t)
  21195. (forward-line)
  21196. (when (looking-at-p org-planning-line-re) (forward-line))
  21197. (when (looking-at org-property-drawer-re)
  21198. (goto-char (match-end 0))
  21199. (forward-line))
  21200. (when (and full (not (org-at-heading-p)))
  21201. (catch 'exit
  21202. (let ((end (save-excursion (outline-next-heading) (point)))
  21203. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21204. (while (not (eobp))
  21205. (cond ((looking-at-p org-drawer-regexp)
  21206. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21207. (forward-line)
  21208. (throw 'exit t)))
  21209. ((looking-at-p re) (forward-line))
  21210. (t (throw 'exit t))))))))
  21211. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21212. "Move forward to the ARG'th subheading at same level as this one.
  21213. Stop at the first and last subheadings of a superior heading.
  21214. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21215. non-nil it will also look at invisible ones."
  21216. (interactive "p")
  21217. (let ((backward? (and arg (< arg 0))))
  21218. (if (org-before-first-heading-p)
  21219. (if backward? (goto-char (point-min)) (outline-next-heading))
  21220. (org-back-to-heading invisible-ok)
  21221. (unless backward? (end-of-line)) ;do not match current headline
  21222. (let ((level (- (match-end 0) (match-beginning 0) 1))
  21223. (f (if backward? #'re-search-backward #'re-search-forward))
  21224. (count (if arg (abs arg) 1))
  21225. (result (point)))
  21226. (while (and (> count 0)
  21227. (funcall f org-outline-regexp-bol nil 'move))
  21228. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21229. (cond ((< l level) (setq count 0))
  21230. ((and (= l level)
  21231. (or invisible-ok
  21232. (not (org-invisible-p
  21233. (line-beginning-position)))))
  21234. (cl-decf count)
  21235. (when (= l level) (setq result (point)))))))
  21236. (goto-char result))
  21237. (beginning-of-line))))
  21238. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  21239. "Move backward to the ARG'th subheading at same level as this one.
  21240. Stop at the first and last subheadings of a superior heading."
  21241. (interactive "p")
  21242. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  21243. (defun org-next-visible-heading (arg)
  21244. "Move to the next visible heading.
  21245. This function wraps `outline-next-visible-heading' with
  21246. `org-with-limited-levels' in order to skip over inline tasks and
  21247. respect customization of `org-odd-levels-only'."
  21248. (interactive "p")
  21249. (org-with-limited-levels
  21250. (outline-next-visible-heading arg)))
  21251. (defun org-previous-visible-heading (arg)
  21252. "Move to the previous visible heading.
  21253. This function wraps `outline-previous-visible-heading' with
  21254. `org-with-limited-levels' in order to skip over inline tasks and
  21255. respect customization of `org-odd-levels-only'."
  21256. (interactive "p")
  21257. (org-with-limited-levels
  21258. (outline-previous-visible-heading arg)))
  21259. (defun org-forward-paragraph ()
  21260. "Move forward to beginning of next paragraph or equivalent.
  21261. The function moves point to the beginning of the next visible
  21262. structural element, which can be a paragraph, a table, a list
  21263. item, etc. It also provides some special moves for convenience:
  21264. - On an affiliated keyword, jump to the beginning of the
  21265. relative element.
  21266. - On an item or a footnote definition, move to the second
  21267. element inside, if any.
  21268. - On a table or a property drawer, jump after it.
  21269. - On a verse or source block, stop after blank lines."
  21270. (interactive)
  21271. (unless (eobp)
  21272. (let* ((deactivate-mark nil)
  21273. (element (org-element-at-point))
  21274. (type (org-element-type element))
  21275. (post-affiliated (org-element-property :post-affiliated element))
  21276. (contents-begin (org-element-property :contents-begin element))
  21277. (contents-end (org-element-property :contents-end element))
  21278. (end (let ((end (org-element-property :end element)) (parent element))
  21279. (while (and (setq parent (org-element-property :parent parent))
  21280. (= (org-element-property :contents-end parent) end))
  21281. (setq end (org-element-property :end parent)))
  21282. end)))
  21283. (cond ((not element)
  21284. (skip-chars-forward " \r\t\n")
  21285. (or (eobp) (beginning-of-line)))
  21286. ;; On affiliated keywords, move to element's beginning.
  21287. ((< (point) post-affiliated)
  21288. (goto-char post-affiliated))
  21289. ;; At a table row, move to the end of the table. Similarly,
  21290. ;; at a node property, move to the end of the property
  21291. ;; drawer.
  21292. ((memq type '(node-property table-row))
  21293. (goto-char (org-element-property
  21294. :end (org-element-property :parent element))))
  21295. ((memq type '(property-drawer table)) (goto-char end))
  21296. ;; Consider blank lines as separators in verse and source
  21297. ;; blocks to ease editing.
  21298. ((memq type '(src-block verse-block))
  21299. (when (eq type 'src-block)
  21300. (setq contents-end
  21301. (save-excursion (goto-char end)
  21302. (skip-chars-backward " \r\t\n")
  21303. (line-beginning-position))))
  21304. (beginning-of-line)
  21305. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  21306. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  21307. (goto-char end)
  21308. (skip-chars-forward " \r\t\n")
  21309. (if (= (point) contents-end) (goto-char end)
  21310. (beginning-of-line))))
  21311. ;; With no contents, just skip element.
  21312. ((not contents-begin) (goto-char end))
  21313. ;; If contents are invisible, skip the element altogether.
  21314. ((org-invisible-p (line-end-position))
  21315. (cl-case type
  21316. (headline
  21317. (org-with-limited-levels (outline-next-visible-heading 1)))
  21318. ;; At a plain list, make sure we move to the next item
  21319. ;; instead of skipping the whole list.
  21320. (plain-list (forward-char)
  21321. (org-forward-paragraph))
  21322. (otherwise (goto-char end))))
  21323. ((>= (point) contents-end) (goto-char end))
  21324. ((>= (point) contents-begin)
  21325. ;; This can only happen on paragraphs and plain lists.
  21326. (cl-case type
  21327. (paragraph (goto-char end))
  21328. ;; At a plain list, try to move to second element in
  21329. ;; first item, if possible.
  21330. (plain-list (end-of-line)
  21331. (org-forward-paragraph))))
  21332. ;; When contents start on the middle of a line (e.g. in
  21333. ;; items and footnote definitions), try to reach first
  21334. ;; element starting after current line.
  21335. ((> (line-end-position) contents-begin)
  21336. (end-of-line)
  21337. (org-forward-paragraph))
  21338. (t (goto-char contents-begin))))))
  21339. (defun org-backward-paragraph ()
  21340. "Move backward to start of previous paragraph or equivalent.
  21341. The function moves point to the beginning of the current
  21342. structural element, which can be a paragraph, a table, a list
  21343. item, etc., or to the beginning of the previous visible one if
  21344. point is already there. It also provides some special moves for
  21345. convenience:
  21346. - On an affiliated keyword, jump to the first one.
  21347. - On a table or a property drawer, move to its beginning.
  21348. - On comment, example, export, src and verse blocks, stop
  21349. before blank lines."
  21350. (interactive)
  21351. (unless (bobp)
  21352. (let* ((deactivate-mark nil)
  21353. (element (org-element-at-point))
  21354. (type (org-element-type element))
  21355. (contents-end (org-element-property :contents-end element))
  21356. (post-affiliated (org-element-property :post-affiliated element))
  21357. (begin (org-element-property :begin element))
  21358. (special? ;blocks handled specially
  21359. (memq type '(comment-block example-block export-block src-block
  21360. verse-block)))
  21361. (contents-begin
  21362. (if special?
  21363. ;; These types have no proper contents. Fake line
  21364. ;; below the block opening line as contents beginning.
  21365. (save-excursion (goto-char begin) (line-beginning-position 2))
  21366. (org-element-property :contents-begin element))))
  21367. (cond
  21368. ((not element) (goto-char (point-min)))
  21369. ((= (point) begin)
  21370. (backward-char)
  21371. (org-backward-paragraph))
  21372. ((<= (point) post-affiliated) (goto-char begin))
  21373. ;; Special behavior: on a table or a property drawer, move to
  21374. ;; its beginning.
  21375. ((memq type '(node-property table-row))
  21376. (goto-char (org-element-property
  21377. :post-affiliated (org-element-property :parent element))))
  21378. (special?
  21379. (if (<= (point) contents-begin) (goto-char post-affiliated)
  21380. ;; Inside a verse block, see blank lines as paragraph
  21381. ;; separators.
  21382. (let ((origin (point)))
  21383. (skip-chars-backward " \r\t\n" contents-begin)
  21384. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  21385. (skip-chars-forward " \r\t\n" origin)
  21386. (if (= (point) origin) (goto-char contents-begin)
  21387. (beginning-of-line))))))
  21388. ((eq type 'paragraph) (goto-char contents-begin)
  21389. ;; When at first paragraph in an item or a footnote definition,
  21390. ;; move directly to beginning of line.
  21391. (let ((parent-contents
  21392. (org-element-property
  21393. :contents-begin (org-element-property :parent element))))
  21394. (when (and parent-contents (= parent-contents contents-begin))
  21395. (beginning-of-line))))
  21396. ;; At the end of a greater element, move to the beginning of
  21397. ;; the last element within.
  21398. ((and contents-end (>= (point) contents-end))
  21399. (goto-char (1- contents-end))
  21400. (org-backward-paragraph))
  21401. (t (goto-char (or post-affiliated begin))))
  21402. ;; Ensure we never leave point invisible.
  21403. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  21404. (defun org-forward-element ()
  21405. "Move forward by one element.
  21406. Move to the next element at the same level, when possible."
  21407. (interactive)
  21408. (cond ((eobp) (user-error "Cannot move further down"))
  21409. ((org-with-limited-levels (org-at-heading-p))
  21410. (let ((origin (point)))
  21411. (goto-char (org-end-of-subtree nil t))
  21412. (unless (org-with-limited-levels (org-at-heading-p))
  21413. (goto-char origin)
  21414. (user-error "Cannot move further down"))))
  21415. (t
  21416. (let* ((elem (org-element-at-point))
  21417. (end (org-element-property :end elem))
  21418. (parent (org-element-property :parent elem)))
  21419. (cond ((and parent (= (org-element-property :contents-end parent) end))
  21420. (goto-char (org-element-property :end parent)))
  21421. ((integer-or-marker-p end) (goto-char end))
  21422. (t (message "No element at point")))))))
  21423. (defun org-backward-element ()
  21424. "Move backward by one element.
  21425. Move to the previous element at the same level, when possible."
  21426. (interactive)
  21427. (cond ((bobp) (user-error "Cannot move further up"))
  21428. ((org-with-limited-levels (org-at-heading-p))
  21429. ;; At a headline, move to the previous one, if any, or stay
  21430. ;; here.
  21431. (let ((origin (point)))
  21432. (org-with-limited-levels (org-backward-heading-same-level 1))
  21433. ;; When current headline has no sibling above, move to its
  21434. ;; parent.
  21435. (when (= (point) origin)
  21436. (or (org-with-limited-levels (org-up-heading-safe))
  21437. (progn (goto-char origin)
  21438. (user-error "Cannot move further up"))))))
  21439. (t
  21440. (let* ((elem (org-element-at-point))
  21441. (beg (org-element-property :begin elem)))
  21442. (cond
  21443. ;; Move to beginning of current element if point isn't
  21444. ;; there already.
  21445. ((null beg) (message "No element at point"))
  21446. ((/= (point) beg) (goto-char beg))
  21447. (t (goto-char beg)
  21448. (skip-chars-backward " \r\t\n")
  21449. (unless (bobp)
  21450. (let ((prev (org-element-at-point)))
  21451. (goto-char (org-element-property :begin prev))
  21452. (while (and (setq prev (org-element-property :parent prev))
  21453. (<= (org-element-property :end prev) beg))
  21454. (goto-char (org-element-property :begin prev)))))))))))
  21455. (defun org-up-element ()
  21456. "Move to upper element."
  21457. (interactive)
  21458. (if (org-with-limited-levels (org-at-heading-p))
  21459. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  21460. (let* ((elem (org-element-at-point))
  21461. (parent (org-element-property :parent elem)))
  21462. (if parent (goto-char (org-element-property :begin parent))
  21463. (if (org-with-limited-levels (org-before-first-heading-p))
  21464. (user-error "No surrounding element")
  21465. (org-with-limited-levels (org-back-to-heading)))))))
  21466. (defun org-down-element ()
  21467. "Move to inner element."
  21468. (interactive)
  21469. (let ((element (org-element-at-point)))
  21470. (cond
  21471. ((memq (org-element-type element) '(plain-list table))
  21472. (goto-char (org-element-property :contents-begin element))
  21473. (forward-char))
  21474. ((memq (org-element-type element) org-element-greater-elements)
  21475. ;; If contents are hidden, first disclose them.
  21476. (when (org-invisible-p (line-end-position)) (org-cycle))
  21477. (goto-char (or (org-element-property :contents-begin element)
  21478. (user-error "No content for this element"))))
  21479. (t (user-error "No inner element")))))
  21480. (defun org-drag-element-backward ()
  21481. "Move backward element at point."
  21482. (interactive)
  21483. (let ((elem (or (org-element-at-point)
  21484. (user-error "No element at point"))))
  21485. (if (eq (org-element-type elem) 'headline)
  21486. ;; Preserve point when moving a whole tree, even if point was
  21487. ;; on blank lines below the headline.
  21488. (let ((offset (skip-chars-backward " \t\n")))
  21489. (unwind-protect (org-move-subtree-up)
  21490. (forward-char (- offset))))
  21491. (let ((prev-elem
  21492. (save-excursion
  21493. (goto-char (org-element-property :begin elem))
  21494. (skip-chars-backward " \r\t\n")
  21495. (unless (bobp)
  21496. (let* ((beg (org-element-property :begin elem))
  21497. (prev (org-element-at-point))
  21498. (up prev))
  21499. (while (and (setq up (org-element-property :parent up))
  21500. (<= (org-element-property :end up) beg))
  21501. (setq prev up))
  21502. prev)))))
  21503. ;; Error out if no previous element or previous element is
  21504. ;; a parent of the current one.
  21505. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  21506. (user-error "Cannot drag element backward")
  21507. (let ((pos (point)))
  21508. (org-element-swap-A-B prev-elem elem)
  21509. (goto-char (+ (org-element-property :begin prev-elem)
  21510. (- pos (org-element-property :begin elem))))))))))
  21511. (defun org-drag-element-forward ()
  21512. "Move forward element at point."
  21513. (interactive)
  21514. (let* ((pos (point))
  21515. (elem (or (org-element-at-point)
  21516. (user-error "No element at point"))))
  21517. (when (= (point-max) (org-element-property :end elem))
  21518. (user-error "Cannot drag element forward"))
  21519. (goto-char (org-element-property :end elem))
  21520. (let ((next-elem (org-element-at-point)))
  21521. (when (or (org-element-nested-p elem next-elem)
  21522. (and (eq (org-element-type next-elem) 'headline)
  21523. (not (eq (org-element-type elem) 'headline))))
  21524. (goto-char pos)
  21525. (user-error "Cannot drag element forward"))
  21526. ;; Compute new position of point: it's shifted by NEXT-ELEM
  21527. ;; body's length (without final blanks) and by the length of
  21528. ;; blanks between ELEM and NEXT-ELEM.
  21529. (let ((size-next (- (save-excursion
  21530. (goto-char (org-element-property :end next-elem))
  21531. (skip-chars-backward " \r\t\n")
  21532. (forward-line)
  21533. ;; Small correction if buffer doesn't end
  21534. ;; with a newline character.
  21535. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  21536. (org-element-property :begin next-elem)))
  21537. (size-blank (- (org-element-property :end elem)
  21538. (save-excursion
  21539. (goto-char (org-element-property :end elem))
  21540. (skip-chars-backward " \r\t\n")
  21541. (forward-line)
  21542. (point)))))
  21543. (org-element-swap-A-B elem next-elem)
  21544. (goto-char (+ pos size-next size-blank))))))
  21545. (defun org-drag-line-forward (arg)
  21546. "Drag the line at point ARG lines forward."
  21547. (interactive "p")
  21548. (dotimes (_ (abs arg))
  21549. (let ((c (current-column)))
  21550. (if (< 0 arg)
  21551. (progn
  21552. (beginning-of-line 2)
  21553. (transpose-lines 1)
  21554. (beginning-of-line 0))
  21555. (transpose-lines 1)
  21556. (beginning-of-line -1))
  21557. (org-move-to-column c))))
  21558. (defun org-drag-line-backward (arg)
  21559. "Drag the line at point ARG lines backward."
  21560. (interactive "p")
  21561. (org-drag-line-forward (- arg)))
  21562. (defun org-mark-element ()
  21563. "Put point at beginning of this element, mark at end.
  21564. Interactively, if this command is repeated or (in Transient Mark
  21565. mode) if the mark is active, it marks the next element after the
  21566. ones already marked."
  21567. (interactive)
  21568. (let (deactivate-mark)
  21569. (if (and (called-interactively-p 'any)
  21570. (or (and (eq last-command this-command) (mark t))
  21571. (and transient-mark-mode mark-active)))
  21572. (set-mark
  21573. (save-excursion
  21574. (goto-char (mark))
  21575. (goto-char (org-element-property :end (org-element-at-point)))))
  21576. (let ((element (org-element-at-point)))
  21577. (end-of-line)
  21578. (push-mark (org-element-property :end element) t t)
  21579. (goto-char (org-element-property :begin element))))))
  21580. (defun org-narrow-to-element ()
  21581. "Narrow buffer to current element."
  21582. (interactive)
  21583. (let ((elem (org-element-at-point)))
  21584. (cond
  21585. ((eq (car elem) 'headline)
  21586. (narrow-to-region
  21587. (org-element-property :begin elem)
  21588. (org-element-property :end elem)))
  21589. ((memq (car elem) org-element-greater-elements)
  21590. (narrow-to-region
  21591. (org-element-property :contents-begin elem)
  21592. (org-element-property :contents-end elem)))
  21593. (t
  21594. (narrow-to-region
  21595. (org-element-property :begin elem)
  21596. (org-element-property :end elem))))))
  21597. (defun org-transpose-element ()
  21598. "Transpose current and previous elements, keeping blank lines between.
  21599. Point is moved after both elements."
  21600. (interactive)
  21601. (org-skip-whitespace)
  21602. (let ((end (org-element-property :end (org-element-at-point))))
  21603. (org-drag-element-backward)
  21604. (goto-char end)))
  21605. (defun org-unindent-buffer ()
  21606. "Un-indent the visible part of the buffer.
  21607. Relative indentation (between items, inside blocks, etc.) isn't
  21608. modified."
  21609. (interactive)
  21610. (unless (eq major-mode 'org-mode)
  21611. (user-error "Cannot un-indent a buffer not in Org mode"))
  21612. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  21613. (unindent-tree
  21614. (lambda (contents)
  21615. (dolist (element (reverse contents))
  21616. (if (memq (org-element-type element) '(headline section))
  21617. (funcall unindent-tree (org-element-contents element))
  21618. (save-excursion
  21619. (save-restriction
  21620. (narrow-to-region
  21621. (org-element-property :begin element)
  21622. (org-element-property :end element))
  21623. (org-do-remove-indentation))))))))
  21624. (funcall unindent-tree (org-element-contents parse-tree))))
  21625. (defun org-make-options-regexp (kwds &optional extra)
  21626. "Make a regular expression for keyword lines.
  21627. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  21628. when non-nil, is a regexp matching keywords names."
  21629. (concat "^[ \t]*#\\+\\("
  21630. (regexp-opt kwds)
  21631. (and extra (concat (and kwds "\\|") extra))
  21632. "\\):[ \t]*\\(.*\\)"))
  21633. ;;; Finish up
  21634. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  21635. (lambda () (add-hook 'change-major-mode-hook
  21636. 'org-show-all 'append 'local)))
  21637. (provide 'org)
  21638. (run-hooks 'org-load-hook)
  21639. ;;; org.el ends here